diff options
119 files changed, 8164 insertions, 143 deletions
@@ -9,8 +9,11 @@ music, photos). It is not a public file-sharing network; public groups are an optional hub feature and are off on the reference deployment. **`docs/MESHBAY_DESIGN.md` is the architecture specification.** -`docs/MESHBAY_NODE_PROTOCOL.md` is the wire format. Everything else under -`docs/` is either an operational guide, or a superseded document kept for its +`docs/MESHBAY_NODE_PROTOCOL.md` is the wire format. `docs/MESHBAY_HTTP_API.md` +lists every route of the hub and of the node's control API; it is **generated** +by `docs/generate_http_api.py` from the routes and their docstrings, never edited +by hand, and `test_http_api_doc.py` fails when it drifts or when a route has no +docstring. Everything else under `docs/` is either an operational guide, or a superseded document kept for its cross-references and carrying a banner that says so. **`docs/QUICKSTART.md` and `docs/USERGUIDE.md` are the user documentation** — @@ -26,7 +29,7 @@ readily as what is (§15.2, §15.3); a feature that lands deletes its line there ``` meshbay/ ├── packages/ -│ ├── meshbay-common/ # Shared crypto + protocol — python3-meshbay-common RPM +│ ├── meshbay-common/ # Shared crypto + protocol — python3-meshbay-common RPM (LGPL; rest AGPL) │ ├── meshbay-hub/ # Hub server (FastAPI + PostgreSQL) — meshbay-hub RPM │ ├── meshbay-node/ # Node daemon + local UI — meshbay-node RPM │ ├── meshbay-client/ # Desktop client (Electron) @@ -132,6 +135,60 @@ Scope: `hub`, `node`, `common`, or omitted for cross-cutting - **Never log GEK, private keys, or plaintext passwords** — even at DEBUG level - **meshbay.org is internet-facing** — open port → test → close port + kill processes in same block +## Licensing + +**The protocol layer is LGPL-3.0-or-later, in every language; everything else is +AGPL-3.0-or-later.** The protocol layer is `meshbay-common` (`COPYING.LESSER` + +`COPYING` in its package) and, in the clients, the files whose first line is +`// SPDX-License-Identifier: LGPL-3.0-or-later`: `keyderive.js`, `crypto.js`, +`playlist-crypto.js`, `transport.js`, `transport-*.js`; `meshbay-client/src/` +`keyring.js`, `transcripts.js`, `argon2-wasm.js`; Android `keys/Kdf.kt`, +`Keyring.kt`, `Transcripts.kt`. A file without that line has its package's +licence: the AGPL (`LICENSE` at the root, copied into `meshbay-hub/` and +`meshbay-node/` because a wheel's `license-files` cannot reach outside its +package; into `static/licenses/` with the LGPL and GPL, so that every client +carries all three). + +- **An LGPL file depends only on LGPL files, permissive vendored code or the + platform.** One import of an AGPL module and a client using the layer is under + the AGPL after all. What a host must supply (`window.MeshBayPlatform`, + `window.meshbay`, a `Secrets` store) is reached as an injected interface, never + imported. `test_licensing.py` checks the closure. +- **The same piece has the same licence on every platform.** A port is LGPL when + its original is (Keyring.kt ↔ keyring.js ↔ keyderive.js), and stays on the AGPL + side when its original is part of a shell (DeviceKey.kt ↔ the device key in + `main.js`). A new protocol file is added to the list here, to the README, and + to `LGPL_FILES` in the test, with its SPDX line. The Android application adds a §7 permission for +Google Play services (`meshbay-android/LICENSE-EXCEPTION.txt`). + +- **A new dependency must be compatible with GPLv3.** Apache-2.0 already is + everywhere (watchdog, asyncpg, msgpack, okhttp), so nothing GPLv2-*only* can + come in. GPL dependencies exist and are fine for the AGPL packages (mutagen in + the node; PyAV's wheel grafts in libx264/libx265) — **but not for + `meshbay-common`**, whose point is to be usable under the LGPL: it imports + only permissive packages, and keeps doing so. The same goes for the LGPL files + in the clients. +- **Group applications may be under any licence** — + `static/licenses/APPLICATION-EXCEPTION.txt`, an AGPL §7 permission over a + named surface: the props and registry fields of §9.2–9.4, the exports of + `i18n.js`, `icon.js`, `file-utils.js`, `settings-ui.js`, `folder-tree.js`, + `style.css`'s classes and the catalogues' keys. **That list is a commitment to + third-party authors**: renaming or removing an export of those modules, or a + prop, breaks applications nobody here can see. Adding a module to it is a + decision, made in the exception file (the test reads the list from there). The + reference application (`helloworld-app*.js`) is 0BSD and imports nothing + outside that surface, so copying it never brings AGPL code along. +- **A proprietary dependency is a licensing change, not a dependency.** Play + services needed an exception; another one needs its own, and keeps the + Android application out of F-Droid until a flavour without it exists. +- **A vendored file** gets its entry in `static/vendor/PROVENANCE.md` and its + licence text in `static/vendor/LICENSES.txt`, in the same commit. +- **Notices are generated, not listed.** `packaging/third_party_notices.py` + writes `THIRD-PARTY-NOTICES.txt` from the metadata of the environment a build + ships (the deb/rpm venv, the frozen Windows node); a hand-kept list would be + wrong by the next upgrade. The ffmpeg the Windows build fetches is not a + Python package and keeps its own `packaging/win/LICENSE-ffmpeg.txt`. + ## Design, security findings and protocol — one document **`docs/MESHBAY_DESIGN.md` is the specification.** Everything that used to be @@ -149,6 +206,7 @@ that produced it. | Cryptography, key hierarchy, the group and chat envelopes | §4 | | The protocol: handshake, authorization, signed ops, leases, versioning | §5, and `docs/MESHBAY_NODE_PROTOCOL.md` for the wire format | | The node, the hub, the clients, the applications | §6, §7, §8, §9 | +| Every HTTP route, hub and node control API | `docs/MESHBAY_HTTP_API.md` (generated) | | Structural decisions that are not revisited | §14 | | What is built, what is not, what is open | §15 | | A reference to a document that no longer exists (`draft-v5 §5.2`, `apps.md §3`, …) — in git history, or in a document outside this repository | §16, the concordance — it maps every one onto its replacement section. The code itself cites `MESHBAY_DESIGN.md` and a section directly | @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. @@ -30,6 +30,9 @@ feature, and they are off on the reference deployment, [meshbay.org](https://mes - **How it works:** [`docs/MESHBAY_DESIGN.md`](docs/MESHBAY_DESIGN.md) is the architecture specification, and [`docs/MESHBAY_NODE_PROTOCOL.md`](docs/MESHBAY_NODE_PROTOCOL.md) the wire format. +- **Programming against it:** [`docs/MESHBAY_HTTP_API.md`](docs/MESHBAY_HTTP_API.md) + lists every route of the hub and of the node's control API, and + [`examples/`](examples/) has small Python programs that use them. ## Repository layout @@ -39,7 +42,8 @@ feature, and they are off on the reference deployment, [meshbay.org](https://mes | `packages/meshbay-hub/` | Hub server (FastAPI + PostgreSQL) and the web client it serves | | `packages/meshbay-node/` | Node daemon, its CLI and its local control UI | | `packaging/` | `.deb`, `.rpm` and Windows packaging, systemd units, Caddy and firewall configuration | -| `docs/` | Design specification, protocol, user and operator guides | +| `docs/` | Design specification, protocol, HTTP API, user and operator guides | +| `examples/` | Small Python programs using the hub, a node and its control API | | `man/` | Manual page for `meshbay-node` | | `site/` | Static website pages (not deployed) | | `poc/` | Early proof-of-concept scripts, kept for reference | @@ -57,6 +61,44 @@ pip install -e "packages/meshbay-common[dev]" -e "packages/meshbay-hub[dev]" \ .venv/bin/pytest ``` +## Licence + +MeshBay is free software. + +| Component | Licence | +|---|---| +| `packages/meshbay-common/` — the protocol and its cryptography, in Python | [LGPL-3.0-or-later](packages/meshbay-common/COPYING.LESSER) (with the [GPL-3.0](packages/meshbay-common/COPYING) it builds on) | +| The same layer in the clients: the files marked `SPDX-License-Identifier: LGPL-3.0-or-later` — in the interface, `keyderive.js`, `crypto.js`, `playlist-crypto.js`, `transport.js` and `transport-*.js`; on the desktop, `keyring.js`, `transcripts.js` and `argon2-wasm.js`; on Android, `keys/Kdf.kt`, `keys/Keyring.kt` and `keys/Transcripts.kt` | LGPL-3.0-or-later | +| Everything else — hub, node, the rest of the interface, the desktop and Android shells | [AGPL-3.0-or-later](LICENSE) | + +The line is the protocol. Whatever a program needs to speak to a hub and a node — +key derivation, the identity bundle, sealing and opening, what is signed, the +wire codec and the transport — is under the Lesser GPL, in every language it +exists in, so a client may use it whatever its own licence; changes to those +files themselves stay under the LGPL. A file without an SPDX line has its +package's licence. Talking to a hub or a node over the network needs none of +this code and carries no condition at all. The rest is under the Affero GPL: +whoever runs a modified hub or node for other people must offer them its +source. The licence texts travel with the interface, in `static/licenses/`. + +Group applications — the application store — may be under any licence, free +or not: the interface grants them that in an additional permission, +[`static/licenses/APPLICATION-EXCEPTION.txt`](packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt), +as long as they use it only through the documented application interface +(`docs/MESHBAY_DESIGN.md` §9.2–9.4 and the modules the permission names). The +reference application, `helloworld-app.js` and its settings pane, is under 0BSD: +copy it to start one. + +The Android application adds one permission to the AGPL, for the Google Play +services libraries the cast to a television goes through: +[`packages/meshbay-android/LICENSE-EXCEPTION.txt`](packages/meshbay-android/LICENSE-EXCEPTION.txt). + +Third-party code keeps its own licence: the vendored browser libraries are +listed in [`static/vendor/PROVENANCE.md`](packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md) +with their texts in `LICENSES.txt` beside it, and every package build carries a +`THIRD-PARTY-NOTICES.txt` generated from what it actually ships +([`packaging/third_party_notices.py`](packaging/third_party_notices.py)). + ## Source The repository is published read-only at <https://git.meshbay.org/>, and can be diff --git a/docs/MESHBAY_DESIGN.md b/docs/MESHBAY_DESIGN.md index 5d33f5f..fdf08f9 100644 --- a/docs/MESHBAY_DESIGN.md +++ b/docs/MESHBAY_DESIGN.md @@ -33,6 +33,7 @@ | `QUICKSTART.md` | one machine to a working group, for somebody who has installed nothing | | `USERGUIDE.md` | using a group and running a node, for the person who does either | | `MESHBAY_NODE_PROTOCOL.md` | the MNP wire format, message by message | +| `MESHBAY_HTTP_API.md` | every route of the hub and of the node's control API, generated from the code | | `transfers-v1.md` | the transfer system's failure-mode analysis, kept because a synthesis cannot carry "every way a slot can be lost" | | `playlists.md` | the playlist design and its interface in full, with what building it corrected (§9.10) | | `cast-smart-tv.md` | the DLNA/UPnP device backend — designed, not built (§11.4) | @@ -392,7 +393,11 @@ Four properties, each load-bearing: attempt is an audit event. 3. **The node's roster is the authority**, not hub membership. A hub that invents an account, adds it to a group and mints it a token gets - `not_authorized_for_group`. + `not_authorized_for_group`. The Members list says the same: it shows the + accounts the node has admitted (the sealed group roster, §11.7 of the protocol). + One the hub counts as a member but that has not presented its code yet is + shown to the owner alone, as waiting for its code; when the roster cannot be + read, the hub's list is shown. 4. **Wrapping happens on every connection.** Nothing is stored per member, so key rotation propagates by itself and revocation actually takes effect. (Rotating the key after a revocation is still required — the ex-member holds the current @@ -1564,7 +1569,8 @@ the whole tree or presents an empty directory to the next scan. Both propagate a though the owner erased their library. So a root has two independent runtime states: -- **`ejected`** — operator-controlled, persisted in `roster.db`. +- **`ejected`** — set by the operator, or by the safety net below; persisted in + `roster.db`, with which of the two set it. - **`available`** — computed as `not ejected and is_live()`. This is what clients and the indexer see. @@ -1585,12 +1591,21 @@ let the following scan read the empty mount point as an erased library. It lives hand-written config must not be rewritten because a USB drive was unplugged. **Auto-eject is the safety net.** If a `removable` root's path disappears, the -availability sweep sets `ejected` as though the operator had clicked it, and -reports it so the daemon persists it. Nothing is deleted: index entries, cached +availability sweep sets `ejected` and reports it so the daemon persists it, marked +as the safety net's. Nothing is deleted: index entries, cached metadata, thumbnails, chat history referencing those files and app directory configurations all survive, the last flagged as temporarily invalid rather than wrong. +**The safety net's eject undoes itself; the operator's never does.** At startup +and at every reconcile, an auto-ejected root whose path is readable again is +checked against what the hash cache knows was under it: a few of those files, +at the same path with the same size and mtime. One found, and the root is +plugged back and rescanned, like a plug. None found, and it stays ejected: an +empty mount point or another drive mounted in its place is exactly what the eject +protects the index from. The case this serves is ordinary: a node started with +the session, before the desktop has mounted its USB drives. + ### 6.3 Indexing The index is **content-addressed**: `GroupIndex` is keyed by blake3, so the same @@ -1888,7 +1903,8 @@ is not authentication: any local process can reach it, as can a page in the operator's browser via DNS rebinding — and this API re-initialises group keys, issues invitations and reads the audit log. There is no server-rendered dashboard; the desktop client's Node page and the CLI are the two consumers, and each -operation endpoint is one `_op(...)` line onto `ops` (§5.4). +operation endpoint is one `_op(...)` line onto `ops` (§5.4). Its routes are listed +in `MESHBAY_HTTP_API.md`. **The node's own controls are not on MNP.** Its status — which lists every group on the machine with each root's absolute path — settings, roster, denylist and @@ -1950,6 +1966,8 @@ an operator-signed op. ## 7. The hub +Its routes are listed in `MESHBAY_HTTP_API.md`. + ### 7.1 Role — chosen, not minimal Hub minimisation was considered and **deferred, and may be dropped** (decision D4). @@ -2070,10 +2088,17 @@ A group's **identity is its UUID**, everywhere: the route, the node's configurat membership. A group **name is unique per owner account**, case-insensitively and trimmed, enforced by a functional unique index; two different owners may each have a `photos`. Names are displayed as `name@owner`, which is a label plus a create-time -check and **not an addressing scheme**. The handle is hub-local: the same +check and **not an identity**. The handle is hub-local: the same `name@owner` on two federated hubs are different groups, and a federated row shows its source hub rather than an account. +The client also accepts the handle in the address, as an alias for the UUID +(§8.4): `#/name@owner`, optionally followed by a path inside the group. It is +resolved **in the client, against the account's own `/v1/groups/mine`**, and no +hub route answers "which group is called this" — so a handle tells nobody +anything they could not already see, and cannot be used to probe for a group. +A rename breaks the handle links to a group and none of its `#/group/<id>` ones. + `visibility` and `join_policy` are the two independent axes described in §3.5. `join_policy` is read from the node's own configuration, never from the hub. @@ -2527,6 +2552,26 @@ that decides where the hub is or fetches the API relative to the page origin. That is a testable invariant, and it is what any feature adding third-party egress must preserve — which is one of the reasons enrichment is node-side (§6.5). +**Inside the application, every route is a fragment** (`#/…`). What follows `#` +is never sent to a server, so it is in no hub or proxy log and no `Referer`; +that is what lets an invitation carry its code (§3.4), and it is why the same +router runs unchanged on `app://meshbay` and in the Android WebView, where no +server could answer a path. Two forms name a group: + +| Route | Meaning | +|---|---| +| `#/group/<uuid>` | the group — every link the application draws | +| `#/name@owner` | the same group by its handle (§7.3); the address shows this form while a group is open, written with `replace` so it is not a history entry | +| `#/name@owner/<root>/<dir>/<file>` | a file: Files opens on its folder and the file is downloaded. A folder instead of a file opens Files there. The path is taken out of the address once acted on, so a reload does not download twice | + +The owner is after the **last** `@` (a username cannot contain one); each path +segment is percent-decoded on its own. Opened signed out, the sign-in form +stands in for the page and the address is left alone, so signing in lands on +it. A download started this way has no user gesture behind it, so where a browser +offers a Save As dialog it takes the fallback a dialog refused for want of a +gesture already takes (`file-utils.js` `_openDownloadTarget`): streamed to the +download folder. `static/group-link.js`. + ### 8.5 Downloads and streaming **Downloads go to disk, never through RAM, on every platform.** There are three @@ -2772,6 +2817,7 @@ destructures what it needs — a new application does not get a bespoke prop lis | `transportRef`, `gekRef` | **refs**, never state, so a reconnect does not re-render every application | | `deviceReady` | **the exception, and why it is a prop.** A ref not re-rendering is right for a transport reached into on demand and wrong for a *fact about the connection* an application renders from | | `mayUpload` | computed once; a second derivation would eventually disagree with the first | +| `linkFor(entry \| folderPath)` | the `#/name@owner/path` link "Copy link" puts on the clipboard (§8.4), or null where none can be named. The group page builds it from the hub's row; Search from each result's own group and unprefixed path. An application offers the action only when this returns a link, and copies with `copy-link.js` `copyLink` | An application that needs local state owns it. One pattern is worth carrying: **any notion of "current location within the group" resets on group change**, because a @@ -2880,6 +2926,16 @@ There is no folder-browsing protocol and this does not add one. application with no toolbar renders none — an empty band still holds a strip of the page open. +9. **Licence.** An application may be under any licence, provided it reaches the + interface only through the *application interface*: the props of §9.2, the + registry fields above, the exports of `i18n.js`, `icon.js`, `file-utils.js`, + `settings-ui.js` and `folder-tree.js`, `style.css`'s classes and the + catalogues' keys (`static/licenses/APPLICATION-EXCEPTION.txt`, an AGPL §7 + permission). Importing any other module of the interface makes the + application a work based on it, under the AGPL. Its registry line and its + catalogue entries are changes to the interface and stay AGPL. Starting from + `helloworld-app.js`, which is 0BSD, brings no AGPL code along. + No protocol change, no hub change, no daemon change. Steps 4 and 7 are the only node-side and test-side touches, and both are allow-lists. diff --git a/docs/MESHBAY_HTTP_API.md b/docs/MESHBAY_HTTP_API.md new file mode 100644 index 0000000..74b9d77 --- /dev/null +++ b/docs/MESHBAY_HTTP_API.md @@ -0,0 +1,233 @@ +# MeshBay HTTP API + +> **Generated** by `docs/generate_http_api.py` from the routes themselves. Do not +> edit this file: change the route's docstring and run the script again. A test +> fails when the two disagree. + +MeshBay has two HTTP APIs: the **hub's**, for accounts, groups and signaling, and +the **node's control API**, which only its own machine reaches. Files, the index +and chat do not use either: they travel between a client and a node over MNP +(`MESHBAY_NODE_PROTOCOL.md`). Why each API is shaped as it is, who may call +what and what the hub must never see are in `MESHBAY_DESIGN.md`; this file lists +what exists. + +`examples/` has small Python programs that use both. + +## Hub + +Under the hub's address, `https://meshbay.org` on the reference deployment. The +hub also serves the web application at `/` and `/app/`, which are not listed. + +| Auth | What the request carries | +|---|---| +| none | No session. Any credential is in the request itself, as the route says | +| user | `Authorization: Bearer`, a person's session. A node's token is refused | +| user or node | A person's session, or a node daemon's token from `/v1/nodes/auth` | +| node | A node daemon's token only | +| moderator | A person's session, for an account with the moderator or admin role | +| admin | A person's session, for an account with the admin role | +| peer hub | Another hub's MHP token. Every route answers 503 unless federation is enabled | + +### Instance + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/v1/hub/info` | none | Versions and the instance policy a client needs before signing in. | +| GET | `/v1/hub/pubkey` | none | Hub Ed25519 public key PEM — cached by nodes on first contact. | +| GET | `/v1/hub/version` | none | Version check endpoint for clients to detect updates. | + +### Accounts + +| Method | Path | Auth | What | +|---|---|---|---| +| POST | `/v1/users/register` | none | Create an account. | +| POST | `/v1/users/verify-email` | none | Verify a registration email with the code received by mail. | +| POST | `/v1/users/me/bundle-pepper` | user | The pepper, for a session that has just been given the passphrase again. | +| POST | `/v1/users/login` | none | Sign in with the auth key derived from the passphrase. | +| POST | `/v1/users/devices` | user | Register a device's hub authentication key. | +| GET | `/v1/users/devices` | user or node | The account's registered devices. | +| DELETE | `/v1/users/devices/{device_id}` | user | Retire a device's hub key. | +| POST | `/v1/users/auth` | none | Sign in with a registered device key. | +| POST | `/v1/users/token/refresh` | none | Exchange a refresh token for a new session. | +| GET | `/v1/users/me` | user or node | The signed-in account: id, name, e-mail, role, status. | +| PATCH | `/v1/users/me` | user | Update the signed-in account. | +| POST | `/v1/users/verify-email-change` | user | Confirm an email change with the code sent to the new address. | +| POST | `/v1/users/logout` | none | End this session on the hub, not only in the browser. | +| POST | `/v1/users/me/sessions/revoke` | user | Sign out everywhere: no refresh token of this account renews any more. | +| POST | `/v1/users/password` | user | Change the passphrase, proving the current one. | +| POST | `/v1/users/password/reset-request` | none | Send a reset code by e-mail, when the username and the address match. | +| POST | `/v1/users/password/reset` | none | Set a new passphrase with the code received by e-mail. | +| GET | `/v1/users/me/preferences` | user or node | The account's stored interface preferences. | +| PUT | `/v1/users/me/preferences/{key:path}` | user | Store one interface preference. | +| DELETE | `/v1/users/me/preferences/{key:path}` | user | Remove one interface preference. | +| PUT | `/v1/users/me/node_key` | user | Link a node daemon's Ed25519 public key to the operator's account. | +| DELETE | `/v1/users/me/node_key` | user or node | Remove the linked node key from the operator's account. | +| DELETE | `/v1/users/me` | user | Erase your own account. | +| GET | `/v1/users/{username}/pubkeys` | user or node | Resolve a username to its account id, and its node's linking key. | + +### Nodes + +| Method | Path | Auth | What | +|---|---|---|---| +| POST | `/v1/nodes/mnp-token` | user | Mint the short-lived token a member presents to a node in the MNP handshake. | +| POST | `/v1/nodes/auth` | none | Authenticate a node daemon via Ed25519 challenge-response. | +| POST | `/v1/nodes/announce` | user or node | Register a node record. | +| GET | `/v1/nodes/{node_id}` | user or node | A node's public record: owner, key, endpoint hint. | + +### Groups + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/v1/groups/mine` | user or node | List groups the current user belongs to. | +| GET | `/v1/groups/invitations` | user or node | Groups somebody added this account to, waiting for it to say yes. | +| POST | `/v1/groups/{group_id}/invitation/accept` | user | Accept an invitation: the account becomes a member of the group. | +| POST | `/v1/groups/{group_id}/invitation/decline` | user | Decline an invitation to a group. | +| POST | `/v1/groups/{group_id}/activity` | user or node | Bump a group's last_activity_at. | +| GET | `/v1/groups/{group_id}/nodes` | user or node | Return online nodes that serve a group (for WebRTC connection). | +| GET | `/v1/groups` | none | List/search public groups — local and optionally federated. | +| GET | `/v1/groups/{group_id}/members` | user or node | A group's members, for its members only. | +| POST | `/v1/groups/{group_id}/join` | user | Join an open group. | +| POST | `/v1/groups` | user | Create a group, owned by the caller. | +| DELETE | `/v1/groups/{group_id}/members/{username}` | user | Remove someone from a group. | +| POST | `/v1/groups/{group_id}/leave` | user | Leave a group you are a member of. | +| PATCH | `/v1/groups/{group_id}` | user | Change the group's description. | +| POST | `/v1/groups/{group_id}/members/{username}` | user or node | Add an account to a group the caller owns. | +| POST | `/v1/groups/{group_id}/mute` | user | Turn this group's notifications on or off, for this account. | +| DELETE | `/v1/groups/{group_id}` | user | Delete a group. | +| POST | `/v1/groups/{group_id}/invite-notify` | user | Send an invitation email to a member who was just invited. | +| GET | `/v1/groups/{group_id}/hosts` | user | The nodes that host a group or asked to, for its owner. | +| POST | `/v1/groups/{group_id}/hosts/{node_id}` | user | Approve a node that asked to host this group. | +| DELETE | `/v1/groups/{group_id}/hosts/{node_id}` | user | Withdraw an approval, or turn a request down. | + +### Invitation links + +| Method | Path | Auth | What | +|---|---|---|---| +| POST | `/v1/groups/{group_id}/invite-links` | user or node | Mint the ticket for a link whose node half already exists. | +| GET | `/v1/groups/{group_id}/invite-links` | user or node | The owner's view: the links nobody has used yet, masked. | +| DELETE | `/v1/groups/{group_id}/invite-links/{link_id}` | user or node | Take the ticket back. | +| POST | `/v1/invite-links/preview` | user | What the confirmation screen shows before anyone joins anything. | +| POST | `/v1/invite-links/redeem` | user | Membership for the first account that asks, once — and the same answer again for that account, because a second tab or a reload is the same person. | + +### Revocation and the node socket + +| Method | Path | Auth | What | +|---|---|---|---| +| WS | `/v1/nodes/ws` | none | Persistent WebSocket connection for nodes, authenticated by the node's token in the first message. | +| POST | `/v1/nodes/{node_id}/incoming` | user or node | Signal a node that a client wants to connect (NAT punch coordination). | +| POST | `/v1/admin/revoke` | admin | Revoke a user or group. | + +### Moderation + +| Method | Path | Auth | What | +|---|---|---|---| +| POST | `/v1/reports` | user | Report a file of a public group, as a member of that group. | +| GET | `/v1/blocklist` | node | The content blocklist, a page at a time, for a node hosting a public group. | +| GET | `/v1/admin/blocklist` | admin | The content blocklist. | +| POST | `/v1/admin/blocklist` | admin | Add a content hash (BLAKE3) to the blocklist. | +| DELETE | `/v1/admin/blocklist/{content_hash}` | admin | Remove a content hash from the blocklist. | +| GET | `/v1/admin/reports` | moderator | Hashes waiting for a decision, oldest first, with what was said about them. | +| POST | `/v1/admin/reports/{content_hash}/block` | admin | Block reported content and close its reports. | +| POST | `/v1/admin/reports/{content_hash}/dismiss` | admin | Dismiss the reports on a piece of content. | + +### Federation (MHP) + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/mhp/info` | peer hub | Return this hub's identity for peer registration. | +| GET | `/mhp/directory` | peer hub | This hub's public groups, for a peer hub presenting an MHP token. | +| POST | `/mhp/directory` | peer hub | A peer hub's public groups, pushed with a single-use MHP token. | +| POST | `/mhp/revoke` | peer hub | Act on a revocation from a peer hub. | +| POST | `/mhp/peers` | admin | Admin: register a trusted peer hub. | +| GET | `/mhp/peers` | admin | Admin: list registered peer hubs. | + +### Health + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/v1/health` | none | Liveness: database reachable, version, connected nodes. | + +### Signaling + +| Method | Path | Auth | What | +|---|---|---|---| +| POST | `/v1/nodes/{node_id}/webrtc/offer` | user or node | Browser sends WebRTC SDP offer for a node. | + +### Administration + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/v1/admin/settings` | moderator | Instance-wide policy an admin controls from the panel. | +| PATCH | `/v1/admin/settings` | admin | Change instance policy. | +| GET | `/v1/admin/mail` | moderator | Is the hub still sending, and how much of the hour is left. | +| GET | `/v1/admin/stats` | moderator | Account, group and node counts. | +| GET | `/v1/admin/users` | moderator | Search and list accounts. | +| GET | `/v1/admin/users/{user_id}` | moderator | One account, with its group count. | +| PATCH | `/v1/admin/users/{user_id}` | moderator | Change an account's status, or its role (admin only). | +| DELETE | `/v1/admin/users/{user_id}` | admin | Erase an account, and every group it owns. | +| GET | `/v1/admin/groups` | moderator | List groups with their member counts. | +| PATCH | `/v1/admin/groups/{group_id}` | moderator | Change a group's status. | +| GET | `/v1/admin/nodes` | moderator | Registered nodes, with the address the hub saw them announce from. | +| GET | `/v1/admin/logs` | moderator | The connection log, filtered by account and event. | + +### Notifications + +| Method | Path | Auth | What | +|---|---|---|---| +| GET | `/v1/notifications` | user or node | The account's notifications, newest first. | +| POST | `/v1/notifications/{notification_id}/read` | user or node | Dismiss one. | +| DELETE | `/v1/notifications/{notification_id}` | user or node | Dismiss one. | +| DELETE | `/v1/notifications` | user or node | Throw them all away. | +| POST | `/v1/notifications/read-all` | user or node | Dismiss every one — the same thing as `DELETE ""`, under the name an older client knows it by. | + +## Node control API + +`http://127.0.0.1:<ui_port>`, port 18000 unless `ui_port` in `node.toml` says +otherwise, and never on another address. Every request carries the token the +daemon writes to `<data_dir>/ui-token` (`~/.local/share/meshbay/ui-token` on +Linux), as the `X-MeshBay-Token` header or the `t` query parameter. The daemon +draws a new one at each start and deletes the file when it stops. + +| Method | Path | What | +|---|---|---| +| GET | `/api/status` | The daemon's state, and what it still needs: a linked key, a group, an operator, a group key. | +| DELETE | `/api/unlink` | Unlink the node's key from its hub account. | +| GET | `/api/groups` | The groups this node hosts, with live status, and whether an operator is paired. | +| POST | `/api/groups/attach` | Host a group that exists on the hub: add it to node.toml with its first folder, then reload. | +| POST | `/api/groups/detach` | Stop hosting a group: remove it from node.toml, then reload. | +| DELETE | `/api/groups/{group_id}/files/{file_id}` | Delete a file from the group's folder on disk. | +| GET | `/api/denylist` | What the node currently refuses. | +| POST | `/api/denylist/clear` | Drop denylist entries: all of them, or one identifier. | +| GET | `/api/index-cache` | Size of the index cache. | +| POST | `/api/index-cache/prune` | Drop index cache rows that no longer match a file on disk. | +| POST | `/api/groups/{group_id}/video/rematch` | Forget the automatic matches of the group's videos, so they are looked up again. | +| GET | `/api/groups/{group_id}/files` | The group's files, from its index. | +| GET | `/api/peers` | The connected peers. | +| GET | `/api/audit` | The audit log, filtered by time, account and event. | +| POST | `/api/operator/pair` | A one-time code that pairs an application as this node's operator. | +| GET | `/api/roster` | The pinned identities, for one group or all. | +| POST | `/api/groups/{group_id}/invites` | An invitation code for one account, for this group. | +| POST | `/api/groups/{group_id}/invite-links` | A whole invitation link: the node's code, then the hub's ticket. | +| DELETE | `/api/groups/{group_id}/invite-links/{invite_id}` | Take an invitation link back, on the node and on the hub. | +| GET | `/api/resolve` | Map a username to an account id, through the hub. | +| POST | `/api/members/{user_id}/revoke` | Stop serving the group key to a member. | +| POST | `/api/members/{user_id}/unpin` | Forget a pinned identity, so the person can pair again with a new key. | +| GET | `/api/groups/{group_id}/chat` | What the operator needs to decide anything about the group's chat. | +| POST | `/api/groups/{group_id}/chat/epoch` | Open a new chat epoch. | +| POST | `/api/groups/{group_id}/chat/encrypt-history` | Re-encrypt the messages written before the group's chat was encrypted. | +| POST | `/api/groups/{group_id}/chat/prune` | Delete chat messages older than a number of days. | +| POST | `/api/groups/{group_id}/gek` | Generate the group key, or rotate it with ?rotate=true. | +| POST | `/api/groups/{group_id}/roots` | Add a folder to a group. | +| PATCH | `/api/groups/{group_id}/roots/{root_name}` | Make a folder writable or removable, or not. | +| PUT | `/api/groups/{group_id}/roots/{root_name}/eject` | Eject a removable folder so its disk can be unplugged. | +| PUT | `/api/groups/{group_id}/roots/{root_name}/plug` | Bring an ejected folder back. | +| DELETE | `/api/groups/{group_id}/roots/{root_name}` | Remove a folder from a group. | +| GET | `/api/groups/{group_id}/index-status` | One group's indexing progress. | +| GET | `/api/index-status` | Every group's indexing progress. | +| PUT | `/api/groups/{group_id}/apps` | Which applications members see for the group. | +| POST | `/api/reload` | Reload node.toml. | +| POST | `/api/shutdown` | Stop the daemon. | +| GET | `/api/node-settings` | The node's effective settings. | +| PUT | `/api/node-settings` | Change node settings, written to roster.db and node.toml. | +| GET | `/api/transfers` | Live transfer leases and queue depth. | +| PUT | `/api/groups/{group_id}/transfer-limits` | How many transfers one member may run at once in this group. | diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index ce1eec1..ea75cab 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -359,7 +359,7 @@ A healthy node reads roughly like this: ``` hub https://meshbay.org (user yourname) node key 7mK2p...= -daemon running — ok +daemon running node_id 82.65.x.x:0 groups 1 files 4213 peers 1 config /home/you/.config/meshbay/node.toml diff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.md index 97ea679..ea81c76 100644 --- a/docs/USERGUIDE.md +++ b/docs/USERGUIDE.md @@ -297,6 +297,19 @@ file browser — sort, select, download, preview. - **Right-click a file or folder** for the same actions as the toolbar, listing only the ones that apply to it. On a ticked row the menu acts on everything ticked, like the toolbar does. +- **A link to a group, a folder or a file.** While a group is open the address + bar shows `https://<hub>/#/name@owner` — the name under the group's title. + Add a path after it to point inside the group: + `#/name@owner/root/folder/photo.jpg` downloads that file, and a folder opens + Files there. Only members get anywhere with such a link — anyone else is told + the group is unknown — and someone not signed in is asked to sign in first, + then taken where the link pointed. Renaming the group breaks these links. +- **Copy link** gives you that address for one file or folder: right-click it, + or tick it and use the link button in the toolbar (the way on a phone). Music + has it in a track's menu (**⋯** on a phone), Photos when you right-click a + photo or in the photo viewer's bar, and the video player and file preview + have a link button next to Download. Search offers the same, pointing at the + group each result comes from. ### Chat diff --git a/docs/generate_http_api.py b/docs/generate_http_api.py new file mode 100644 index 0000000..d064519 --- /dev/null +++ b/docs/generate_http_api.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +""" +Write docs/MESHBAY_HTTP_API.md from the routes of the hub and of the node's +control API. + + python docs/generate_http_api.py + +Generated rather than written: a list of a hundred routes kept by hand is wrong +by the next one added. `test_http_api_doc.py` fails when the file and the code +disagree, and when a route has no docstring to describe it. +""" + +import inspect +import re +import sys +from pathlib import Path + +from fastapi.routing import APIRoute, APIWebSocketRoute + +OUT = Path(__file__).resolve().parent / "MESHBAY_HTTP_API.md" + +# The hub's routers, by module, in the order the hub includes them. +SECTIONS = { + "hub": "Instance", + "users": "Accounts", + "nodes": "Nodes", + "groups": "Groups", + "invite_links": "Invitation links", + "revocation": "Revocation and the node socket", + "moderation": "Moderation", + "federation": "Federation (MHP)", + "health": "Health", + "signaling": "Signaling", + "admin": "Administration", + "notifications": "Notifications", +} + +# Strongest first: a route is labelled by the first dependency it carries. +AUTH = [ + ("require_admin", "admin"), + ("require_moderator", "moderator"), + ("require_node_scope", "node"), + ("require_user_scope", "user"), + ("get_current_user", "user or node"), + ("_decode_token", "token"), + ("_federation_open", "peer hub"), +] + +AUTH_LEGEND = """\ +| Auth | What the request carries | +|---|---| +| none | No session. Any credential is in the request itself, as the route says | +| user | `Authorization: Bearer`, a person's session. A node's token is refused | +| user or node | A person's session, or a node daemon's token from `/v1/nodes/auth` | +| node | A node daemon's token only | +| moderator | A person's session, for an account with the moderator or admin role | +| admin | A person's session, for an account with the admin role | +| peer hub | Another hub's MHP token. Every route answers 503 unless federation is enabled | +""" + +HEADER = """\ +# MeshBay HTTP API + +> **Generated** by `docs/generate_http_api.py` from the routes themselves. Do not +> edit this file: change the route's docstring and run the script again. A test +> fails when the two disagree. + +MeshBay has two HTTP APIs: the **hub's**, for accounts, groups and signaling, and +the **node's control API**, which only its own machine reaches. Files, the index +and chat do not use either: they travel between a client and a node over MNP +(`MESHBAY_NODE_PROTOCOL.md`). Why each API is shaped as it is, who may call +what and what the hub must never see are in `MESHBAY_DESIGN.md`; this file lists +what exists. + +`examples/` has small Python programs that use both. +""" + +HUB_INTRO = """\ + +## Hub + +Under the hub's address, `https://meshbay.org` on the reference deployment. The +hub also serves the web application at `/` and `/app/`, which are not listed. + +""" + +NODE_INTRO = """\ +## Node control API + +`http://127.0.0.1:<ui_port>`, port 18000 unless `ui_port` in `node.toml` says +otherwise, and never on another address. Every request carries the token the +daemon writes to `<data_dir>/ui-token` (`~/.local/share/meshbay/ui-token` on +Linux), as the `X-MeshBay-Token` header or the `t` query parameter. The daemon +draws a new one at each start and deletes the file when it stops. + +| Method | Path | What | +|---|---|---| +""" + + +def flatten(routes): + for r in routes: + if hasattr(r, "original_router"): + yield from flatten(r.original_router.routes) + elif isinstance(r, (APIRoute, APIWebSocketRoute)): + yield r + + +def summary(route) -> str: + """The docstring's first sentence.""" + doc = inspect.getdoc(route.endpoint) or "" + first = " ".join(doc.split("\n\n")[0].split()) + return re.split(r"(?<=[.!?])\s+(?=[A-Z`])", first)[0].replace("|", "\\|") + + +def method(route) -> str: + if isinstance(route, APIWebSocketRoute): + return "WS" + return ", ".join(sorted(route.methods - {"HEAD"})) + + +def auth(route) -> str: + names = set() + + def walk(dependant): + for d in dependant.dependencies: + if d.call is not None: + names.add(getattr(d.call, "__name__", "")) + walk(d) + + walk(route.dependant) + return next((label for name, label in AUTH if name in names), "none") + + +def hub_routes() -> list: + from meshbay_hub.app import create_app + return [r for r in flatten(create_app().routes) + if r.endpoint.__module__.rsplit(".", 1)[-1] != "webapp"] + + +def node_routes() -> list: + from meshbay_node.ui.app import create_ui_app + return list(flatten(create_ui_app({}).routes)) + + +def render() -> str: + out = [HEADER, HUB_INTRO, AUTH_LEGEND] + by_module: dict[str, list] = {} + for r in hub_routes(): + by_module.setdefault(r.endpoint.__module__.rsplit(".", 1)[-1], []).append(r) + for module, routes in by_module.items(): + out.append(f"\n### {SECTIONS.get(module, module.replace('_', ' ').capitalize())}\n\n") + out.append("| Method | Path | Auth | What |\n|---|---|---|---|\n") + for r in routes: + out.append(f"| {method(r)} | `{r.path}` | {auth(r)} | {summary(r)} |\n") + out.append("\n" + NODE_INTRO) + for r in node_routes(): + out.append(f"| {method(r)} | `{r.path}` | {summary(r)} |\n") + return "".join(out) + + +if __name__ == "__main__": + OUT.write_text(render(), encoding="utf-8") + print(f"wrote {OUT}", file=sys.stderr) diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..f13e37a --- /dev/null +++ b/examples/README.md @@ -0,0 +1,38 @@ +# Examples + +Small programs that talk to MeshBay the way the application does, without the +application. The values to change are variables at the top of each script. + +| File | What it does | +|---|---| +| `meshbay_session.py` | The shared part: signs in to the hub, connects to a node serving the group over WebRTC, and completes the handshake. Used by the scripts below | +| `list_groups.py` | Lists your groups, `up` when a node serving the group is connected to the hub, `down` otherwise | +| `create_group.py` | Creates a group on the hub and hosts it on the node running on this machine, through the node's control API on 127.0.0.1 | +| `download.py` | Downloads one file from a group and saves it decrypted | +| `upload.py` | Uploads one file into a folder of a group | + +```bash +# From the root of the repository +python3 -m venv .venv +.venv/bin/pip install -e packages/meshbay-common aiortc httpx argon2-cffi + +# Edit the variables at the top of the script, then +cd examples +../.venv/bin/python download.py +``` + +The hub is `https://meshbay.org` by default. Paths in a group start with the +root's name, then the folders, as in the group's file browser: `FILE_PATH = +"shared/2024/beach.jpg"`, `DEST_DIR = "shared/2024"`. An upload needs a root the +operator made writable, and never replaces a file: on a name clash the node +picks a free name and says which. + +Why not curl: files never pass through the hub. They travel over a WebRTC +DataChannel, straight between you and the node, encrypted under the group key. +Signing in, the handshake with the node and the encryption all happen in the +scripts. + +They need the node to keep a copy of your identity keys, sealed so that only +your passphrase and your hub account can open it. That is the case when +*Browser access* is on in the application's settings, or once you have opened +the group in a browser. diff --git a/examples/create_group.py b/examples/create_group.py new file mode 100755 index 0000000..c03e5e8 --- /dev/null +++ b/examples/create_group.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +""" +Create a group and host it on the node running on this machine. + +Run it on the node's machine, as the user the node runs as: the node's control +API only answers on 127.0.0.1, with a token the node writes to its data folder. +USERNAME must be the hub account the node is linked to. +""" + +import sys +import time +from pathlib import Path + +import httpx +from meshbay_session import auth_key + +HUB = "https://meshbay.org" +USERNAME = "alice" +PASSPHRASE = "your passphrase" +GROUP_NAME = "Family Photos" +DESCRIPTION = "" +FOLDER = "~/Pictures/shared" # the folder to share, created if missing +WRITABLE = True # whether members may upload into it + +NODE_API = "http://127.0.0.1:18000" # ui_port in node.toml +TOKEN_FILE = "~/.local/share/meshbay/ui-token" + + +def call(client: httpx.Client, method: str, path: str, **kwargs) -> dict: + r = client.request(method, path, **kwargs) + if r.status_code >= 400: + sys.exit(f"{method} {path} refused: {r.text}") + return r.json() + + +def main() -> None: + # 1. Create the group on the hub. It is only a name and a member list there. + with httpx.Client(base_url=HUB, timeout=30) as hub: + login = call(hub, "POST", "/v1/users/login", json={ + "username": USERNAME, "auth_key": auth_key(USERNAME, PASSPHRASE)}) + auth = {"Authorization": f"Bearer {login['access_token']}"} + body = {"name": GROUP_NAME, "visibility": "private", "join_policy": "invite"} + if DESCRIPTION: + body["description"] = DESCRIPTION + group_id = call(hub, "POST", "/v1/groups", headers=auth, json=body)["group_id"] + print(f"Created {GROUP_NAME!r} on the hub ({group_id})") + + # The node changes its token at every start: read it now. + token = Path(TOKEN_FILE).expanduser().read_text().strip() + with httpx.Client(base_url=NODE_API, timeout=30, + headers={"X-MeshBay-Token": token}) as node: + + # 2. Ask the node to host it. The node writes the group into node.toml, + # then indexes the folder. + call(node, "POST", "/api/groups/attach", json={ + "name": group_id, "shared_dir": FOLDER, + "writable": WRITABLE, "join_policy": "invite"}) + while True: + hosted = call(node, "GET", "/api/groups") + group = next((g for g in hosted["groups"] if g["id"] == group_id), None) + if group: + break + print("Waiting for the node to index the folder...") + time.sleep(2) + + # 3. The group key. It never leaves the node, except wrapped for a member. + call(node, "POST", f"/api/groups/{group_id}/gek") + + # 4. First group on this node: a one-time code makes your application + # its operator. + pair = None if hosted["operator_paired"] else call(node, "POST", "/api/operator/pair") + + print(f"Hosted on this node: {group['file_count']} files indexed") + if pair: + print(f"Operator code, to enter when the application asks: {pair['code']} " + f"(valid until {pair['expires_at']})") + + +if __name__ == "__main__": + main() diff --git a/examples/download.py b/examples/download.py new file mode 100755 index 0000000..b5359d2 --- /dev/null +++ b/examples/download.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Download one file from a MeshBay group, as a member, without a browser.""" + +import asyncio +import math +import sys + +from meshbay_common.webcrypto import chunk_key_aes, decrypt_chunk_aes +from meshbay_session import connect + +HUB = "https://meshbay.org" +USERNAME = "alice" +PASSPHRASE = "your passphrase" +GROUP = "Family Photos" # the group's name, as shown in the sidebar +NODE_ID = "" # empty: the first node online for this group +FILE_PATH = "shared/2024/beach.jpg" # root name, then folders, then the file name +OUTPUT = "beach.jpg" + +CHUNK_SIZE = 1024 * 1024 # the node serves files in 1 MiB chunks + + +async def main() -> None: + session = await connect(HUB, USERNAME, PASSPHRASE, GROUP, NODE_ID) + + entry = next((e for e in await session.index() + if f"{e['path']}/{e['name']}" == FILE_PATH), None) + if entry is None: + sys.exit(f"No file {FILE_PATH!r} in this group") + + # Each chunk is encrypted under its own key, derived from the group key. + chunks = max(1, math.ceil(entry["size"] / CHUNK_SIZE)) + tr = await session.open_transfer("download", entry["size"], chunks) + file_hash = bytes.fromhex(entry["id"]) + with open(OUTPUT, "wb") as out: + for i in range(chunks): + session.ch.send({"type": "file_req", "v": "0.1", "file_id": entry["id"], + "chunk_index": i, "tr": tr}) + chunk = await session.ch.recv("file_chunk") + out.write(decrypt_chunk_aes(chunk_key_aes(session.gek, file_hash, i), + chunk["nonce"], chunk["ct"])) + print(f"\r{i + 1}/{chunks} chunks", end="", flush=True) + session.close_transfer(tr) + print(f"\nSaved {OUTPUT} ({entry['size']} bytes)") + await session.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/list_groups.py b/examples/list_groups.py new file mode 100755 index 0000000..61773e2 --- /dev/null +++ b/examples/list_groups.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""List a user's groups, and whether a node serving each one is up.""" + +import sys + +import httpx +from meshbay_session import auth_key + +HUB = "https://meshbay.org" +USERNAME = "alice" +PASSPHRASE = "your passphrase" + + +def main() -> None: + with httpx.Client(base_url=HUB, timeout=30) as hub: + r = hub.post("/v1/users/login", + json={"username": USERNAME, "auth_key": auth_key(USERNAME, PASSPHRASE)}) + if r.status_code != 200: + sys.exit(f"Sign-in refused: {r.text}") + auth = {"Authorization": f"Bearer {r.json()['access_token']}"} + groups = hub.get("/v1/groups/mine", headers=auth).json()["groups"] + + # "up" means a node serving the group is connected to the hub right now. + # It does not prove that this machine can reach that node. + for g in groups: + state = "up" if g["node_online"] else "down" + print(f"{state:<6}{g['name']} (@{g['owner_username']})") + + +if __name__ == "__main__": + main() diff --git a/examples/meshbay_session.py b/examples/meshbay_session.py new file mode 100644 index 0000000..86bf17e --- /dev/null +++ b/examples/meshbay_session.py @@ -0,0 +1,251 @@ +""" +A member's session with a MeshBay node, shared by the examples. + +The hub only signs you in and relays the WebRTC offer. Everything after that +goes straight to the node, encrypted under the group key. +""" + +import asyncio +import base64 +import hashlib +import json +import os +import struct +import sys +import time + +import httpx +import msgpack +from aiortc import RTCConfiguration, RTCIceServer, RTCPeerConnection, RTCSessionDescription +from argon2.low_level import Type, hash_secret_raw +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC +from cryptography.hazmat.primitives.serialization import load_der_private_key +from meshbay_common import MNP_VERSION +from meshbay_common.crypto import pk_to_b64, unwrap_gek_aes +from meshbay_common.groupbox import PURPOSE_ACK, PURPOSE_INDEX, unseal +from meshbay_common.handshake import ( + MNP_MIN_SUPPORTED, + challenge_transcript, + check_version, + handshake_transcript, + make_proof, + verify_proof, + webrtc_binding, +) +from meshbay_common.join import join_transcript + + +def b64(data: bytes) -> str: + return base64.b64encode(data).decode() + + +def unb64(text: str) -> bytes: + return base64.b64decode(text) + + +def hkdf(key: bytes, info: str) -> bytes: + return HKDF(algorithm=hashes.SHA256(), length=32, salt=None, + info=info.encode()).derive(key) + + +# Keys derived from the passphrase, the same way as keyderive.js + +def auth_key(username: str, passphrase: str) -> str: + """What the hub checks at sign-in. The passphrase itself never leaves here.""" + salt = hashlib.sha256(f"meshbay:auth:v1:{username}".encode()).digest() + return b64(PBKDF2HMAC(algorithm=hashes.SHA512(), length=32, salt=salt, + iterations=600_000).derive(passphrase.encode())) + + +def bundle_master_key(username: str, passphrase: str, user_id: str, pepper_b64: str) -> bytes: + """Argon2id of the passphrase, mixed with the pepper the hub returns at sign-in.""" + salt = hashlib.sha256(f"meshbay:bundle:v2:{username}".encode()).digest()[:16] + a = hash_secret_raw(passphrase.encode(), salt, time_cost=3, memory_cost=131072, + parallelism=1, hash_len=32, type=Type.ID) + return hkdf(a + unb64(pepper_b64), f"meshbay:bundle-master:v3|{user_id}") + + +def open_identity(bundle_b64: str, master: bytes, user_id: str, node_pk: str): + """Open your identity keys for this node. The node stores them sealed.""" + raw = unb64(bundle_b64) # "MBK3", pepper version, nonce, ciphertext + key = hkdf(master, f"meshbay:bundle:v3|node|{node_pk}") + aad = f"meshbay:bundle:v3|{user_id}|{node_pk}".encode() + keys = json.loads(AESGCM(key).decrypt(raw[5:17], raw[17:], aad)) + sk_ed = load_der_private_key(unb64(keys["skEd"]), password=None) + sk_x = load_der_private_key(unb64(keys["skX"]), password=None) + return sk_ed, sk_x + + +# MNP over a WebRTC DataChannel + +class Channel: + """Frames are a 4-byte big-endian length followed by msgpack.""" + + def __init__(self, dc): + self.dc = dc + self.buf = bytearray() + self.queue: asyncio.Queue = asyncio.Queue() + dc.on("message", self._on_message) + + def _on_message(self, data): + self.buf.extend(data if isinstance(data, bytes) else data.encode()) + while len(self.buf) >= 4: + size = struct.unpack(">I", self.buf[:4])[0] + if len(self.buf) < 4 + size: + break + self.queue.put_nowait(msgpack.unpackb(bytes(self.buf[4:4 + size]), raw=False)) + del self.buf[:4 + size] + + def send(self, msg: dict) -> None: + data = msgpack.packb(msg, use_bin_type=True) + self.dc.send(struct.pack(">I", len(data)) + data) + + async def recv(self, *types: str) -> dict: + """The next message of one of these types. Pushes from the node are skipped.""" + while True: + msg = await asyncio.wait_for(self.queue.get(), timeout=60) + if msg.get("type") == "error": + sys.exit(f"Node refused: {msg.get('detail') or msg}") + if msg.get("type") in types: + return msg + + +def dtls_fingerprint(sdp: str) -> bytes: + for line in sdp.splitlines(): + if line.startswith("a=fingerprint:sha-256 "): + return bytes.fromhex(line.split(" ", 1)[1].strip().replace(":", "")) + sys.exit("No DTLS fingerprint in the SDP") + + +class Session: + """An authenticated connection to one node, for one group.""" + + def __init__(self, pc, ch: Channel, group_id: str, gek: bytes): + self.pc = pc + self.ch = ch + self.group_id = group_id + self.gek = gek + + async def index(self) -> list[dict]: + """The group's files. Each entry's path is its root name, then its folders.""" + self.ch.send({"type": "index_sync", "v": "0.1"}) + msg = await self.ch.recv("index_sync") + return unseal(self.gek, PURPOSE_INDEX, "index_sync", self.group_id, msg)["entries"] + + async def open_transfer(self, kind: str, size: int, chunks: int) -> str: + """Ask the node for a transfer slot and wait until it is granted.""" + tr = os.urandom(16).hex() + self.ch.send({"type": "transfer_open", "v": "0.1", "tr": tr, "kind": kind, + "bytes": size, "chunks": chunks}) + while (await self.ch.recv("transfer_state"))["state"] != "granted": + print("Waiting for a free transfer slot on the node...") + return tr + + def close_transfer(self, tr: str) -> None: + self.ch.send({"type": "transfer_close", "v": "0.1", "tr": tr, "reason": "done"}) + + async def close(self) -> None: + await self.pc.close() + + +async def connect(hub_url: str, username: str, passphrase: str, + group_name: str, node_id: str = "") -> Session: + async with httpx.AsyncClient(base_url=hub_url, timeout=30) as hub: + + # 1. Sign in to the hub. + r = await hub.post("/v1/users/login", json={ + "username": username, "auth_key": auth_key(username, passphrase)}) + if r.status_code != 200: + sys.exit(f"Sign-in refused: {r.text}") + login = r.json() + auth = {"Authorization": f"Bearer {login['access_token']}"} + user_id = (await hub.get("/v1/users/me", headers=auth)).json()["user_id"] + master = bundle_master_key(username, passphrase, user_id, login["bundle_pepper"]) + + # 2. Find the group, and a node that serves it. + groups = (await hub.get("/v1/groups/mine", headers=auth)).json()["groups"] + group = next((g for g in groups if g["name"] == group_name), None) + if group is None: + sys.exit(f"You are not a member of a group named {group_name!r}") + group_id = group["id"] + nodes = (await hub.get(f"/v1/groups/{group_id}/nodes", headers=auth)).json()["nodes"] + node = next((n for n in nodes if not node_id or n["node_id"] == node_id), None) + if node is None: + sys.exit("No node serving this group is online") + + # 3. Open a DataChannel to the node. The hub relays the offer and the + # answer, and nothing after that. + pc = RTCPeerConnection(RTCConfiguration( + iceServers=[RTCIceServer(urls="stun:stun.l.google.com:19302")])) + dc = pc.createDataChannel("mnp", ordered=True) + ch = Channel(dc) + opened = asyncio.Event() + dc.on("open", opened.set) + await pc.setLocalDescription(await pc.createOffer()) + offer_sdp = pc.localDescription.sdp + r = await hub.post(f"/v1/nodes/{node['node_id']}/webrtc/offer", headers=auth, + json={"sdp": offer_sdp, "ice_candidates": []}) + if r.status_code != 200: + sys.exit(f"The node did not answer: {r.text}") + answer_sdp = r.json()["sdp"] + await pc.setRemoteDescription(RTCSessionDescription(sdp=answer_sdp, type="answer")) + await asyncio.wait_for(opened.wait(), timeout=30) + binding = webrtc_binding(dtls_fingerprint(offer_sdp), dtls_fingerprint(answer_sdp)) + + # 4. Handshake. The node gets a short-lived token for this group only, + # never the hub session token. + r = await hub.post("/v1/nodes/mnp-token", headers=auth, + json={"node_pk": node["pk_node"], "group_id": group_id}) + mnp_token = r.json()["mnp_token"] + + nonce_c = os.urandom(32) + ch.send({"type": "handshake", "v": MNP_VERSION, "v_min": MNP_MIN_SUPPORTED, + "token": mnp_token, "group_id": group_id, "nonce": b64(nonce_c)}) + challenge = await ch.recv("handshake_challenge") + check_version(challenge["v"], challenge["v_min"]) + nonce_s = unb64(challenge["nonce"]) + node_pk = challenge["node_pk"] + # The node signs its challenge over this connection: node_pk is proved here. + Ed25519PublicKey.from_public_bytes(unb64(node_pk)).verify( + unb64(challenge["sig"]), challenge_transcript(group_id, nonce_c, nonce_s, binding)) + + # 5. Your identity keys for this node, which it keeps sealed for you. + ch.send({"type": "keypair_bundle_fetch", "v": "0.1"}) + kp = await ch.recv("keypair_bundle_resp") + if not kp.get("found"): + sys.exit("This node keeps no copy of your keys. Turn on Browser access in " + "the application's settings, or open the group once in a browser.") + sk_ed, sk_x = open_identity(kp["bundle_enc"], master, user_id, node_pk) + + # 6. The group key. The node recognises your identity and wraps the key for it. + pk_ed = pk_to_b64(sk_ed.public_key()) + pk_x = b64(sk_x.public_key().public_bytes_raw()) + ts = int(time.time()) + ch.send({"type": "join_request", "v": "0.1", "group_id": group_id, + "pk_ed25519": pk_ed, "pk_x25519": pk_x, "code": "", "ts": ts, + "sig": b64(sk_ed.sign(join_transcript( + node_pk_b64=node_pk, group_id=group_id, user_id=user_id, + pk_ed25519_b64=pk_ed, pk_x25519_b64=pk_x, nonce_node=nonce_s, ts=ts)))}) + joined = await ch.recv("join_result") + if not joined.get("ok") or not joined.get("gek"): + sys.exit(f"The node did not give the group key: {joined.get('reason')}") + gek = unwrap_gek_aes(joined, sk_x.private_bytes_raw(), + sk_x.public_key().public_bytes_raw()) + + # 7. Prove the group key, then check that the node proves it too. + ch.send({"type": "handshake_response", "v": "0.1", "proof": b64(make_proof( + gek, "client", group_id, nonce_c, nonce_s, binding))}) + ack = await ch.recv("handshake_ack") + if not verify_proof(gek, unb64(ack["proof"]), "node", group_id, nonce_c, nonce_s, binding): + sys.exit("The node does not hold the group key") + Ed25519PublicKey.from_public_bytes(unb64(ack["node_pk"])).verify( + unb64(ack["sig"]), handshake_transcript("node", group_id, nonce_c, nonce_s, binding)) + if ack["node_pk"] != node_pk: + sys.exit("The node changed identity during the handshake") + unseal(gek, PURPOSE_ACK, "handshake_ack", group_id, ack) + + return Session(pc, ch, group_id, gek) diff --git a/examples/upload.py b/examples/upload.py new file mode 100755 index 0000000..518b5ec --- /dev/null +++ b/examples/upload.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Upload one file to a MeshBay group, as a member, without a browser.""" + +import asyncio +import math +import os + +from meshbay_common.groupbox import PURPOSE_UPLOAD, unseal +from meshbay_common.protocol import file_upload_wire +from meshbay_session import connect + +HUB = "https://meshbay.org" +USERNAME = "alice" +PASSPHRASE = "your passphrase" +GROUP = "Family Photos" # the group's name, as shown in the sidebar +NODE_ID = "" # empty: the first node online for this group +LOCAL_FILE = "beach.jpg" # the file to send +DEST_DIR = "shared/2024" # root name, then folders; the root must be writable + +CHUNK_SIZE = 48 * 1024 # what fits in one DataChannel message +WINDOW = 32 # chunks sent ahead of the node's acks + + +async def main() -> None: + session = await connect(HUB, USERNAME, PASSPHRASE, GROUP, NODE_ID) + + filename = os.path.basename(LOCAL_FILE) + size = os.path.getsize(LOCAL_FILE) + chunks = max(1, math.ceil(size / CHUNK_SIZE)) + tr = await session.open_transfer("upload", size, chunks) + upload_id = os.urandom(16).hex() + + # The file name, the folder and the bytes are sealed under the group key. + # Only the upload id and the chunk numbers stay in clear. + acked = 0 + ack = {} + with open(LOCAL_FILE, "rb") as f: + for i in range(chunks): + if i - acked >= WINDOW: + ack = await session.ch.recv("file_upload_ack") + acked += 1 + msg = file_upload_wire(session.gek, session.group_id, upload_id=upload_id, + chunk_index=i, total_chunks=chunks, filename=filename, + data=f.read(CHUNK_SIZE), dir=DEST_DIR) + session.ch.send({**msg, "tr": tr}) + print(f"\r{i + 1}/{chunks} chunks", end="", flush=True) + while acked < chunks: + ack = await session.ch.recv("file_upload_ack") + acked += 1 + session.close_transfer(tr) + + # The node never overwrites: on a name clash it picks a free one. + done = unseal(session.gek, PURPOSE_UPLOAD, "file_upload_ack", session.group_id, ack) + print(f"\nStored as {done['dir']}/{done['stored_as']} ({size} bytes)") + await session.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/packages/meshbay-android/LICENSE-EXCEPTION.txt b/packages/meshbay-android/LICENSE-EXCEPTION.txt new file mode 100644 index 0000000..bd526f6 --- /dev/null +++ b/packages/meshbay-android/LICENSE-EXCEPTION.txt @@ -0,0 +1,24 @@ +MeshBay for Android — additional permission under GNU AGPL version 3, section 7 +============================================================================== + +The MeshBay Android application is free software under the GNU Affero General +Public License, version 3 or (at your option) any later version — see LICENSE +at the root of the repository — with the following additional permission. +(Its protocol files, those marked SPDX-License-Identifier: LGPL-3.0-or-later, +are under the GNU Lesser GPL instead, which needs no such permission.) + + If you modify this Program, or any covered work, by linking or combining + it with the Google Play services client libraries (the Maven group + com.google.android.gms, or a modified version of those libraries), + containing parts covered by the terms of the licence under which Google + distributes them, the licensors of this Program grant you additional + permission to convey the resulting work. Corresponding Source for a + non-source form of such a combination shall not include the source code + for the parts of those libraries used as well as that of the covered work. + +Why: casting to a television goes through Google's cast sender SDK, which is +not free software and is linked into the application. Without this permission, +nobody but the copyright holders could lawfully distribute the application as +it is built, including from a fork. The permission covers those libraries only; +nothing else in the application is exempt from the AGPL, and anybody who +distributes a modified version may remove it (section 7). diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt index fc446b9..0fa63d6 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/MainActivity.kt @@ -6,9 +6,11 @@ import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle +import android.os.SystemClock import android.util.Log import android.view.View import android.view.ViewGroup +import android.view.ViewTreeObserver import android.view.WindowInsets import android.webkit.ConsoleMessage import android.webkit.PermissionRequest @@ -66,6 +68,7 @@ class MainActivity : Activity() { root = FrameLayout(this) setContentView(root) applyInsets(root) + if (savedInstanceState == null && Build.VERSION.SDK_INT >= 31) holdSplash() // A WebView too old for the page's crypto would fail at the first // handshake; say so before loading anything. @@ -255,6 +258,22 @@ class MainActivity : Activity() { catch (e: android.content.ActivityNotFoundException) { Log.w(Bridge.TAG, "no browser for $url") } } + /** + * Android 12+ shows the launcher icon until the first frame is drawn, which + * on a warm process is a flash. Holding that frame keeps it up long enough + * to be seen; the WebView loads underneath in the meantime. + */ + private fun holdSplash() { + val until = SystemClock.uptimeMillis() + SPLASH_MS + root.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener { + override fun onPreDraw(): Boolean { + if (SystemClock.uptimeMillis() < until) return false + root.viewTreeObserver.removeOnPreDrawListener(this) + return true + } + }) + } + /** Edge-to-edge is enforced from Android 15: keep the page clear of the bars and the keyboard. */ private fun applyInsets(view: View) { view.setOnApplyWindowInsetsListener { v, insets -> @@ -296,4 +315,8 @@ class MainActivity : Activity() { if (::web.isInitialized) { root.removeView(web); web.destroy() } super.onDestroy() } + + companion object { + private const val SPLASH_MS = 500L + } } diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt index 30f094e..404efcb 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Kdf.kt @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. package org.meshbay.client.keys import org.bouncycastle.crypto.digests.SHA256Digest diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt index fa8ff71..9a7dd9f 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Keyring.kt @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. package org.meshbay.client.keys import org.bouncycastle.crypto.agreement.X25519Agreement diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt index 4d183f7..cf20a0b 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/keys/Transcripts.kt @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. package org.meshbay.client.keys import org.json.JSONObject diff --git a/packages/meshbay-client/package.json b/packages/meshbay-client/package.json index 8a1fec7..a13c0ab 100644 --- a/packages/meshbay-client/package.json +++ b/packages/meshbay-client/package.json @@ -53,6 +53,10 @@ { "from": "../../packaging/win/ensure-node-path.ps1", "to": "ensure-node-path.ps1" + }, + { + "from": "../../LICENSE", + "to": "LICENSE.txt" } ] }, diff --git a/packages/meshbay-client/src/argon2-wasm.js b/packages/meshbay-client/src/argon2-wasm.js index c68e994..4660414 100644 --- a/packages/meshbay-client/src/argon2-wasm.js +++ b/packages/meshbay-client/src/argon2-wasm.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * Argon2id for the main process, from the page's own WebAssembly build. * diff --git a/packages/meshbay-client/src/keyring.js b/packages/meshbay-client/src/keyring.js index ec37fd4..c9997aa 100644 --- a/packages/meshbay-client/src/keyring.js +++ b/packages/meshbay-client/src/keyring.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * The account's keys in the desktop application: the bundle master key `M` and * the identity on every node, held here and never handed to the page. diff --git a/packages/meshbay-client/src/main.js b/packages/meshbay-client/src/main.js index a2a7a86..f582b57 100644 --- a/packages/meshbay-client/src/main.js +++ b/packages/meshbay-client/src/main.js @@ -1269,11 +1269,11 @@ function registerBridge() { // // The renderer never sees the session token. It names an operation and this // process executes it — the same pattern as hub:fetch. The token is read - // from the daemon's data directory, cached for the lifetime of this process, - // and never exposed through the preload. + // from the daemon's data directory on every call and never exposed through + // the preload. Not cached: the daemon writes a new one each run and deletes + // it on stop, so a cached copy answered 401 after every node restart, and an + // operation asked before any page had called detect() had none at all. - let _nodeToken = null; - let _nodePort = 18000; let _nodePairingCode = null; function nodeConfigPath() { @@ -1305,16 +1305,20 @@ function registerBridge() { } } + function nodeEndpoint() { + const nc = readNodeConfig(); + const token = readNodeToken(nc ? nc.dataDir : meshbayDataDir()); + return token ? { token, port: nc ? nc.uiPort : 18000 } : null; + } + handle('node:detect', async () => { const nc = readNodeConfig(); if (!nc) return { detected: false, configured: false }; const token = readNodeToken(nc.dataDir); if (!token) return { detected: false, configured: true }; - _nodeToken = token; - _nodePort = nc.uiPort; try { const r = await fetch( - `http://127.0.0.1:${_nodePort}/api/status?t=${_nodeToken}`, + `http://127.0.0.1:${nc.uiPort}/api/status?t=${token}`, { signal: AbortSignal.timeout(3000) }); if (!r.ok) return { detected: false, configured: true }; const status = await r.json(); @@ -1889,8 +1893,6 @@ function registerBridge() { const READY = ['running', 'waiting_for_node_key', 'waiting_for_account', 'waiting_for_hub', 'starting']; if (!READY.includes(status.status)) return null; - _nodeToken = token; - _nodePort = port; return { pk_node_ed25519: status.pk_node_ed25519 || '', status: status.status, version: status.version || '' }; } catch { return null; } @@ -2235,10 +2237,11 @@ function registerBridge() { handle('node:op', async (_e, name, args) => { const op = Object.hasOwn(NODE_OPS, String(name)) ? NODE_OPS[String(name)] : null; if (!op) throw new Error(`Refused: unknown node operation ${String(name)}`); - if (!_nodeToken) throw new Error('Node not detected'); + const endpoint = nodeEndpoint(); + if (!endpoint) throw new Error('Node not detected'); const [method, apiPath, body] = await op(anObject(args)); const sep = apiPath.includes('?') ? '&' : '?'; - const url = `http://127.0.0.1:${_nodePort}${apiPath}${sep}t=${_nodeToken}`; + const url = `http://127.0.0.1:${endpoint.port}${apiPath}${sep}t=${endpoint.token}`; const init = { method }; if (body !== undefined && body !== null) { init.headers = { 'Content-Type': 'application/json' }; diff --git a/packages/meshbay-client/src/transcripts.js b/packages/meshbay-client/src/transcripts.js index 8b0f6ef..a58cb24 100644 --- a/packages/meshbay-client/src/transcripts.js +++ b/packages/meshbay-client/src/transcripts.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * What a node identity signs, built here from named fields — never bytes the * page chose. diff --git a/packages/meshbay-common/COPYING b/packages/meshbay-common/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/packages/meshbay-common/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/packages/meshbay-common/COPYING.LESSER b/packages/meshbay-common/COPYING.LESSER new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/packages/meshbay-common/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/packages/meshbay-common/pyproject.toml b/packages/meshbay-common/pyproject.toml index f8035ba..dca3aa0 100644 --- a/packages/meshbay-common/pyproject.toml +++ b/packages/meshbay-common/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["hatchling"] +requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files` build-backend = "hatchling.build" [project] @@ -7,6 +7,8 @@ name = "meshbay-common" version = "0.18.0" description = "MeshBay shared cryptographic primitives and protocol types" requires-python = ">=3.12" +license = "LGPL-3.0-or-later" +license-files = ["COPYING", "COPYING.LESSER"] dependencies = [ "cryptography>=43.0", "PyJWT>=2.9", diff --git a/packages/meshbay-hub/LICENSE b/packages/meshbay-hub/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/packages/meshbay-hub/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/packages/meshbay-hub/pyproject.toml b/packages/meshbay-hub/pyproject.toml index c927242..643363e 100644 --- a/packages/meshbay-hub/pyproject.toml +++ b/packages/meshbay-hub/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["hatchling"] +requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files` build-backend = "hatchling.build" [project] @@ -7,6 +7,8 @@ name = "meshbay-hub" version = "0.18.0" description = "MeshBay Hub — identity authority and group registry server" requires-python = ">=3.12" +license = "AGPL-3.0-or-later" +license-files = ["LICENSE"] dependencies = [ "meshbay-common>=0.10.0", "fastapi>=0.115", diff --git a/packages/meshbay-hub/src/meshbay_hub/api/admin.py b/packages/meshbay-hub/src/meshbay_hub/api/admin.py index dbda197..1cb8bf9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/admin.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/admin.py @@ -213,6 +213,7 @@ async def admin_stats( current_user: User = Depends(require_moderator), db: AsyncSession = Depends(get_db), ): + """Account, group and node counts.""" # Deleted accounts are tombstoned rather than dropped, so that the # connection log stays readable. They are not users any more and must not be # counted as any: a hub whose user count only ever rises is measuring its @@ -244,6 +245,7 @@ async def admin_list_users( offset: int = 0, limit: int = Query(default=50, le=200), ): + """Search and list accounts.""" query = (select(User).where(User.status != "deleted") .order_by(User.created_at.desc())) if q: @@ -279,6 +281,7 @@ async def admin_get_user( current_user: User = Depends(require_moderator), db: AsyncSession = Depends(get_db), ): + """One account, with its group count.""" user = await db.get(User, user_id) if not user: raise HTTPException(status_code=404, detail="User not found") @@ -310,6 +313,7 @@ async def admin_patch_user( current_user: User = Depends(require_moderator), db: AsyncSession = Depends(get_db), ): + """Change an account's status, or its role (admin only).""" user = await db.get(User, user_id) if not user: raise HTTPException(status_code=404, detail="User not found") @@ -473,6 +477,7 @@ async def admin_list_groups( offset: int = 0, limit: int = Query(default=50, le=200), ): + """List groups with their member counts.""" query = ( select( Group, @@ -524,6 +529,7 @@ async def admin_patch_group( current_user: User = Depends(require_moderator), db: AsyncSession = Depends(get_db), ): + """Change a group's status.""" group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") @@ -624,6 +630,7 @@ async def admin_list_logs( offset: int = 0, limit: int = Query(default=50, le=200), ): + """The connection log, filtered by account and event.""" query = ( select(IPLog, User.username) .outerjoin(User, IPLog.user_id == User.id) diff --git a/packages/meshbay-hub/src/meshbay_hub/api/federation.py b/packages/meshbay-hub/src/meshbay_hub/api/federation.py index 755639e..e737a1c 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/federation.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/federation.py @@ -190,6 +190,7 @@ async def export_directory( db: AsyncSession = Depends(get_db), authorization: str = Header(...), ): + """This hub's public groups, for a peer hub presenting an MHP token.""" try: await _verify_mhp_token(authorization.removeprefix("Bearer "), db) except Exception as e: @@ -232,6 +233,7 @@ async def receive_directory( authorization: str = Header(...), db: AsyncSession = Depends(get_db), ): + """A peer hub's public groups, pushed with a single-use MHP token.""" try: payload = await _verify_mhp_token( authorization.removeprefix("Bearer "), db, single_use=True) diff --git a/packages/meshbay-hub/src/meshbay_hub/api/groups.py b/packages/meshbay-hub/src/meshbay_hub/api/groups.py index fc117bf..d58e32c 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/groups.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/groups.py @@ -120,6 +120,7 @@ async def accept_invitation( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Accept an invitation: the account becomes a member of the group.""" inv = await db.get(GroupInvitation, (group_id, current_user.id)) group = await db.get(Group, group_id) if inv is None or group is None or group.status != "active": @@ -141,6 +142,7 @@ async def decline_invitation( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Decline an invitation to a group.""" inv = await db.get(GroupInvitation, (group_id, current_user.id)) if inv is None: raise HTTPException(status_code=404, detail="No such invitation") @@ -281,6 +283,7 @@ async def group_members( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """A group's members, for its members only.""" group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") @@ -319,6 +322,7 @@ async def join_group( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Join an open group.""" group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") @@ -421,6 +425,7 @@ async def create_group( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Create a group, owned by the caller. No node hosts it yet.""" # Being listed and being open are one question, not two. # # A public group that admits nobody is a contradiction: it is in the @@ -643,6 +648,7 @@ async def add_group_member( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """Add an account to a group the caller owns. Also called by the owner's node.""" # `get_current_user`, not `require_user_scope`: the node calls this after a # CLI `member invite` so the group becomes visible in the invitee's SPA # (commit 0443cf8). The node authenticates with a node-scoped token, and the @@ -713,6 +719,7 @@ async def delete_group( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Delete a group. Its owner only.""" group = await db.get(Group, group_id) if not group: raise HTTPException(status_code=404, detail="Group not found") @@ -827,6 +834,7 @@ async def list_hosts( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """The nodes that host a group or asked to, for its owner.""" from meshbay_hub.api.revocation import is_node_connected await _owned(db, group_id, current_user) rows = (await db.execute( diff --git a/packages/meshbay-hub/src/meshbay_hub/api/health.py b/packages/meshbay-hub/src/meshbay_hub/api/health.py index 516856b..abb1b53 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/health.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/health.py @@ -13,6 +13,7 @@ router = APIRouter(tags=["health"]) @router.get("/v1/health") async def health(db: AsyncSession = Depends(get_db)): + """Liveness: database reachable, version, connected nodes.""" await db.execute(text("SELECT 1")) return { "status": "ok", diff --git a/packages/meshbay-hub/src/meshbay_hub/api/hub.py b/packages/meshbay-hub/src/meshbay_hub/api/hub.py index 2a3efaf..d1246a3 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/hub.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/hub.py @@ -22,6 +22,7 @@ def set_config(cfg: HubConfig) -> None: @router.get("/info") async def hub_info(db: AsyncSession = Depends(get_db)): + """Versions and the instance policy a client needs before signing in.""" engine = get_engine() return { "hub_version": __version__, diff --git a/packages/meshbay-hub/src/meshbay_hub/api/moderation.py b/packages/meshbay-hub/src/meshbay_hub/api/moderation.py index 038f310..ecca4df 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/moderation.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/moderation.py @@ -244,6 +244,7 @@ async def admin_list_blocklist( db: AsyncSession = Depends(get_db), limit: int = 500, ): + """The content blocklist.""" result = await db.execute( select(ContentBlocklist) .order_by(ContentBlocklist.added_at.desc()) @@ -269,6 +270,7 @@ async def admin_add_blocklist( current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): + """Add a content hash (BLAKE3) to the blocklist.""" if not _is_hash(body.content_hash): raise HTTPException(status_code=422, detail="content_hash must be 64 hex chars (blake3)") existing = await db.get(ContentBlocklist, body.content_hash) @@ -291,6 +293,7 @@ async def admin_remove_blocklist( current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): + """Remove a content hash from the blocklist.""" entry = await db.get(ContentBlocklist, content_hash) if not entry: raise HTTPException(status_code=404, detail="Hash not in blocklist") @@ -344,6 +347,7 @@ async def admin_block_reported( current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): + """Block reported content and close its reports.""" await _decide(db, content_hash, "blocked", current_user.username) reasons = Counter((await db.execute(select(ContentReport.reason).where( ContentReport.content_hash == content_hash))).scalars().all()) @@ -363,6 +367,7 @@ async def admin_dismiss_reported( current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): + """Dismiss the reports on a piece of content.""" await _decide(db, content_hash, "dismissed", current_user.username) await db.commit() return {"status": "dismissed", "hash": content_hash} diff --git a/packages/meshbay-hub/src/meshbay_hub/api/nodes.py b/packages/meshbay-hub/src/meshbay_hub/api/nodes.py index decd20e..b158621 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/nodes.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/nodes.py @@ -250,6 +250,7 @@ async def get_node( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """A node's public record: owner, key, endpoint hint.""" node = await db.get(Node, node_id) if not node: raise HTTPException(status_code=404, detail="Node not found") diff --git a/packages/meshbay-hub/src/meshbay_hub/api/notifications.py b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py index d96ec18..e4bac2e 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/notifications.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/notifications.py @@ -43,6 +43,7 @@ async def list_notifications( offset: int = Query(default=0, ge=0), unread_only: bool = False, ): + """The account's notifications, newest first.""" query = select(Notification).where(Notification.user_id == current_user.id) if unread_only: query = query.where(Notification.read == False) # noqa: E712 diff --git a/packages/meshbay-hub/src/meshbay_hub/api/revocation.py b/packages/meshbay-hub/src/meshbay_hub/api/revocation.py index 5a33d77..2499374 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/revocation.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/revocation.py @@ -438,7 +438,8 @@ async def _authorize_node_ws(token: str, claimed_id: str, claimed_groups) -> tup @router.websocket("/v1/nodes/ws") async def node_websocket(ws: WebSocket): """ - Persistent WebSocket connection for nodes. + Persistent WebSocket connection for nodes, authenticated by the node's token in the + first message. Finding C2: this used to take `node_id` and `group_ids` straight from the client's first message, with no check that the authenticated user owned that diff --git a/packages/meshbay-hub/src/meshbay_hub/api/users.py b/packages/meshbay-hub/src/meshbay_hub/api/users.py index 9326bfb..795a902 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/users.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/users.py @@ -183,6 +183,7 @@ async def register( request: Request, db: AsyncSession = Depends(get_db), ): + """Create an account. It stays inactive until its e-mail address is verified.""" eh = hash_email_blind(body.email) # Unique regardless of case: invitations and member management name people @@ -485,6 +486,10 @@ async def login( request: Request, db: AsyncSession = Depends(get_db), ): + """ + Sign in with the auth key derived from the passphrase. Returns the session and the bundle + pepper. + """ ip = client_ip(request) if not body.auth_key and not body.password: @@ -662,6 +667,7 @@ async def list_devices( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """The account's registered devices.""" result = await db.execute( select(UserDevice).where(UserDevice.user_id == current_user.id) .order_by(UserDevice.created_at)) @@ -777,6 +783,7 @@ async def token_refresh( request: Request, db: AsyncSession = Depends(get_db), ): + """Exchange a refresh token for a new session. Reusing a spent one revokes the whole family.""" rt_hash = hash_refresh_token(body.refresh_token) result = await db.execute( select(RefreshToken).where(RefreshToken.token_hash == rt_hash)) @@ -840,6 +847,7 @@ async def get_current_user_info( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """The signed-in account: id, name, e-mail, role, status.""" email = "" try: email = decrypt_email(current_user.email) if current_user.email else "" @@ -1144,6 +1152,7 @@ async def change_password( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Change the passphrase, proving the current one.""" await _take_login_attempt(db, _session_counter(current_user)) if not await verify_password_off_loop(body.old_auth_key, current_user.pw_hash, current_user.pw_salt, current_user.pw_version): @@ -1231,6 +1240,7 @@ async def password_reset_request( request: Request, db: AsyncSession = Depends(get_db), ): + """Send a reset code by e-mail, when the username and the address match.""" if _cfg and _cfg.captcha.enabled: await _verify_captcha_or_raise(body.captcha_token, request) @@ -1310,6 +1320,7 @@ async def password_reset( request: Request, db: AsyncSession = Depends(get_db), ): + """Set a new passphrase with the code received by e-mail.""" now = datetime.now(UTC) result = await db.execute(select(User).where(User.username == body.username)) user = result.scalar_one_or_none() @@ -1407,6 +1418,7 @@ async def get_preferences( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """The account's stored interface preferences.""" result = await db.execute( select(UserPreference).where(UserPreference.user_id == current_user.id)) prefs = {p.key: p.value for p in result.scalars().all()} @@ -1424,6 +1436,7 @@ async def set_preference( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Store one interface preference.""" if not _valid_pref_key(key): raise HTTPException(status_code=400, detail=f"Unknown preference key: {key[:80]}") if len(body.value) > MAX_PREFERENCE_VALUE: @@ -1454,6 +1467,7 @@ async def delete_preference( current_user: User = Depends(require_user_scope), db: AsyncSession = Depends(get_db), ): + """Remove one interface preference.""" result = await db.execute( select(UserPreference).where( UserPreference.user_id == current_user.id, @@ -1624,6 +1638,7 @@ async def get_user_pubkeys( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): + """Resolve a username to its account id, and its node's linking key. Not a key directory.""" result = await db.execute(select(User).where(User.username == username)) target = result.scalar_one_or_none() if not target: diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js index 6f97ca5..bdab271 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js @@ -21,6 +21,7 @@ import { } from './hub-client.js'; import { startIdleWatch, markActive } from './idle.js'; import { GroupPage } from './group-page.js'; +import { parseGroupLink, groupLinkRoute, findLinkedGroup } from './group-link.js'; import { lazy } from './lazy.js'; import { ConnectionPool } from './connection-pool.js'; import { MusicPlayerBar } from './music-player.js'; @@ -766,6 +767,9 @@ function App() { const [needsHub, setNeedsHub] = useState( platform.isNative && !platform.hubBase()); const [groups, setGroups] = useState([]); + // Whether `/mine` has answered for this sign-in. A `#/name@owner` link can + // only be called unknown once the list it is looked up in has arrived. + const [groupsLoaded, setGroupsLoaded] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const [notifications, setNotifications] = useState([]); const [unreadCount, setUnreadCount] = useState(0); @@ -1008,11 +1012,13 @@ function App() { if (!user) { nodeKeyAskedForRef.current = null; setGroups([]); setNotifications([]); setUnreadCount(0); setHasNodeKey(false); + setGroupsLoaded(false); return; } hubFetch('/v1/groups/mine', { token: user.token }) .then(data => setGroups(data.groups || [])) - .catch(() => setGroups([])); + .catch(() => setGroups([])) + .finally(() => setGroupsLoaded(true)); hubFetch('/v1/users/me/preferences', { token: user.token }) .then(async (prefs) => { setUserPrefs(prefs || {}); @@ -1233,11 +1239,36 @@ function App() { // out as the only way back. const refreshAuth = useCallback(() => refreshAccessToken(), []); + // A group is reached by its id (`#/group/<id>`, what every link inside the + // application uses) or by its handle (`#/name@owner[/path]`, the one a person + // types or shares — group-link.js). Both open the same page; `groupRoute` is + // the first form whichever was used, so the sidebar and the page see one. + const groupLink = route.startsWith('/group/') ? null : parseGroupLink(route); + const linkedGroup = groupLink ? findLinkedGroup(groups, groupLink) : null; + const groupId = route.startsWith('/group/') ? route.slice(7) + : linkedGroup ? linkedGroup.id : null; + const groupRoute = groupId ? '/group/' + groupId : route; + const shownGroup = groupId ? groups.find(g => g.id === groupId) : null; + const linkPath = groupLink && linkedGroup ? groupLink.path : ''; + // The address shows the handle, which is the link worth copying. `replace`, + // so this is not a history entry; and only once the path a link named has + // been acted on (`onLinkOpened`), so a reload does not download the file a + // second time. + const shownGroupRoute = shownGroup ? groupLinkRoute(shownGroup) : null; + useEffect(() => { + if (shownGroupRoute && !linkPath && route !== shownGroupRoute) { + window.location.replace('#' + shownGroupRoute); + } + }, [route, shownGroupRoute, linkPath]); + const onLinkOpened = useCallback(() => { + if (shownGroupRoute) window.location.replace('#' + shownGroupRoute); + }, [shownGroupRoute]); + let page; // A desktop build with no hub configured cannot do anything at all, so it - // asks before showing a sign-in form that could not work. Deliberately not - // defaulted to meshbay.org: a client that picks its own hub is a client that - // can be pointed at one. + // asks before showing a sign-in form that could not work. The field comes + // filled with meshbay.org but is still asked: a client that picks its own hub + // is a client that can be pointed at one. if (needsHub) { page = html`<${FirstRunPage} onSet=${() => setNeedsHub(false)} />`; } else if (!deviceTried) { @@ -1282,17 +1313,23 @@ function App() { }} />`; } else if (route === '/node' && platform.capabilities.nodeAdmin && hasNodeKey) { page = html`<${LazyNodePage} groups=${groups} token=${user.token} username=${user.username} />`; - } else if (route.startsWith('/group/')) { - const groupId = route.slice(7); - const group = groups.find(g => g.id === groupId); + } else if (groupId) { page = html`<${GroupPage} - groupId=${groupId} group=${group} token=${user.token} + groupId=${groupId} group=${shownGroup} token=${user.token} + openPath=${linkPath} onLinkOpened=${onLinkOpened} username=${user.username} userId=${user.userId} userPrefs=${userPrefs} onRefreshAuth=${refreshAuth} onJoined=${dismissGroupNotifications} onGroupUpdated=${updateGroup} onPresence=${notePresence} onLeft=${handleLeftGroup} onPlayQueue=${handlePlayQueue} onStopMusic=${handleStopMusic} />`; + } else if (groupLink) { + // Not among this account's groups — or not yet known to be. The same words + // whether it does not exist or is someone else's: the list it was looked + // up in is this account's own, so there is nothing else to tell. + page = groupsLoaded + ? html`<div class="page-content"><p class="page-message">${t('group.link_unknown')}</p></div>` + : html`<div class="page-content"><p class="page-message"><span class="spinner"></span></p></div>`; } else if (route === '/admin') { page = (user.role === 'moderator' || user.role === 'admin') ? html`<${LazyAdminPage} token=${user.token} role=${user.role} />` @@ -1334,7 +1371,7 @@ function App() { groups=${groups} presence=${presence} indexProgressPct=${indexProgressPct} - route=${route} + route=${groupRoute} menuOpen=${menuOpen} role=${user.role} allowPublicGroups=${allowPublicGroups} diff --git a/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js b/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js index d3d3bd7..57db475 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js @@ -130,7 +130,7 @@ function passwordBits(pw) { } export function FirstRunPage({ onSet }) { - const [url, setUrl] = useState(''); + const [url, setUrl] = useState('https://meshbay.org'); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); @@ -161,7 +161,6 @@ export function FirstRunPage({ onSet }) { </button> </form> ${error && html`<div class="error-msg">${error}</div>`} - <p class="settings-hint" style="margin-top:16px">${t('firstrun.note')}</p> </div> </div> `; @@ -186,8 +185,12 @@ export function LoginPage({ onLogin }) { // Trimmed to match the hub's stored username and every client-side key // derivation (auth_key, bundle_key, recovery_key all fold the username in). await onLogin(name, password); - // Back to the invitation that sent them here, if one is waiting. - navigate(loadPending() ? '/invite' : '/'); + // Back to the invitation that sent them here, if one is waiting. Otherwise + // nowhere: on `#/login` or `#/register` the router sends a signed-in + // person home itself, and anywhere else this form stood in for the page + // the address names — a group, a file in one — which is where they were + // going. Sending everyone home lost every link opened signed out. + if (loadPending()) navigate('/invite'); } catch (err) { if (err.message === 'email_verification_required') { setPendingVerif(true); @@ -277,7 +280,8 @@ const WELCOME_DOCS = [ ['welcome.docs_userguide', `${REPO}docs/USERGUIDE.md`]]], ['gear', 'welcome.docs_devel', [ ['welcome.docs_design', `${REPO}docs/MESHBAY_DESIGN.md`], - ['welcome.docs_protocol', `${REPO}docs/MESHBAY_NODE_PROTOCOL.md`]]], + ['welcome.docs_protocol', `${REPO}docs/MESHBAY_NODE_PROTOCOL.md`], + ['welcome.docs_api', `${REPO}docs/MESHBAY_HTTP_API.md`]]], ]; // Under the sign-in form rather than at the foot of the text: on a desktop the diff --git a/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js b/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js new file mode 100644 index 0000000..4cc3f30 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/copy-link.js @@ -0,0 +1,50 @@ +import { t } from './i18n.js'; +import * as platform from './platform.js'; +import { groupLinkRoute } from './group-link.js'; +import { say } from './note.js'; + +/** + * "Copy link": the `#/name@owner/path` address of a file or folder + * (group-link.js), on this hub, put on the clipboard. + * + * The hub's origin, never the page's: in the desktop application the page is + * `app://meshbay`, and a link that only opens inside one person's application + * is not a link. + */ + +/** The full link to `path` inside `group` (`{ name, owner_username }`). */ +export function groupItemLink(group, path) { + return platform.hubOrigin() + '/#' + groupLinkRoute(group, path); +} + +/** An entry's path inside its group: its folder, root first, then its name. */ +export function entryPath(entry, dir = entry.path) { + return [dir, entry.name].filter(Boolean).join('/'); +} + +// The async clipboard first; the old command where it is refused — a page +// without focus, a WebView without the permission. Neither needs to read +// anything back. +async function _write(text) { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { /* fall through */ } + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', ''); + area.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none'; + document.body.appendChild(area); + area.select(); + let ok = false; + try { ok = document.execCommand('copy'); } catch { ok = false; } + area.remove(); + return ok; +} + +/** Copy `url`, and say whether it worked. The link itself is shown if not. */ +export async function copyLink(url) { + if (!url) return; + const ok = await _write(url); + say(ok ? t('link.copied') : t('link.copy_failed', { url })); +} diff --git a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js index ce5ec76..11114d9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * MeshBay Browser Crypto — AES-256-GCM, through WebCrypto's SubtleCrypto API. * The one content cipher, for every client (meshbay_common/webcrypto.py). diff --git a/packages/meshbay-hub/src/meshbay_hub/static/files-app.js b/packages/meshbay-hub/src/meshbay_hub/static/files-app.js index 38157b9..b3672c9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/files-app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/files-app.js @@ -13,6 +13,7 @@ import { import { useStickyBand } from './sticky.js'; import { Menu, useMenu } from './menu.js'; import { askReport } from './report.js'; +import { copyLink } from './copy-link.js'; // ── Files ──────────────────────────────────────────────────────────────────── // @@ -142,12 +143,16 @@ function FilesPanel({ entries, nodeDirs, nodeRoots, setEntries, setNodeDirs, setNodeRoots, applyIndex, isNodeAdmin, operatorPaired, userId, setError, onPreview, showGroup, readOnly, getTransport, onRefreshIndex, showRefresh, onReport, + openDirectory, linkFor, }) { const [selected, setSelected] = useState(() => new Set()); const [sortKey, setSortKey] = useState('name'); const [sortAsc, setSortAsc] = useState(true); const [filter, setFilter] = useState(''); - const [currentPath, setCurrentPath] = useState(''); + const [currentPath, setCurrentPath] = useState(() => (openDirectory ? openDirectory.dir : '')); + // A link into the group named a folder (group-page.js); a new object each + // time, so the same folder linked twice is opened twice. + useEffect(() => { if (openDirectory) setCurrentPath(openDirectory.dir); }, [openDirectory]); const [refreshing, setRefreshing] = useState(false); // The toolbar pins below the page's own band and tells the column heads how // far down to pin. Its height is not a constant — it wraps to three rows on @@ -619,6 +624,14 @@ function FilesPanel({ onSelect: () => run(async () => { for (const d of dirs) await downloadDirectory(d); }, clear) }, + // One file or one folder, ticked (the toolbar, which is also how a phone + // gets at it) or under the pointer. Absent rather than disabled where + // the view can name no link at all (`linkFor` returns null). + linkFor && { key: 'link', icon: 'link', label: t('link.copy'), + disabled: files.length + dirs.length !== 1 + || !linkFor(files.length ? files[0] : dirs[0]), + onSelect: () => run( + () => copyLink(linkFor(files.length ? files[0] : dirs[0])), clear) }, mayEverDelete && !readOnly && { key: 'delete', icon: 'trash', danger: true, label: deletableCount > 1 ? t('group.delete_n', { n: deletableCount }) : t('group.delete'), disabled: status !== 'connected' || deletableCount === 0, @@ -901,7 +914,7 @@ function FilesPanel({ const IMAGE_EXTS = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i; -function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) { +function FilePreview({ entry, transportRef, gekRef, onClose, onDownload, onCopyLink }) { const [phase, setPhase] = useState('loading'); const [progress, setProgress] = useState(0); const [content, setContent] = useState(null); @@ -996,6 +1009,11 @@ function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) { }}> <div class="video-top-bar"> <span class="video-title">${entry.name} (${formatSize(entry.size)})</span> + ${onCopyLink && html` + <button class="video-close" onClick=${onCopyLink} + title="${t('link.copy')}" aria-label="${t('link.copy')}"> + <${Icon} name="link" /></button> + `} ${onDownload && html` <button class="video-close ${downloading ? 'dl-active' : ''}" onClick=${() => { diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-link.js b/packages/meshbay-hub/src/meshbay_hub/static/group-link.js new file mode 100644 index 0000000..3c9063c --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-link.js @@ -0,0 +1,95 @@ +/** + * A group named in the address: `#/name@owner`, optionally followed by a path + * inside it — `#/name@owner/root/folder/file.jpg`. + * + * The same handle `GroupName` shows under every group, so a link reads the way + * the group is labelled. It is resolved against the signed-in account's own + * group list and nothing else: no hub route answers "which group is this + * name", so a name says nothing to someone who is not already a member, and + * nobody can probe for one. The UUID stays the group's identity; a renamed + * group breaks its name links, never its `#/group/<id>` ones. + * + * In the fragment, never the path: what follows `#` is not sent to the server, + * so a group's name and a file's path appear in no hub or proxy log and in no + * Referer. + * + * The owner is everything after the *last* `@`: a username cannot contain one + * (users.py, RegisterRequest), a group name can. Each segment is + * percent-decoded on its own, so a `/` inside a name or a file name travels as + * `%2F` without splitting the path. + * + * No imports, so `test_group_link.py` can execute the module as it is. + */ + +function _decode(segment) { + try { return decodeURIComponent(segment); } catch { return null; } +} + +// `@` is legal in a fragment and the owner is found by the last one, so the +// name's own need no escaping; everything else is escaped as a URI component. +function _encode(segment) { + return encodeURIComponent(segment).replace(/%40/g, '@'); +} + +/** + * `{ name, owner, path }` for a route (the hash without its `#`), or null when + * the route does not name a group. `path` is '' for the group itself. + */ +function parseGroupLink(route) { + if (!route || route[0] !== '/') return null; + const parts = route.slice(1).split('/'); + const head = _decode(parts[0]); + if (!head) return null; + const at = head.lastIndexOf('@'); + if (at <= 0 || at === head.length - 1) return null; + const rest = parts.slice(1).filter(Boolean).map(_decode); + if (rest.some((s) => s === null || s === '.' || s === '..')) return null; + return { name: head.slice(0, at), owner: head.slice(at + 1), path: rest.join('/') }; +} + +/** The route naming `group`, and `path` inside it when one is given. */ +function groupLinkRoute(group, path = '') { + const head = `/${_encode(group.name)}@${_encode(group.owner_username || '')}`; + const tail = path ? '/' + path.split('/').filter(Boolean).map(_encode).join('/') : ''; + return head + tail; +} + +/** + * The group `link` names among `groups` (`/v1/groups/mine` rows), or null. + * + * Case-insensitively on the name, as the hub keeps it unique + * (`uq_groups_owner_name` is on `lower(name)`); the owner as typed first, then + * case-insensitively when that finds exactly one. + */ +function findLinkedGroup(groups, link) { + if (!link) return null; + const name = link.name.toLowerCase(); + const named = (groups || []).filter((g) => (g.name || '').toLowerCase() === name); + const exact = named.find((g) => g.owner_username === link.owner); + if (exact) return exact; + const owner = link.owner.toLowerCase(); + const loose = named.filter((g) => (g.owner_username || '').toLowerCase() === owner); + return loose.length === 1 ? loose[0] : null; +} + +/** + * What `path` names in a group's index: `{ kind: 'file', entry }`, + * `{ kind: 'dir', dir }`, or null. An entry's `path` is its folder, root + * first, and `name` its file name — so a file is matched on both together. + * Folders come from the files under them and from the node's own listing, + * which is the only place an empty one appears. + */ +function resolveLinkedPath(entries, nodeDirs, path) { + if (!path) return null; + const cut = path.lastIndexOf('/'); + const dir = cut < 0 ? '' : path.slice(0, cut); + const name = cut < 0 ? path : path.slice(cut + 1); + const entry = (entries || []).find((e) => (e.path || '') === dir && e.name === name); + if (entry) return { kind: 'file', entry }; + const prefix = path + '/'; + const isDir = (nodeDirs || []).includes(path) + || (entries || []).some((e) => (e.path || '') === path || (e.path || '').startsWith(prefix)); + return isDir ? { kind: 'dir', dir: path } : null; +} + +export { parseGroupLink, groupLinkRoute, findLinkedGroup, resolveLinkedPath }; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js index fe858b2..48b1c80 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js @@ -5,6 +5,8 @@ import { t } from './i18n.js'; import { Icon } from './icon.js'; import { transfers } from './transfers.js'; import { downloadEntry } from './file-utils.js'; +import { resolveLinkedPath } from './group-link.js'; +import { copyLink, entryPath, groupItemLink } from './copy-link.js'; import { HUB, session, hubFetch, ensureFreshToken, _loadBundleKey, _loadRecoveryKey, _storeBundleKey, @@ -33,7 +35,8 @@ import { clearPending, nodePkFromLink, pendingFor } from './invite-link.js'; */ function GroupPage({ groupId, group, token, username, userId, userPrefs, onRefreshAuth, onJoined, onGroupUpdated, onPresence, onLeft, - onPlayQueue: parentOnPlayQueue, onStopMusic }) { + onPlayQueue: parentOnPlayQueue, onStopMusic, + openPath = '', onLinkOpened }) { const [status, setStatus] = useState('idle'); // The tab bar pins under the navigation bar and tells the application's own // toolbar how far down to pin (style.css, "Sticky chrome"). @@ -313,12 +316,18 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, }); }, []); + // Which group `entries` is the index of. The page is not remounted between + // groups, so for one render after a switch `status` and `entries` are still + // the last group's — and a link into the new one must not be looked up there. + const indexGroupRef = useRef(null); + // One place that takes an index from the node and puts it everywhere it has to // go. Deleting a file used to refresh the table and leave the cache alone, so // the search page went on offering a file that no longer existed until the // group was reconnected. const applyIndex = useCallback((indexMsg) => { const fresh = indexMsg.entries || []; + indexGroupRef.current = groupId; setEntries(fresh); if (indexMsg.dirs) setNodeDirs(indexMsg.dirs); if (indexMsg.roots) setNodeRoots(indexMsg.roots); @@ -731,6 +740,36 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, await downloadEntry(transfers, transport, gekRef.current, entry); }, []); + // A link that named a path inside the group (`#/name@owner/root/dir/file`, + // group-link.js): a file is downloaded, and Files opens on its folder either + // way. Acted on once the index is in — before that, nothing can say whether + // the path is a file, a folder or nothing — and then handed back to the + // router, which takes the path out of the address so a reload does not + // download it again. + const [openDirectory, setOpenDirectory] = useState(null); + useEffect(() => { setOpenDirectory(null); }, [groupId]); + useEffect(() => { + if (!openPath || status !== 'connected' || indexGroupRef.current !== groupId) return; + const target = resolveLinkedPath(entries, nodeDirs, openPath); + if (!target) { + setError(t('group.link_path_unknown', { path: openPath })); + } else { + const dir = target.kind === 'file' ? (target.entry.path || '') : target.dir; + setOpenDirectory({ dir }); + chooseTab('files'); + if (target.kind === 'file') downloadFileForModal(target.entry); + } + if (onLinkOpened) onLinkOpened(); + }, [openPath, status, groupId]); + + // The link "Copy link" puts on the clipboard, for an entry or a folder path + // (group-link.js). Null until the hub's row for the group is in: the handle + // is its name and its owner's, and the node knows neither. + const linkFor = useCallback((target) => { + if (!group || !group.name || !group.owner_username || !target) return null; + return groupItemLink(group, typeof target === 'string' ? target : entryPath(target)); + }, [group]); + const refreshIndex = useCallback(async () => { const transport = transportRef.current; if (!transport || !transport.connected) return; @@ -861,7 +900,7 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, entries, availableEntries, nodeDirs, nodeRoots, setEntries, setNodeDirs, setNodeRoots, applyIndex, isNodeAdmin, operatorPaired, attachRoot, attachDir, userId, setError, onPreview, - onRefreshIndex: refreshIndex, onActivity: touchActivity, + onRefreshIndex: refreshIndex, onActivity: touchActivity, linkFor, // Plural everywhere, and built from the registry rather than a list of app // names kept here: Videos and Music read a list, Photos always did, and an // application added to `APPS` gets its own entry without this file @@ -987,7 +1026,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, </div> ${apps.map(a => tab === a.key && html` - <${a.Component} key=${a.key + '-' + groupId} ...${commonProps} /> + <${a.Component} key=${a.key + '-' + groupId} ...${commonProps} + ...${a.key === 'files' ? { openDirectory } : {}} /> `)} ${tab === 'settings' && html` @@ -1029,7 +1069,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, transportRef=${transportRef} gekRef=${gekRef} onClose=${() => setPreviewEntry(null)} - onDownload=${() => downloadFileForModal(previewEntry)} /> + onDownload=${() => downloadFileForModal(previewEntry)} + onCopyLink=${linkFor(previewEntry) && (() => copyLink(linkFor(previewEntry)))} /> `} ${videoEntry && html` <${VideoPlayer} @@ -1037,7 +1078,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, transportRef=${transportRef} gekRef=${gekRef} onClose=${() => setVideoEntry(null)} - onDownload=${() => downloadFileForModal(videoEntry)} /> + onDownload=${() => downloadFileForModal(videoEntry)} + onCopyLink=${linkFor(videoEntry) && (() => copyLink(linkFor(videoEntry)))} /> `} </div> `; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js index 29aa7eb..3ffa524 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js @@ -783,6 +783,27 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, useEffect(() => { loadMembers(); }, [loadMembers]); + // Who the node has admitted to this group. The hub counts someone a member + // once they accept the invitation; the node, once they present their code. + // Until then they are not in the group, and are listed as waiting, to the + // owner only. Null when the roster cannot be read: the hub's list is shown. + const [admitted, setAdmitted] = useState(null); + useEffect(() => { + const transport = transportRef.current; + if (!connected || !transport || !transport.connected) { setAdmitted(null); return; } + let cancelled = false; + transport.groupRoster({ fresh: true }) + .then((roster) => { if (!cancelled) setAdmitted(new Set(roster.byAccount.keys())); }) + .catch(() => { if (!cancelled) setAdmitted(null); }); + return () => { cancelled = true; }; + }, [connected, transportRef, members]); + const joined = admitted + ? members.filter(m => m.user_id === adminId || admitted.has(m.user_id)) + : members; + const awaitingCode = admitted + ? members.filter(m => m.user_id !== adminId && !admitted.has(m.user_id)) + : []; + const ownsGroup = Boolean(group && group.is_admin); const loadHosts = useCallback(() => { if (!ownsGroup) return; @@ -1340,7 +1361,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, </${CollapsibleSection}> `} - <${CollapsibleSection} title=${`${t('group.tab_members')} (${members.length})`}> + <${CollapsibleSection} title=${`${t('group.tab_members')} (${joined.length})`}> <table class="admin-table"> <thead> <tr> @@ -1350,7 +1371,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, </tr> </thead> <tbody> - ${members.map(m => html` + ${joined.map(m => html` <tr key=${m.user_id}> <td>${m.username}</td> <td> @@ -1372,6 +1393,21 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, </td> </tr> `)} + ${isAdmin && awaitingCode.map(m => html` + <tr key=${m.user_id}> + <td>${m.username}</td> + <td><span class="badge">${t('members.awaiting_code')}</span></td> + <td class="admin-actions"> + <button class="admin-btn danger" disabled=${removing === m.user_id} + onClick=${async () => { + if (!await ask(t('members.remove_confirm', { user: m.username }))) return; + removeMember(m); + }}> + ${removing === m.user_id ? '...' : t('members.remove')} + </button> + </td> + </tr> + `)} ${invited.map(m => html` <tr key=${m.user_id}> <td>${m.username}</td> @@ -1391,7 +1427,7 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, `)} </tbody> </table> - ${isAdmin && members.length > 1 && html` + ${isAdmin && joined.length > 1 && html` <p class="settings-hint">${t('members.remove_hint')}</p> `} </${CollapsibleSection}> diff --git a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js index be26fbc..f033915 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app-settings.js @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: 0BSD +// The reference application: copy it to start one of your own, under any licence +// (licenses/APPLICATION-EXCEPTION.txt). import { html, useState, useEffect } from './vendor/htm-preact.js'; import { t } from './i18n.js'; import { useSaver } from './settings-ui.js'; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js index 98ca8fa..8781d18 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/helloworld-app.js @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: 0BSD +// The reference application: copy it to start one of your own, under any licence +// (licenses/APPLICATION-EXCEPTION.txt). import { html, useMemo } from './vendor/htm-preact.js'; import { t } from './i18n.js'; import { Icon } from './icon.js'; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/icon.js b/packages/meshbay-hub/src/meshbay_hub/static/icon.js index 4fa4357..4d549f1 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/icon.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/icon.js @@ -65,6 +65,8 @@ const ICON_PATHS = { plus: ['M12 5v14', 'M5 12h14'], refresh: ['M20 11a8 8 0 0 0-15.3-2', 'M4 5v4h4', 'M4 13a8 8 0 0 0 15.3 2', 'M20 19v-4h-4'], + link: ['M10 13.5a4.5 4.5 0 0 0 6.4.4l3-3a4.5 4.5 0 0 0-6.4-6.4l-1.6 1.6', + 'M14 10.5a4.5 4.5 0 0 0-6.4-.4l-3 3a4.5 4.5 0 0 0 6.4 6.4l1.6-1.6'], clip: ['M20.5 11.8l-8.4 8.4a5.4 5.4 0 0 1-7.6-7.6l8.8-8.8a3.6 3.6 0 0 1 5.1 5.1l-8.8 8.8a1.8 1.8 0 0 1-2.5-2.5l8.1-8.1'], pencil: ['M4 20h4l10.5-10.5a2.1 2.1 0 0 0-3-3L5 17v3', 'M14.5 6.5l3 3'], diff --git a/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js b/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js index 6730e60..6c89eb6 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/index-dock.js @@ -51,9 +51,18 @@ function useLoopbackActivity() { let stopped = false; let timer = null; let last = ''; + // Asked before the first operation and again after any failure: detect() + // answers "no node" as a value, where an operation on an absent node is a + // rejected IPC call that Electron prints to its terminal on every poll. + let present = false; const poll = async () => { let delay = IDLE_POLL_MS; try { + if (!present) { + const found = await platform.node.detect(); + if (!found || !found.detected) throw new Error('no node'); + present = true; + } const data = await platform.node.op('indexStatus'); const next = {}; for (const g of (data && data.groups) || []) next[g.group_id] = fromLoopback(g); @@ -64,6 +73,7 @@ function useLoopbackActivity() { if (!stopped && text !== last) { last = text; setLocal(next); } } catch { // No node on this machine, or one older than the route. + present = false; if (!stopped && last !== '{}') { last = '{}'; setLocal({}); } delay = ABSENT_POLL_MS; } diff --git a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js index 7bbcac5..edf4df9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * MeshBay Browser Key Management — keyderive.js * diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/AGPL-3.0.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt new file mode 100644 index 0000000..5ab0921 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/APPLICATION-EXCEPTION.txt @@ -0,0 +1,65 @@ +MeshBay interface — additional permission for group applications +under GNU AGPL version 3, section 7 +============================================================================== + +The MeshBay interface is free software under the GNU Affero General Public +License, version 3 or (at your option) any later version (AGPL-3.0.txt, beside +this file), with the following additional permission. Its protocol layer, the +files marked SPDX-License-Identifier: LGPL-3.0-or-later, is under the GNU +Lesser GPL instead and needs no such permission. + +Definitions + + "The Interface" is the MeshBay web interface: the files of + packages/meshbay-hub/src/meshbay_hub/static/ that are under the AGPL, + wherever they are conveyed — served by a hub, or carried by the desktop or + the Android application. + + "The Application Interface" is: + 1. the properties the Interface passes to a group application's component + and to its settings pane, and the fields of an entry in its application + registry (apps.js), as docs/MESHBAY_DESIGN.md sections 9.2 to 9.4 + describe them; + 2. the names exported by these modules of the Interface: + i18n.js + icon.js + file-utils.js + settings-ui.js + folder-tree.js + 3. the CSS class names style.css defines, and the message keys of the + catalogues under locales/. + + "An Application" is a module, or a set of modules, that the Interface loads + as a group application and that interacts with the Interface only through + the Application Interface. It may also use the protocol layer and the + third-party files under vendor/, each under its own licence. It contains no + part of the Interface itself, copied or modified. + +Permission + + As a special exception, the copyright holders of the Interface give you + permission to combine an Application with the Interface, and to convey the + resulting combination, with the Application under terms of your choice, + provided that the Interface itself — including any modification of it, of + which registering the Application in apps.js or adding its messages to the + catalogues is one — remains under the GNU AGPL with this permission, and + that you meet the AGPL's terms for it, section 13 included. An Application + does not become a work based on the Interface by using the Application + Interface, and conveyed on its own carries no obligation from the + Interface's licence. + + This permission covers the Interface only. The hub, the node and the + desktop and Android shells keep their licence unchanged: code running there + on an Application's behalf is a modification of them. + + If you modify the Interface, you may extend this permission to your version + of it, but you are not obliged to do so. If you do not wish to, delete this + permission from your version (section 7). + +Why: the point of the application store is that people other than MeshBay's +authors write applications, under the licence they choose — free or not. An +application runs in the same page as the Interface and calls into it, which +without this permission would make it a work based on the Interface, under the +AGPL. The permission is limited to a named, documented surface so that what an +application may rely on is a deliberate commitment, not whatever happens to be +importable. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt b/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/licenses/LGPL-3.0.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js index c72de49..6e42af9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/de.js @@ -123,6 +123,7 @@ export default { 'welcome.docs_devel': 'Entwicklerdoku', 'welcome.docs_design': 'Architektur', 'welcome.docs_protocol': 'Protokoll', + 'welcome.docs_api': 'API', 'welcome.download': 'Herunterladen (Beta)', 'welcome.legal': 'Rechtliche Hinweise', 'register.err_mismatch': 'Die Passwörter stimmen nicht überein', @@ -209,6 +210,11 @@ export default { 'group.mkdir_prompt': 'Name des neuen Ordners', 'group.mkdir_offline': 'Nicht mit dem Node verbunden.', 'group.download_offline': 'Keine Verbindung zum Node — der Download kann nicht starten. Die Verbindung wird automatisch wiederhergestellt; versuchen Sie es gleich erneut.', + 'group.link_unknown': "Dieser Link verweist auf eine Gruppe, in der Sie nicht Mitglied sind, oder die nicht mehr so heißt.", + 'group.link_path_unknown': "Unter {path} gibt es in dieser Gruppe nichts — die Datei wurde vielleicht verschoben, umbenannt oder gelöscht.", + 'link.copy': "Link kopieren", + 'link.copied': "Link kopiert", + 'link.copy_failed': "Kopieren nicht möglich — der Link lautet {url}", 'group.download_write_stalled': 'Die Datei wird nicht mehr auf die Festplatte geschrieben ({seconds} s ohne Fortschritt). Der Download wurde abgebrochen statt hängen gelassen; versuchen Sie es erneut.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -503,12 +509,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1237,6 +1242,7 @@ export default { 'home.accept': "Annehmen", 'home.decline': "Ablehnen", 'members.invited': "eingeladen", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Hosts", 'hosts.hint': "Ihre eigenen Nodes stellen diese Gruppe ohne Rückfrage bereit. Ein anderer Node tut es erst, wenn Sie ihn hier genehmigen; ein Node, der anfragt, steht unten.", 'hosts.none': "Kein anderer Node hat angefragt, diese Gruppe bereitzustellen.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js index a799b34..f94b438 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js @@ -126,6 +126,7 @@ export default { 'welcome.docs_devel': 'Developer docs', 'welcome.docs_design': 'Design', 'welcome.docs_protocol': 'Protocol', + 'welcome.docs_api': 'API', 'welcome.download': 'Download (beta)', 'welcome.legal': 'Legal information', 'register.err_mismatch': 'Passwords do not match', @@ -209,6 +210,11 @@ export default { 'group.mkdir_prompt': 'New folder name', 'group.mkdir_offline': 'Not connected to the node.', 'group.download_offline': 'Not connected to the node — the download cannot start. It reconnects on its own; try again in a moment.', + 'group.link_unknown': "This link names a group you are not a member of, or one that no longer goes by that name.", + 'group.link_path_unknown': "Nothing at {path} in this group — the file may have been moved, renamed or deleted.", + 'link.copy': "Copy link", + 'link.copied': "Link copied", + 'link.copy_failed': "Could not copy — the link is {url}", 'group.download_write_stalled': 'The file stopped being written to disk ({seconds}s with no progress). The download was stopped rather than left hanging; try it again.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -495,12 +501,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1218,6 +1223,7 @@ export default { 'home.accept': "Accept", 'home.decline': "Decline", 'members.invited': "invited", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Hosts", 'hosts.hint': "Your own nodes serve this group without asking. Another node serves it only once you approve it here; a node that asks is listed below.", 'hosts.none': "No other node has asked to host this group.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js index 8e49240..6ff8be2 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/es.js @@ -122,6 +122,7 @@ export default { 'welcome.docs_devel': 'Docs de desarrollo', 'welcome.docs_design': 'Diseño', 'welcome.docs_protocol': 'Protocolo', + 'welcome.docs_api': 'API', 'welcome.download': 'Descargar (beta)', 'welcome.legal': 'Información legal', 'register.err_mismatch': 'Las contraseñas no coinciden', @@ -207,6 +208,11 @@ export default { 'group.mkdir_prompt': 'Nombre de la nueva carpeta', 'group.mkdir_offline': 'Sin conexión con el nodo.', 'group.download_offline': 'Sin conexión con el nodo — la descarga no puede empezar. Se reconecta sola; inténtelo de nuevo en un momento.', + 'group.link_unknown': "Este enlace nombra un grupo del que no eres miembro, o que ya no se llama así.", + 'group.link_path_unknown': "No hay nada en {path} en este grupo: puede que el archivo se haya movido, renombrado o eliminado.", + 'link.copy': "Copiar enlace", + 'link.copied': "Enlace copiado", + 'link.copy_failed': "No se pudo copiar: el enlace es {url}", 'group.download_write_stalled': 'El archivo dejó de escribirse en el disco ({seconds} s sin avance). La descarga se detuvo en lugar de quedarse colgada; inténtelo de nuevo.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -499,12 +505,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1231,6 +1236,7 @@ export default { 'home.accept': "Aceptar", 'home.decline': "Rechazar", 'members.invited': "invitado", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Anfitriones", 'hosts.hint': "Sus propios nodes sirven este grupo sin preguntar. Otro node lo sirve solo cuando usted lo aprueba aquí; un node que lo pide aparece abajo.", 'hosts.none': "Ningún otro node ha pedido alojar este grupo.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js index 1432f11..9132bd2 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js @@ -122,6 +122,7 @@ export default { 'welcome.docs_devel': 'Docs développeur', 'welcome.docs_design': 'Conception', 'welcome.docs_protocol': 'Protocole', + 'welcome.docs_api': 'API', 'welcome.download': 'Télécharger (bêta)', 'welcome.legal': 'Informations légales', 'register.err_mismatch': 'Les mots de passe ne correspondent pas', @@ -208,6 +209,11 @@ export default { 'group.mkdir_prompt': 'Nom du nouveau dossier', 'group.mkdir_offline': 'Non connecté au nœud.', 'group.download_offline': 'Pas de connexion au node — le téléchargement ne peut pas démarrer. La reconnexion est automatique, réessayez dans un instant.', + 'group.link_unknown': "Ce lien désigne un groupe dont vous n'êtes pas membre, ou qui ne porte plus ce nom.", + 'group.link_path_unknown': "Rien à l'emplacement {path} dans ce groupe — le fichier a peut-être été déplacé, renommé ou supprimé.", + 'link.copy': "Copier le lien", + 'link.copied': "Lien copié", + 'link.copy_failed': "Copie impossible — le lien est {url}", 'group.download_write_stalled': 'L\'écriture du fichier sur le disque s\'est arrêtée ({seconds} s sans progression). Le téléchargement a été interrompu plutôt que laissé en suspens ; réessayez.', 'device.add_title': 'Ce navigateur n’est pas encore lié à ce nœud', 'device.add_hint': 'Votre compte est connu ici, mais ce navigateur détient une autre clé. Approuvez-le depuis un appareil déjà lié — sans passer par l’opérateur.', @@ -502,12 +508,11 @@ export default { 'firstrun.hint': 'Un hub détient votre compte et vous met en relation avec les nœuds. Il ne voit ni vos fichiers, ni vos messages, ni vos clés.', 'firstrun.btn': 'Continuer', 'firstrun.checking': 'Vérification…', - 'firstrun.note': 'Il n’y a volontairement pas de valeur par défaut : cette application ne fait confiance à un hub que pour son API, jamais pour l’interface, qui est livrée avec l’application.', 'device.this_device': 'Cet appareil', 'settings.keys_heading': 'Clés sur cet appareil', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Actuellement', - 'settings.hub_hint': 'Changer cette adresse vous déconnecte et redémarre la fenêtre.', + 'settings.hub_hint': 'Le hub auquel cette application se connecte. En changer vous déconnecte : votre compte reste sur ce hub.', 'settings.hub_change': 'Changer', 'settings.keys_where': 'Protégées par', 'settings.keys_unprotected': 'Aucun trousseau système ne fonctionne : vos clés sont chiffrées avec une clé qui n’est pas secrète. Quiconque peut lire les fichiers de cette machine peut les lire. Démarrez un trousseau, ou considérez cet appareil comme non fiable.', @@ -1246,6 +1251,7 @@ export default { 'home.accept': "Accepter", 'home.decline': "Refuser", 'members.invited': "invité", + 'members.awaiting_code': "en attente du code", 'hosts.title': "Hôtes", 'hosts.hint': "Vos propres nodes servent ce groupe sans rien demander. Un autre node ne le sert qu'une fois approuvé ici ; un node qui le demande apparaît ci-dessous.", 'hosts.none': "Aucun autre node n'a demandé à héberger ce groupe.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js index 579f8da..f3ff714 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/it.js @@ -123,6 +123,7 @@ export default { 'welcome.docs_devel': 'Documentazione tecnica', 'welcome.docs_design': 'Architettura', 'welcome.docs_protocol': 'Protocollo', + 'welcome.docs_api': 'API', 'welcome.download': 'Scarica (beta)', 'welcome.legal': 'Note legali', 'register.err_mismatch': 'Le password non coincidono', @@ -208,6 +209,11 @@ export default { 'group.mkdir_prompt': 'Nome della nuova cartella', 'group.mkdir_offline': 'Non connesso al nodo.', 'group.download_offline': 'Nessuna connessione al nodo — il download non può iniziare. La riconnessione è automatica, riprovi tra poco.', + 'group.link_unknown': "Questo link indica un gruppo di cui non sei membro, o che non ha più questo nome.", + 'group.link_path_unknown': "Non c'è nulla in {path} in questo gruppo: il file potrebbe essere stato spostato, rinominato o eliminato.", + 'link.copy': "Copia link", + 'link.copied': "Link copiato", + 'link.copy_failed': "Impossibile copiare — il link è {url}", 'group.download_write_stalled': 'Il file ha smesso di essere scritto su disco ({seconds} s senza progressi). Il download è stato interrotto invece di restare bloccato; riprovi.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -502,12 +508,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1245,6 +1250,7 @@ export default { 'home.accept': "Accetta", 'home.decline': "Rifiuta", 'members.invited': "invitato", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Host", 'hosts.hint': "I tuoi node servono questo gruppo senza chiedere. Un altro node lo serve solo dopo che lo approvi qui; un node che lo chiede compare qui sotto.", 'hosts.none': "Nessun altro node ha chiesto di ospitare questo gruppo.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js index cea7bfc..0690034 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/ja.js @@ -123,6 +123,7 @@ export default { 'welcome.docs_devel': '開発者向け', 'welcome.docs_design': '設計', 'welcome.docs_protocol': 'プロトコル', + 'welcome.docs_api': 'API', 'welcome.download': 'ダウンロード(ベータ版)', 'welcome.legal': '法的情報', 'register.err_mismatch': 'パスワードが一致しません', @@ -206,6 +207,11 @@ export default { 'group.mkdir_prompt': '新しいフォルダー名', 'group.mkdir_offline': 'ノードに接続していません。', 'group.download_offline': 'ノードに接続していません — ダウンロードを開始できません。再接続は自動で行われます。少し待って再試行してください。', + 'group.link_unknown': "このリンクは、あなたがメンバーでないグループ、またはもうその名前ではないグループを指しています。", + 'group.link_path_unknown': "このグループの {path} には何もありません。ファイルが移動、名前変更、または削除された可能性があります。", + 'link.copy': "リンクをコピー", + 'link.copied': "リンクをコピーしました", + 'link.copy_failed': "コピーできませんでした。リンク: {url}", 'group.download_write_stalled': 'ファイルのディスクへの書き込みが止まりました({seconds} 秒間進みません)。ぶら下がったままにせず中止しました。もう一度お試しください。', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -496,12 +502,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1229,6 +1234,7 @@ export default { 'home.accept': "承諾", 'home.decline': "辞退", 'members.invited': "招待中", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "ホスト", 'hosts.hint': "あなた自身の node は確認なしでこのグループを提供します。他の node は、ここで承認した後にのみ提供します。申請した node は下に表示されます。", 'hosts.none': "このグループのホストを申請した node は他にありません。", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js index 007154a..ce6312c 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/nl.js @@ -123,6 +123,7 @@ export default { 'welcome.docs_devel': 'Ontwikkelaarsdocs', 'welcome.docs_design': 'Ontwerp', 'welcome.docs_protocol': 'Protocol', + 'welcome.docs_api': 'API', 'welcome.download': 'Downloaden (bèta)', 'welcome.legal': 'Juridische informatie', 'register.err_mismatch': 'De wachtwoorden komen niet overeen', @@ -209,6 +210,11 @@ export default { 'group.mkdir_prompt': 'Naam van de nieuwe map', 'group.mkdir_offline': 'Niet verbonden met de node.', 'group.download_offline': 'Geen verbinding met de node — de download kan niet starten. Er wordt automatisch opnieuw verbonden; probeer het zo weer.', + 'group.link_unknown': "Deze link verwijst naar een groep waarvan je geen lid bent, of die niet meer zo heet.", + 'group.link_path_unknown': "Er staat niets op {path} in deze groep — het bestand is misschien verplaatst, hernoemd of verwijderd.", + 'link.copy': "Link kopiëren", + 'link.copied': "Link gekopieerd", + 'link.copy_failed': "Kopiëren mislukt — de link is {url}", 'group.download_write_stalled': 'Het bestand wordt niet meer naar schijf geschreven ({seconds} s zonder voortgang). De download is gestopt in plaats van te blijven hangen; probeer het opnieuw.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -503,12 +509,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1247,6 +1252,7 @@ export default { 'home.accept': "Accepteren", 'home.decline': "Weigeren", 'members.invited': "uitgenodigd", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Hosts", 'hosts.hint': "Uw eigen nodes bedienen deze groep zonder te vragen. Een andere node doet dat pas nadat u hem hier goedkeurt; een node die erom vraagt, staat hieronder.", 'hosts.none': "Geen andere node heeft gevraagd deze groep te hosten.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js index 7969cd0..2737532 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/pl.js @@ -126,6 +126,7 @@ export default { 'welcome.docs_devel': 'Dla programistów', 'welcome.docs_design': 'Architektura', 'welcome.docs_protocol': 'Protokół', + 'welcome.docs_api': 'API', 'welcome.download': 'Pobierz (beta)', 'welcome.legal': 'Informacje prawne', 'register.err_mismatch': 'Hasła nie są zgodne', @@ -212,6 +213,11 @@ export default { 'group.mkdir_prompt': 'Nazwa nowego folderu', 'group.mkdir_offline': 'Brak połączenia z węzłem.', 'group.download_offline': 'Brak połączenia z węzłem — pobieranie nie może się rozpocząć. Połączenie wróci samo; proszę spróbować za chwilę.', + 'group.link_unknown': "Ten link wskazuje grupę, do której nie należysz, lub która nie nosi już tej nazwy.", + 'group.link_path_unknown': "W tej grupie nie ma niczego pod {path} — plik mógł zostać przeniesiony, zmieniony lub usunięty.", + 'link.copy': "Kopiuj link", + 'link.copied': "Link skopiowany", + 'link.copy_failed': "Nie udało się skopiować — link to {url}", 'group.download_write_stalled': 'Plik przestał być zapisywany na dysk ({seconds} s bez postępu). Pobieranie zostało przerwane, zamiast wisieć w nieskończoność; proszę spróbować ponownie.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -515,12 +521,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1273,6 +1278,7 @@ export default { 'home.accept': "Akceptuj", 'home.decline': "Odrzuć", 'members.invited': "zaproszony", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Hosty", 'hosts.hint': "Twoje własne node'y obsługują tę grupę bez pytania. Inny node robi to dopiero po Twojej akceptacji tutaj; node, który o to prosi, jest widoczny poniżej.", 'hosts.none': "Żaden inny node nie prosił o hostowanie tej grupy.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js index 52d9d4c..c7cdf01 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/pt-BR.js @@ -124,6 +124,7 @@ export default { 'welcome.docs_devel': 'Docs de desenvolvimento', 'welcome.docs_design': 'Arquitetura', 'welcome.docs_protocol': 'Protocolo', + 'welcome.docs_api': 'API', 'welcome.download': 'Baixar (beta)', 'welcome.legal': 'Informações legais', 'register.err_mismatch': 'As senhas não coincidem', @@ -209,6 +210,11 @@ export default { 'group.mkdir_prompt': 'Nome da nova pasta', 'group.mkdir_offline': 'Sem conexão com o nó.', 'group.download_offline': 'Sem conexão com o nó — o download não pode começar. Ele reconecta sozinho; tente de novo em instantes.', + 'group.link_unknown': "Este link aponta para um grupo do qual você não é membro, ou que não tem mais esse nome.", + 'group.link_path_unknown': "Não há nada em {path} neste grupo — o arquivo pode ter sido movido, renomeado ou excluído.", + 'link.copy': "Copiar link", + 'link.copied': "Link copiado", + 'link.copy_failed': "Não foi possível copiar — o link é {url}", 'group.download_write_stalled': 'O arquivo parou de ser gravado no disco ({seconds}s sem progresso). O download foi interrompido em vez de ficar travado; tente de novo.', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -501,12 +507,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1232,6 +1237,7 @@ export default { 'home.accept': "Aceitar", 'home.decline': "Recusar", 'members.invited': "convidado", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "Hosts", 'hosts.hint': "Seus próprios nodes servem este grupo sem perguntar. Outro node só o serve depois que você o aprova aqui; um node que pede aparece abaixo.", 'hosts.none': "Nenhum outro node pediu para hospedar este grupo.", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js index 3739dcf..06f61ff 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/zh-CN.js @@ -123,6 +123,7 @@ export default { 'welcome.docs_devel': '开发文档', 'welcome.docs_design': '设计', 'welcome.docs_protocol': '协议', + 'welcome.docs_api': 'API', 'welcome.download': '下载(测试版)', 'welcome.legal': '法律信息', 'register.err_mismatch': '两次输入的密码不一致', @@ -205,6 +206,11 @@ export default { 'group.mkdir_prompt': '新文件夹名称', 'group.mkdir_offline': '未连接到节点。', 'group.download_offline': '未连接到节点 — 无法开始下载。连接会自动恢复,请稍后重试。', + 'group.link_unknown': "此链接指向一个您不是其成员的群组,或该群组已不再使用此名称。", + 'group.link_path_unknown': "此群组中 {path} 处没有内容——文件可能已被移动、重命名或删除。", + 'link.copy': "复制链接", + 'link.copied': "链接已复制", + 'link.copy_failed': "无法复制——链接为 {url}", 'group.download_write_stalled': '文件停止写入磁盘({seconds} 秒无进展)。已中止下载而不是让它一直卡住,请重试。', 'device.add_title': 'This browser is not linked to this node yet', 'device.add_hint': 'Your account is known here, but this browser holds a different key. Approve it from a device already linked — no operator needed.', @@ -490,12 +496,11 @@ export default { 'firstrun.hint': 'A hub holds your account and introduces you to nodes. It never sees your files, your messages or your keys.', 'firstrun.btn': 'Continue', 'firstrun.checking': 'Checking…', - 'firstrun.note': 'There is no default on purpose: this application only trusts a hub for its API, never for the interface, which ships with the application itself.', 'device.this_device': 'This device', 'settings.keys_heading': 'Keys on this device', 'settings.hub_heading': 'Hub', 'settings.hub_current': 'Currently', - 'settings.hub_hint': 'Changing this signs you out and restarts the window.', + 'settings.hub_hint': 'The hub this application connects to. Changing it signs you out: your account stays on this hub.', 'settings.hub_change': 'Change', 'settings.keys_where': 'Protected by', 'settings.keys_unprotected': 'No system keyring is running, so your keys are encrypted with a key that is not a secret. Anyone who can read this machine’s files can read them. Start a keyring, or treat this device as untrusted.', @@ -1218,6 +1223,7 @@ export default { 'home.accept': "接受", 'home.decline': "拒绝", 'members.invited': "已邀请", + 'members.awaiting_code': "waiting for their code", 'hosts.title': "主机", 'hosts.hint': "你自己的 node 无需询问即可提供此群组。其他 node 只有在你于此处批准后才会提供;提出申请的 node 列在下方。", 'hosts.none': "没有其他 node 申请托管此群组。", diff --git a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js index f2c4374..9adb1e1 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js @@ -11,6 +11,7 @@ import { Menu, MenuDots, useMenu } from './menu.js'; import { PlaylistMenuButton, NameModal, usePlaylists } from './playlist-menu.js'; import * as P from './playlists.js'; import { CastButton } from './cast-session.js'; +import { copyLink } from './copy-link.js'; // -- Music -------------------------------------------------------------------- // @@ -564,7 +565,7 @@ function FlatList({ items, onPlayQueue, onMenu }) { function MusicApp({ groupId, transportRef, gekRef, status, entries, availableEntries, musicDirectories, musicbrainzConfig, onPlayQueue, userId, - hideFilter, userPrefs, pageResetKey, + hideFilter, userPrefs, pageResetKey, linkFor, }) { const [mode, setMode] = useState(loadViewMode); const [filter, setFilter] = useState(''); @@ -618,6 +619,9 @@ function MusicApp({ // argument slot for one. const onMenu = useCallback((e, tracks, startIndex) => { if (!tracks || !tracks.length) return; + // One track's menu — a row's, whose dots are how a phone opens it. An + // album's carries all its tracks and gets no link: Files has the folder's. + const link = tracks.length === 1 && linkFor ? linkFor(tracks[0]) : null; openAt(e, [ { label: t('music.menu_play'), icon: 'play', onSelect: () => onPlayQueue(tracks, startIndex || 0) }, @@ -650,8 +654,10 @@ function MusicApp({ }, ], }, + ...(link ? [{ divider: true }, + { label: t('link.copy'), icon: 'link', onSelect: () => copyLink(link) }] : []), ]); - }, [openAt, onPlayQueue, playlists, addToPlaylist]); + }, [openAt, onPlayQueue, playlists, addToPlaylist, linkFor]); useEffect(() => { setMode(loadViewMode()); }, [groupId]); useEffect(() => { setFilter(''); }, [groupId]); diff --git a/packages/meshbay-hub/src/meshbay_hub/static/note.js b/packages/meshbay-hub/src/meshbay_hub/static/note.js new file mode 100644 index 0000000..f55c307 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/note.js @@ -0,0 +1,24 @@ +/** + * A line said once and gone, in the playlists' note (style.css + * `.playlist-note`): "Link copied", "2 groups unreachable". Not a dialog — + * nothing here is anyone's to dismiss. + * + * Appended to the body rather than rendered by a view, because the views that + * speak include modals and a context menu that has already closed. One note + * at a time: a second replaces the first and restarts the clock. + */ + +let _note = null; +let _timer = null; + +export function say(text, ms = 2500) { + if (!_note) { + _note = document.createElement('div'); + _note.className = 'playlist-note page-note'; + _note.setAttribute('role', 'status'); + } + _note.textContent = text; + document.body.appendChild(_note); + clearTimeout(_timer); + _timer = setTimeout(() => { if (_note) _note.remove(); }, ms); +} diff --git a/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js b/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js index 00bc288..afc815a 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js @@ -10,6 +10,8 @@ import { transfers } from './transfers.js'; import { MediaThumb, LazyTile } from './media-tiles.js'; import { SourceTag } from './group-name.js'; import { CastButton, castSession, useCastDevice, showPhoto } from './cast-session.js'; +import { Menu, useMenu } from './menu.js'; +import { copyLink } from './copy-link.js'; // ── Photos ─────────────────────────────────────────────────────────────────── // @@ -118,11 +120,11 @@ function AlbumLanding({ albums, transportRef, gekRef, onOpen }) { // ── open album: grid of its own photos ────────────────────────────────────── -function PhotoTile({ entry, transportRef, gekRef, onOpen }) { +function PhotoTile({ entry, transportRef, gekRef, onOpen, onMenu }) { const tRef = entry._tRef || transportRef; const gRef = entry._gRef || gekRef; return html` - <div class="photo-tile" onClick=${onOpen}> + <div class="photo-tile" onClick=${onOpen} onContextMenu=${onMenu}> <${MediaThumb} thumbHash=${entry.thumb_hash} alt=${entry.name} cls="photo-tile-thumb" transportRef=${tRef} gekRef=${gRef} emptyIcon="image" /> @@ -153,7 +155,7 @@ const ZOOM_MAX = 400; // a slow node must not skip a photo nobody saw. const SLIDESHOW_MS = 5000; -function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) { +function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav, linkFor }) { const entry = photos[index]; const tRef = entry._tRef || transportRef; const gRef = entry._gRef || gekRef; @@ -284,6 +286,10 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) { aria-pressed=${slideshow ? 'true' : 'false'}> <${Icon} name=${slideshow ? 'pause' : 'play'} /></button> <${CastButton} variant="overlay" cls="video-close" /> + ${linkFor && linkFor(entry) && html` + <button class="video-close" onClick=${() => copyLink(linkFor(entry))} + title=${t('link.copy')} aria-label=${t('link.copy')}> + <${Icon} name="link" /></button>`} <button class="video-close" onClick=${onClose} title=${t('video.close')}> <${Icon} name="close" /></button> </div> @@ -311,8 +317,16 @@ function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) { `; } -function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, readOnly }) { +function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, readOnly, linkFor }) { const [lightboxIndex, setLightboxIndex] = useState(null); + // Right-click a photo for its link. A tile has no dots to press, so on a + // touchscreen the link is in the lightbox's bar instead. + const { menu, openAt, close: closeMenu } = useMenu(); + const onTileMenu = (e, entry) => { + const link = linkFor ? linkFor(entry) : null; + if (!link) return; + openAt(e, [{ label: t('link.copy'), icon: 'link', onSelect: () => copyLink(link) }]); + }; const zip = useCallback(async () => { const transport = transportRef.current; @@ -352,15 +366,16 @@ function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, rea ${album.photos.map((e, i) => html` <${LazyTile} key=${e.id} cls="photo-tile-slot"> <${PhotoTile} entry=${e} transportRef=${transportRef} gekRef=${gekRef} - onOpen=${() => setLightboxIndex(i)} /> + onOpen=${() => setLightboxIndex(i)} onMenu=${(ev) => onTileMenu(ev, e)} /> </${LazyTile}> `)} </div> ${lightboxIndex !== null && html` <${Lightbox} photos=${album.photos} index=${lightboxIndex} transportRef=${transportRef} gekRef=${gekRef} - onClose=${() => setLightboxIndex(null)} onNav=${navigate} /> + onClose=${() => setLightboxIndex(null)} onNav=${navigate} linkFor=${linkFor} /> `} + ${menu && html`<${Menu} ...${menu} onClose=${closeMenu} />`} `; } @@ -369,7 +384,7 @@ function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, rea function PhotosApp({ groupId, transportRef, gekRef, status, entries, availableEntries, photoDirectories, setError, - hideFilter, readOnly, + hideFilter, readOnly, linkFor, }) { const [openDir, setOpenDir] = useState(null); const [filter, setFilter] = useState(''); @@ -423,7 +438,7 @@ function PhotosApp({ ${status === 'connected' && openAlbum && html` <${AlbumView} album=${openAlbum} entries=${entries} transportRef=${transportRef} gekRef=${gekRef} setError=${setError} - onBack=${() => setOpenDir(null)} readOnly=${readOnly} /> + onBack=${() => setOpenDir(null)} readOnly=${readOnly} linkFor=${linkFor} /> `} `; } diff --git a/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js b/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js index 6323b96..2a24160 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/playlist-crypto.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * Sealing a playlist blob, and opening one. * diff --git a/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js b/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js index 1800d72..aac3c14 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js @@ -27,6 +27,8 @@ async function lockedMessage(token) { export function ProfilePage({ user, onLogout }) { const [nodeKey, setNodeKey] = useState(''); + const [hubInput, setHubInput] = useState(''); + const [hubError, setHubError] = useState(''); const [currentNodeKey, setCurrentNodeKey] = useState(null); const [nodeKeyStatus, setNodeKeyStatus] = useState(''); const [nodeKeyLoading, setNodeKeyLoading] = useState(false); @@ -602,6 +604,29 @@ export function ProfilePage({ user, onLogout }) { </button> </div> + ${platform.isNative && html` + <div class="settings-section"> + <h3 class="settings-heading">${t('settings.hub_heading')}</h3> + <div class="settings-row"> + <span class="settings-label">${t('settings.hub_current')}</span> + <span class="settings-value">${platform.hubBase() || '—'}</span> + </div> + <p class="settings-hint">${t('settings.hub_hint')}</p> + <form onSubmit=${async (e) => { + e.preventDefault(); + setHubError(''); + try { + await window.meshbay.setHubBase(hubInput.trim()); + } catch (err) { setHubError(platform.bridgeMessage(err)); } + }} style="display:flex;gap:8px"> + <input type="text" placeholder=${platform.hubBase()} + value=${hubInput} onInput=${e => setHubInput(e.target.value)} /> + <button class="admin-btn" type="submit">${t('settings.hub_change')}</button> + </form> + ${hubError && html`<p class="error-msg">${hubError}</p>`} + </div> + `} + <div class="settings-section"> <h3 class="settings-heading">${t('settings.danger')}</h3> <p class="settings-hint">${t('settings.delete_hint')}</p> diff --git a/packages/meshbay-hub/src/meshbay_hub/static/search-page.js b/packages/meshbay-hub/src/meshbay_hub/static/search-page.js index 874b7b0..ae8eac7 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/search-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/search-page.js @@ -13,6 +13,8 @@ import { MusicApp, groupMusicEntries, foldKey } from './music-app.js'; import { PhotosApp, groupPhotoAlbums } from './photos-app.js'; import { VideoPlayer } from './video-player.js'; import { transfers } from './transfers.js'; +import { copyLink, entryPath, groupItemLink } from './copy-link.js'; +import { say } from './note.js'; import { mergeUnitEntries } from './source-merge.js'; import { useStickyBand } from './sticky.js'; import { ConnectionPool, MAX_IN_FLIGHT, MAX_POOL_SIZE } from './connection-pool.js'; @@ -21,6 +23,8 @@ const DEBOUNCE_MS = 200; const SEARCH_VIDEO_ROOT = '__search__'; const SEARCH_AUDIO_ROOT = '__search__'; const SEARCH_PHOTO_ROOTS = ['__search_photos__']; +// How long "N groups unreachable" stays up once a search pass is over. +const UNREACHABLE_NOTE_MS = 5000; // -- Index fetching ----------------------------------------------------------- @@ -312,13 +316,20 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) setProgress({ done: 0, total: groups.length, unreachable: [] }); if (!poolRef.current) return; - await fetchAllIndexes( + const { unreachable } = await fetchAllIndexes( poolRef.current, groups, token, username, userId, (p) => { if (!cancelled) setProgress(p); }, (results) => { if (!cancelled) setIndexedGroups(new Map(results)); }, ); - if (!cancelled) setFetching(false); + if (cancelled) return; + setFetching(false); + // Said once the pass is over, for a few seconds, rather than left above + // the results: by then nothing more can be done about it here, and a + // line that stays is one more thing between the reader and the results. + if (unreachable.length) { + say(t('search.unreachable', { n: unreachable.length }), UNREACHABLE_NOTE_MS); + } })(); return () => { cancelled = true; }; @@ -514,6 +525,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) result.push({ ...e, path: SEARCH_VIDEO_ROOT + '/' + e.path, + _origPath: e.path, groupId, groupName: data.groupName, groupOwner: data.groupOwner, @@ -540,6 +552,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) result.push({ ...e, path: SEARCH_AUDIO_ROOT + '/' + e.path, + _origPath: e.path, groupId, groupName: data.groupName, groupOwner: data.groupOwner, @@ -567,6 +580,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) result.push({ ...e, path: '__search_photos__/' + e.path, + _origPath: e.path, groupId, groupName: data.groupName, groupOwner: data.groupOwner, @@ -640,6 +654,19 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) // No-op setters for FilesPanel const noop = useCallback(() => {}, []); + + // "Copy link" for a result: its own group's handle and its path there, from + // `_origPath` — every view here prefixes `path` to merge groups into one tree. + // A merged entry is the source it was resolved to (source-merge.js), so the + // link names a group that has the file. A folder is a path in that merged + // tree, named by group name alone, which two owners may share: no link. + const linkFor = useCallback((target) => { + if (!target || typeof target === 'string' || !target.groupName || !target.groupOwner) { + return null; + } + return groupItemLink({ name: target.groupName, owner_username: target.groupOwner }, + entryPath(target, target._origPath)); + }, []); // The search field and its view toggle are this page's equivalent of a // group's tab bar: the same band, pinned the same way, publishing the same // property for the toolbar underneath (style.css, "Sticky chrome"). @@ -698,11 +725,6 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) </div> `} - ${progress.unreachable.length > 0 && html` - <p class="search-unreachable"> - ${t('search.unreachable', { n: progress.unreachable.length })} - </p> - `} ${viewMode === 'files' && hasResults && html` <${FilesPanel} @@ -726,6 +748,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) readOnly=${true} getTransport=${getTransport} showRefresh=${true} + linkFor=${linkFor} onRefreshIndex=${() => setRefreshTick((n) => n + 1)} /> `} @@ -754,7 +777,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) entries=${musicEntries} musicDirectories=${[SEARCH_AUDIO_ROOT]} musicbrainzConfig=${{ enabled: true }} - onPlayQueue=${handleMusicPlay} userId=${userId} + onPlayQueue=${handleMusicPlay} userId=${userId} linkFor=${linkFor} userPrefs=${userPrefs} pageResetKey=${q} hideFilter=${true} /> `} @@ -767,7 +790,7 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) status="connected" entries=${photoEntries} photoDirectories=${SEARCH_PHOTO_ROOTS} - setError=${noop} + setError=${noop} linkFor=${linkFor} hideFilter=${true} readOnly=${true} /> `} @@ -788,7 +811,8 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) transportRef=${modalTransportRef} gekRef=${modalGekRef} onClose=${() => setPreviewEntry(null)} - onDownload=${() => downloadForModal(previewEntry)} /> + onDownload=${() => downloadForModal(previewEntry)} + onCopyLink=${linkFor(previewEntry) && (() => copyLink(linkFor(previewEntry)))} /> `} ${videoEntry && html` <${VideoPlayer} @@ -796,7 +820,8 @@ function SearchPage({ token, username, userId, groups, onPlayQueue, userPrefs }) transportRef=${modalTransportRef} gekRef=${modalGekRef} onClose=${() => setVideoEntry(null)} - onDownload=${() => downloadForModal(videoEntry)} /> + onDownload=${() => downloadForModal(videoEntry)} + onCopyLink=${linkFor(videoEntry) && (() => copyLink(linkFor(videoEntry)))} /> `} </div> `; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js b/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js index 9a52059..8755556 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/settings-page.js @@ -131,8 +131,6 @@ export function SettingsPage({ user, theme, onThemeChange, groups, onPrefsChange // Changing the hub after the first run. Without this a typo on the first // screen was permanent: the prompt only appears when no hub is set, so a // wrong one left editing a JSON file by hand as the only way out. - const [hubInput, setHubInput] = useState(''); - const [hubError, setHubError] = useState(''); useEffect(() => { if (!platform.secrets.available) return; platform.secrets.backend().then(setKeyBackend).catch(() => {}); @@ -287,29 +285,6 @@ export function SettingsPage({ user, theme, onThemeChange, groups, onPrefsChange <p class="settings-hint">${t('settings.music_keep_screen_on_hint')}</p> </div> - ${platform.isNative && html` - <div class="settings-section"> - <h3 class="settings-heading">${t('settings.hub_heading')}</h3> - <div class="settings-row"> - <span class="settings-label">${t('settings.hub_current')}</span> - <span class="settings-value">${platform.hubBase() || '—'}</span> - </div> - <p class="settings-hint">${t('settings.hub_hint')}</p> - <form onSubmit=${async (e) => { - e.preventDefault(); - setHubError(''); - try { - await window.meshbay.setHubBase(hubInput.trim()); - } catch (err) { setHubError(platform.bridgeMessage(err)); } - }} style="display:flex;gap:8px"> - <input type="text" placeholder=${platform.hubBase()} - value=${hubInput} onInput=${e => setHubInput(e.target.value)} /> - <button class="admin-btn" type="submit">${t('settings.hub_change')}</button> - </form> - ${hubError && html`<p class="error-msg">${hubError}</p>`} - </div> - `} - ${keyBackend && html` <div class="settings-section"> <h3 class="settings-heading">${t('settings.keys_heading')}</h3> diff --git a/packages/meshbay-hub/src/meshbay_hub/static/style.css b/packages/meshbay-hub/src/meshbay_hub/static/style.css index 9383043..21d92df 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/style.css +++ b/packages/meshbay-hub/src/meshbay_hub/static/style.css @@ -156,10 +156,6 @@ a:hover { text-decoration: underline; } height: 100%; background: var(--accent); transition: width 0.3s; } -.search-unreachable { - font-size: 0.8em; color: var(--text-dim); margin-bottom: 8px; -} - .view-toggle { display: flex; gap: 0; flex-shrink: 0; margin-left: auto; } @@ -5613,6 +5609,14 @@ h2 .gn-owner, h3 .gn-owner { font-size: 0.55em; } overflow: hidden; text-overflow: ellipsis; } +/* The same note, said from anywhere (note.js). It can carry a link the + clipboard refused, which must be readable whole rather than cut. */ +.page-note.playlist-note { + white-space: normal; + overflow-wrap: anywhere; + border-radius: 12px; + text-align: center; +} /* A run of single-album artists, pooled into one grid so five of them fill one row instead of spending five (music-app.js `albumSections`). diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js index 63cb644..7bc77af 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-admin.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // The operator's side: signed operations (the two-step challenge), the node's // settings and roots, members and invitations. // diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js index b734d44..96e06d7 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-chat.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // The group chat: history, sending, link previews, and the epoch keys that // seal it. // diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js index eba0461..b2356e8 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-codec.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // The wire codec: the subset of msgpack MNP uses (maps, strings, integers, // binary, arrays, null), and hex for the ids the transport mints. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js index 1c6fc78..f079f80 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-devices.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // An account's devices and what they hold: joining a group, linking a device, // the identity bundles and the per-account blobs (playlists). // @@ -21,7 +23,10 @@ extendTransport(class { * at first sight, where there is nothing to compare against — that boundary * is `docs/MESHBAY_DESIGN.md` §3.2's and does not move. */ - async groupRoster() { + async groupRoster({ fresh = false } = {}) { + // `fresh`: read it again rather than keep this connection's copy, for a + // page that lists the members and must show who joined since. + if (fresh && !this._rosterInFlight) this._roster = null; if (this._roster) return this._roster; if (this._rosterInFlight) return this._rosterInFlight; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js index b4d4048..ca015b9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-media.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // What the media apps ask the node for: TMDB and MusicBrainz metadata, audio // transcoding, subtitles, and the video stream. // diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js index c0699dc..c32901b 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-pins.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // Which node this browser has met under which key (trust on first use), and // the version range a node declares at the handshake. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js index cdf86b0..fb2f5cf 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-rewrap.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // A passphrase change, carried to every node that holds this account's // identity bundle. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js index ca0769d..cac3b52 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-roster.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // What a node says about who is in a group, checked rather than trusted: the // roster's signatures, and the keys this browser pinned for each account. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js b/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js index 9f4b531..a8f039d 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport-upload.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. // Uploads: a whole file, sealed chunk by chunk with several in flight, and the // folders it lands in. // diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport.js b/packages/meshbay-hub/src/meshbay_hub/static/transport.js index 279396a..5ed6fa9 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport.js @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// Part of MeshBay's protocol layer, under the LGPL so that any client may use it. /** * MeshBay Browser Transport — WebRTC DataChannel client. * diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt b/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt new file mode 100644 index 0000000..aa2f6a9 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/LICENSES.txt @@ -0,0 +1,268 @@ +Licences of the third-party files in this directory +==================================================== + +Each file below is redistributed unmodified; PROVENANCE.md records exactly +which release it was taken from. This file travels with them wherever the +interface is copied (hub, desktop client, Android application). + +htm-preact.js htm 3.1.1 (Apache-2.0), with Preact 10 bundled into it (MIT) +argon2.min.js argon2-browser 1.18.0 (MIT), compiling the Argon2 reference +argon2.wasm implementation (CC0-1.0 OR Apache-2.0; taken under CC0-1.0) + + +============================================================================== +htm — Apache License 2.0 +============================================================================== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +============================================================================== +Preact — MIT License +============================================================================== + +The MIT License (MIT) + +Copyright (c) 2015-present Jason Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +============================================================================== +argon2-browser — MIT License +============================================================================== + +Copyright © 2021 Antelle + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +============================================================================== +Argon2 reference implementation — CC0-1.0 +============================================================================== + +The Argon2 reference implementation (https://github.com/P-H-C/phc-winner-argon2) +is dual-licensed under CC0 1.0 Universal or the Apache License 2.0, at the +recipient's choice. It is used here under CC0 1.0, which waives copyright and +asks for no notice: https://creativecommons.org/publicdomain/zero/1.0/legalcode diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md index 6935e91..53d4af3 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md +++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md @@ -34,3 +34,25 @@ The browser never requests it — `argon2.min.js` carries the same bytes inline a data URL. It is kept because the cross-language parity test drives the vendored library under node, where the emscripten loader takes its file path instead of the inline copy, and a test that cannot run is a test that stops being true. + +## htm-preact.js + +| | | +|---|---| +| Package | `htm` 3.1.1 (npm) — Apache-2.0 | +| Source | https://registry.npmjs.org/htm/-/htm-3.1.1.tgz | +| Tarball sha256 | `2425b9bee11409177bcabc7f32e319926fc6690c1701c0b257c88bdff2d5ba90` | +| Tarball sha1 (npm dist.shasum) | `49266582be0dc66ed2235d5ea892307cc0c24b78` | +| File taken | `package/preact/standalone.module.js` | +| File sha256 | `72284e8e9079c87817145df1110f74e8a2aa040b2fc384922e18dfcb46fc1fd7` | + +htm's "standalone" build: htm and Preact 10 (MIT) with its hooks, in one ES +module, so the SPA has a component model without a bundler or a second request. +The same bytes ship in htm 3.1.0; this entry was identified after the fact, by +matching the committed file against both releases. + +## Licences + +`LICENSES.txt`, beside these files, carries the licence text of each of them; +the MIT and Apache licences both ask for it to travel with every copy. A file +added here adds its licence there. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js index 37ea727..21abe8e 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js @@ -403,7 +403,7 @@ function purgeUnscopedResumePositions() { purgeUnscopedResumePositions(); -function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) { +function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload, onCopyLink }) { const [dlBusy, setDlBusy] = useState(false); const [phase, setPhase] = useState('loading'); const [error, setError] = useState(''); @@ -1957,6 +1957,11 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) { } </span> `} + ${onCopyLink && html` + <button class="video-close" onClick=${onCopyLink} + title="${t('link.copy')}" aria-label="${t('link.copy')}"> + <${Icon} name="link" /></button> + `} ${onDownload && html` <button class="video-close ${dlBusy ? 'dl-active' : ''}" disabled=${dlBusy} onClick=${() => { diff --git a/packages/meshbay-hub/tests/harness/copy_link_probe.py b/packages/meshbay-hub/tests/harness/copy_link_probe.py new file mode 100644 index 0000000..564d277 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/copy_link_probe.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +""" +"Copy link" in Files, Music and Photos, in a real browser. + +Mounts the shipped `FilesPanel`, `MusicApp` and `PhotosApp` on a made-up +index — no node, no transport — with the `linkFor` a group page gives them, +built by the real `copy-link.js` for a group `demo@someowner`. Opens each +menu the way a reader would (right-click; the dots on a phone; the Files +toolbar with one row ticked), picks "Copy link", and reads back what reached +the clipboard and what the page said. + + copy_link_probe.py + +Prints JSON: one entry per case. +""" + +import http.server +import json +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8775 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +FRAME = r"""<!doctype html><html><head><meta charset=utf-8> +<link rel="stylesheet" href="/style.css"></head><body> +<div id="files"></div><div id="music"></div><div id="photos"></div> +<script type="module"> +import { html, render } from '/vendor/htm-preact.js'; +import { initLocale, setLocale } from '/i18n.js'; +import { FilesPanel } from '/files-app.js'; +import { MusicApp } from '/music-app.js'; +import { PhotosApp } from '/photos-app.js'; +import { groupItemLink, entryPath } from '/copy-link.js'; + +const LOGS = []; +addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e))); +addEventListener('unhandledrejection', + (e) => LOGS.push('rejection: ' + (e.reason && e.reason.message || e.reason))); +const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +// What the clipboard was handed, and nothing else: a headless page has no +// clipboard permission to test against. +const COPIES = []; +Object.defineProperty(navigator, 'clipboard', { configurable: true, + value: { writeText: async (text) => { COPIES.push(text); } } }); + +const GROUP = { name: 'demo', owner_username: 'someowner' }; +const linkFor = (target) => (target + ? groupItemLink(GROUP, typeof target === 'string' ? target : entryPath(target)) : null); +const noop = () => {}; +const ref = { current: null }; + +const labels = () => [...document.querySelectorAll('.ctx-menu .ctx-menu-label')] + .map((el) => el.textContent); +const pick = async (label) => { + const item = [...document.querySelectorAll('.ctx-menu .ctx-menu-item')] + .find((b) => b.querySelector('.ctx-menu-label').textContent === label); + if (!item) return false; + item.click(); + await wait(50); + return true; +}; +const note = () => (document.querySelector('.page-note') || {}).textContent || ''; +const closeMenus = async () => { + document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + await frame(); +}; +const rightClick = async (el) => { + await closeMenus(); + const r = el.getBoundingClientRect(); + el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, + clientX: r.left + 10, clientY: r.top + 5 })); + await frame(); +}; +const rowNamed = (name) => [...document.querySelectorAll('tr.file-row')] + .find((tr) => tr.querySelector('.file-name') + && tr.querySelector('.file-name').textContent.trim().startsWith(name)); + +(async () => { + const cases = []; + try { + setLocale('en'); + await initLocale(); + try { localStorage.setItem('meshbay_music_view_mode', 'flat'); } catch {} + + // -- Files -- + const FILES = [ + { id: 'f1', name: 'IMG 0001.JPG', path: 'Root/trip_2015', size: 10, type: 'image', + added_at: 1 }, + { id: 'f2', name: 'notes.txt', path: 'Root/trip_2015', size: 5, type: 'document', + added_at: 2 }, + ]; + render(html`<${FilesPanel} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${FILES} nodeDirs=${['Root', 'Root/trip_2015']} + nodeRoots=${[{ name: 'Root', writable: false }]} + setEntries=${noop} setNodeDirs=${noop} setNodeRoots=${noop} applyIndex=${noop} + isNodeAdmin=${false} operatorPaired=${false} userId="me" setError=${noop} + onPreview=${noop} linkFor=${linkFor} />`, document.getElementById('files')); + await frame(); + + await rightClick(rowNamed('Root')); + const folderLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files folder', labels: folderLabels, copied: COPIES.at(-1), note: note() }); + + rowNamed('Root').click(); await frame(); + rowNamed('trip_2015').click(); await frame(); + await rightClick(rowNamed('IMG 0001.JPG')); + const fileLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files file', labels: fileLabels, copied: COPIES.at(-1), note: note() }); + + await closeMenus(); + const linkBtn = () => document.querySelector('.tb-actions button[aria-label="Copy link"]'); + rowNamed('notes.txt').querySelector('input[type=checkbox]').click(); await frame(); + const oneTicked = linkBtn() ? !linkBtn().disabled : null; + if (linkBtn() && !linkBtn().disabled) { linkBtn().click(); await wait(50); } + const copiedFromToolbar = COPIES.at(-1); + for (const n of ['IMG 0001.JPG', 'notes.txt']) { + rowNamed(n).querySelector('input[type=checkbox]').click(); await frame(); + } + const twoTicked = linkBtn() ? !linkBtn().disabled : null; + cases.push({ case: 'files toolbar', one_enabled: oneTicked, two_enabled: twoTicked, + copied: copiedFromToolbar }); + render(null, document.getElementById('files')); + + // -- Music: a loose track, its row's dots (what a phone has) -- + const TRACKS = [ + { id: 'a1', name: 'track 01.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + { id: 'a2', name: 'track 02.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + ]; + render(html`<${MusicApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${TRACKS} musicDirectories=${['Music']} + musicbrainzConfig=${{ enabled: false }} onPlayQueue=${noop} userId="" + linkFor=${linkFor} />`, document.getElementById('music')); + await frame(); + await closeMenus(); + const dots = document.querySelector('.music-flat-track .ctx-dots'); + if (dots) { dots.click(); await frame(); } + const trackLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'music track', dots: Boolean(dots), labels: trackLabels, + copied: COPIES.at(-1) }); + render(null, document.getElementById('music')); + + // -- Photos: right-click a tile; the lightbox's button -- + const PHOTOS = [ + { id: 'p1', name: 'beach.jpg', path: 'Pics/Summer', size: 4, type: 'image', added_at: 1 }, + ]; + render(html`<${PhotosApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${PHOTOS} photoDirectories=${['Pics']} + setError=${noop} linkFor=${linkFor} />`, document.getElementById('photos')); + await frame(); + const album = document.querySelector('.photo-album-card'); + if (album) { album.click(); await frame(); } + const tile = document.querySelector('.photo-tile'); + let tileLabels = []; + if (tile) { + await rightClick(tile); + tileLabels = labels(); + await pick('Copy link'); + } + const fromTile = COPIES.at(-1); + if (tile) { tile.click(); await frame(); } + const lb = document.querySelector('.photo-lightbox button[aria-label="Copy link"]'); + COPIES.length = 0; + if (lb) { lb.click(); await wait(50); } + cases.push({ case: 'photos', tile: Boolean(tile), labels: tileLabels, copied: fromTile, + lightbox_button: Boolean(lb), lightbox_copied: COPIES.at(-1) || null }); + + // Said, then gone (note.js): still up just after, not 2.5 s later. + const upAfterCopy = Boolean(document.querySelector('.page-note')); + await wait(2700); + cases.push({ case: 'note goes', up_after_copy: upAfterCopy, + up_later: Boolean(document.querySelector('.page-note')) }); + + parent.postMessage({ cases, logs: LOGS, origin: location.origin }, '*'); + } catch (err) { + parent.postMessage({ error: String(err && (err.stack || err)), logs: LOGS }, '*'); + } +})(); +</script></body></html>""" + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head> +<body style="margin:0"><div id="frames"></div><script> +addEventListener('message', (e) => { + fetch('/log', { method: 'POST', body: JSON.stringify(e.data) }); +}); +const f = document.createElement('iframe'); +f.src = '/case'; +f.style.cssText = 'width:1100px;height:800px;border:0;display:block'; +document.getElementById('frames').appendChild(f); +</script></body></html>""" + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + if self.path == "/log": + RECORDS.append(json.loads(self.rfile.read(length).decode())) + else: + self.rfile.read(length) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = self.path.split("?")[0] + if path == "/": + self._send(PAGE.encode(), "text/html; charset=utf-8") + elif path == "/case": + self._send(FRAME.encode(), "text/html; charset=utf-8") + else: + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + self._send(asset.read_bytes(), + "text/css" if asset.suffix == ".css" + else "text/javascript" if asset.suffix == ".js" + else "application/octet-stream") + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile: + proc = subprocess.Popen( + ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", "--window-size=1100,900", + f"http://127.0.0.1:{PORT}/"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if RECORDS: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + if not RECORDS: + print(json.dumps({"error": "no measurement"}), file=sys.stderr) + return 1 + print(json.dumps(RECORDS[0], indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/harness/group_link_probe.py b/packages/meshbay-hub/tests/harness/group_link_probe.py new file mode 100644 index 0000000..2d7c0d7 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/group_link_probe.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +""" +A group link, `#/name@owner[/path]`, opened in the real application. + +`test_group_link.py` runs `group-link.js` on its own; this is where it meets +the router, the account's group list and the sign-in state. Loads the shipped +`app.js` in a real browser with `fetch` stubbed (no node answers, so a group +page goes as far as "offline"), once per case: + + handle — `#/demo@someowner`: the group page, the address left as it is + uuid — `#/group/<id>`: the same page, the address showing the handle + file — `#/demo@someowner/<path>`: the page, the path kept in the address + until the index can say what it is (no node here: never) + unknown — `#/demo@stranger1`: not among the account's groups + signed_out — `#/demo@someowner/<path>` with no session: the sign-in form, and + the address untouched under it + + group_link_probe.py + +Prints JSON: one object per case. +""" + +import http.server +import json +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8774 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e" +FILE = "backup/city_2015/backup/IMG_0001.JPG" +LINKS = { + "handle": "#/demo@someowner", + "uuid": f"#/group/{GROUP}", + "file": f"#/demo@someowner/{FILE}", + "unknown": "#/demo@stranger1", + "signed_out": f"#/demo@someowner/{FILE}", +} +CASES = list(LINKS) + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head><body> +<div id="app"></div> +<script type="module"> +const CASE = new URLSearchParams(location.search).get('case'); +const LINKS = __LINKS__; +const realFetch = window.fetch.bind(window); +const post = (o) => realFetch('/log', { method: 'POST', body: JSON.stringify(o) }); +const calls = []; +const json = (body, status = 200) => ({ + ok: status < 400, status, statusText: '', headers: new Headers(), + json: async () => body, text: async () => JSON.stringify(body), +}); +window.fetch = async (url, init = {}) => { + const u = String(url); + calls.push(u); + if (u.includes('/v1/users/me/preferences')) return json({}); + if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' }); + if (u.includes('/v1/groups/mine')) return json({ groups: [ + { id: '__GROUP__', name: 'demo', owner_username: 'someowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + { id: 'other-group', name: 'demo', owner_username: 'otherowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + ] }); + if (u.includes('/nodes')) return json({ nodes: [] }); + return json({}); +}; +if (CASE === 'signed_out') { + localStorage.removeItem('mb_auth'); +} else { + localStorage.setItem('mb_auth', JSON.stringify({ + username: 'member-account', userId: 'u-1', token: 'tok', refreshToken: 'ref', + role: 'user' })); +} +sessionStorage.clear(); +history.replaceState(null, '', '/?case=' + CASE + LINKS[CASE]); + +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +(async () => { + const out = { case: CASE }; + try { + await import('/app.js'); + await wait(2000); + out.hash = decodeURI(location.hash); + out.history_length = history.length; + out.group_page = Boolean(document.querySelector('.group-header')); + out.group_title = (document.querySelector('.group-header h2') || {}).innerText || ''; + out.active_sidebar = [...document.querySelectorAll('.sidebar-group.active')] + .map((a) => a.getAttribute('href')); + out.message = (document.querySelector('main .page-message') || {}).innerText || ''; + out.spinner = Boolean(document.querySelector('main .page-message .spinner')); + out.login_form = Boolean(document.querySelector('input[type=password]')); + out.hub_calls = calls.map((c) => c.replace(/^https?:\/\/[^/]+/, '')); + } catch (e) { + out.error = String(e && e.stack || e); + } + post(out); +})(); +</script></body></html> +""".replace("__GROUP__", GROUP).replace("__LINKS__", json.dumps(LINKS)) + + +class H(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + if self.path == "/log": + RECORDS.append(json.loads(body.decode())) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = self.path.split("?")[0] + if path == "/": + self._send(PAGE.encode(), "text/html; charset=utf-8") + return + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + ctype = "text/javascript" if asset.suffix in (".js", ".mjs") else ( + "application/wasm" if asset.suffix == ".wasm" else "application/octet-stream") + self._send(asset.read_bytes(), ctype) + + +def _run(case: str) -> dict | None: + before = len(RECORDS) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile: + proc = subprocess.Popen( + ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", f"http://127.0.0.1:{PORT}/?case={case}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if len(RECORDS) > before: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[before] if len(RECORDS) > before else None + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + results = [_run(case) for case in CASES] + if not all(results): + print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) + return 1 + print(json.dumps(results, indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/harness/invite_link_probe.py b/packages/meshbay-hub/tests/harness/invite_link_probe.py index 97ee893..b0a833e 100644 --- a/packages/meshbay-hub/tests/harness/invite_link_probe.py +++ b/packages/meshbay-hub/tests/harness/invite_link_probe.py @@ -13,6 +13,9 @@ Loads the shipped `app.js` in a real browser with `fetch` stubbed, twice: signed_out — a link, no session signed_in — the same link, a session; then the Join button is clicked + signed_in_listed — the same, with the hub listing the group once joined, as + it does: the group page opens and the address shows its handle + (`#/name@owner`, group-link.js) invite_link_probe.py @@ -56,7 +59,15 @@ window.fetch = async (url, init = {}) => { calls.push({ url: u, body: init.body ? String(init.body) : '' }); if (u.includes('/v1/users/me/preferences')) return json({}); if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' }); - if (u.includes('/v1/groups/mine')) return json({ groups: [] }); + // Joined, the hub lists the group — in the one case that says so. The others + // keep an empty list, so the address stays the `#/group/<id>` the Join + // button navigated to and is read before the router could rewrite it. + if (u.includes('/v1/groups/mine')) return json({ groups: + CASE === 'signed_in_listed' && calls.some((c) => c.url.includes('/redeem')) + ? [{ id: '__GROUP__', name: 'Some Group', owner_username: 'the-owner', + visibility: 'private', created_at: '2026-01-01T00:00:00+00:00', + description: '' }] + : [] }); if (u.includes('/v1/invite-links/preview')) return json({ group_id: '__GROUP__', group_name: 'Some Group', inviter: 'the-owner', expires_at: '2099-01-01T00:00:00+00:00', already_member: false }); @@ -65,7 +76,7 @@ window.fetch = async (url, init = {}) => { if (u.includes('/nodes')) return json({ nodes: [] }); return json({}); }; -if (CASE === 'signed_in') { +if (CASE.startsWith('signed_in')) { localStorage.setItem('mb_auth', JSON.stringify({ username: 'invitee-account', userId: 'u-1', token: 'tok', refreshToken: 'ref', role: 'user' })); @@ -98,6 +109,12 @@ const text = () => document.getElementById('app').innerText; out.join_button = Boolean(join); if (join) { join.click(); await wait(1500); } out.hash_after_click = location.hash; + if (CASE === 'signed_in_listed') { + await wait(1500); + out.hash_settled = decodeURI(location.hash); + out.group_page = Boolean(document.querySelector('.group-header')); + out.history_length = history.length; + } out.redeem_bodies = calls.filter((c) => c.url.includes('/redeem')).map((c) => c.body); } out.code_in_a_hub_request = calls.some( @@ -169,7 +186,7 @@ def _run(case: str) -> dict | None: def main() -> int: with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: threading.Thread(target=srv.serve_forever, daemon=True).start() - results = [_run("signed_out"), _run("signed_in")] + results = [_run("signed_out"), _run("signed_in"), _run("signed_in_listed")] if not all(results): print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) return 1 diff --git a/packages/meshbay-hub/tests/test_copy_link.py b/packages/meshbay-hub/tests/test_copy_link.py new file mode 100644 index 0000000..22e56e7 --- /dev/null +++ b/packages/meshbay-hub/tests/test_copy_link.py @@ -0,0 +1,103 @@ +""" +"Copy link": the `#/name@owner/path` address of a file or folder, from the +views that show one (harness/copy_link_probe.py). + +Files offers it for one row — right-click, or the toolbar with one row ticked, +which is how a phone reaches it; Music on one track's menu, whose dots are a +phone's way in; Photos on a right-clicked tile and in the lightbox. The video +player and the file preview carry a button. Search passes the same `linkFor`, +naming each result's own group and its path there rather than the merged tree's. +""" + +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +HARNESS = Path(__file__).parent / "harness" / "copy_link_probe.py" +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +ORIGIN = "http://127.0.0.1:8775" + + +@pytest.fixture(scope="module") +def cases(): + if shutil.which("google-chrome") is None: + pytest.skip("Chrome is not available") + proc = subprocess.run([sys.executable, str(HARNESS)], + capture_output=True, text=True, timeout=180) + assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}" + out = json.loads(proc.stdout) + assert "error" not in out, out["error"] + assert out["logs"] == [] + return {c["case"]: c for c in out["cases"]} + + +def test_files_a_folder(cases): + c = cases["files folder"] + assert "Copy link" in c["labels"] + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root" + assert c["note"] == "Link copied" + + +def test_files_a_file(cases): + c = cases["files file"] + assert c["labels"].index("Copy link") > c["labels"].index("Download") + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/IMG%200001.JPG" + + +def test_files_toolbar_one_ticked_row_only(cases): + c = cases["files toolbar"] + assert c["one_enabled"] is True and c["two_enabled"] is False + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/notes.txt" + + +def test_music_a_track_from_its_dots(cases): + c = cases["music track"] + assert c["dots"] and c["labels"][-1] == "Copy link" + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Music/Some%20Album/track%2001.flac" + + +def test_photos_tile_and_lightbox(cases): + c = cases["photos"] + link = f"{ORIGIN}/#/demo@someowner/Pics/Summer/beach.jpg" + assert c["labels"] == ["Copy link"] and c["copied"] == link + assert c["lightbox_button"] and c["lightbox_copied"] == link + + +@pytest.mark.parametrize("module", ["video-player.js", "files-app.js"]) +def test_the_modals_carry_a_link_button(module): + source = (STATIC / module).read_text(encoding="utf-8") + assert re.search(r"function (VideoPlayer|FilePreview)\(\{[^}]*onCopyLink", source) + assert "${onCopyLink && html`" in source + + +@pytest.mark.parametrize("page, n", [("group-page.js", 2), ("search-page.js", 2)]) +def test_both_pages_hand_the_modals_a_link(page, n): + source = (STATIC / page).read_text(encoding="utf-8") + assert source.count("onCopyLink=${linkFor(") == n + + +def test_search_names_each_results_own_group_and_path(): + source = (STATIC / "search-page.js").read_text(encoding="utf-8") + # Every view prefixes `path`; the link is built from the original. + assert source.count("_origPath: e.path,") == 4 + assert "entryPath(target, target._origPath)" in source + for view in ("FilesPanel", "MusicApp", "PhotosApp"): + at = source.index(f"<${{{view}}}") + assert "linkFor=${linkFor}" in source[at:source.index("/>", at)], view + + +def test_the_link_is_the_hubs_not_the_pages(): + """In the desktop application the page is app://meshbay.""" + source = (STATIC / "copy-link.js").read_text(encoding="utf-8") + assert "platform.hubOrigin() + '/#' + groupLinkRoute(" in source + assert "location.origin" not in source + + +def test_the_note_goes_by_itself(cases): + c = cases["note goes"] + assert c["up_after_copy"] is True and c["up_later"] is False diff --git a/packages/meshbay-hub/tests/test_group_link.py b/packages/meshbay-hub/tests/test_group_link.py new file mode 100644 index 0000000..e71df20 --- /dev/null +++ b/packages/meshbay-hub/tests/test_group_link.py @@ -0,0 +1,170 @@ +""" +A group named in the address: `#/name@owner[/path]`. + +The handle under every group's name is also a link to it, and a path after it +names a folder to open or a file to download. `group-link.js` parses it, +builds it, finds the group among the account's own and the entry in the +group's index; the module is executed whole, as `test_search_source_merge.py` +does with `source-merge.js`, so these rules are the ones the page runs. + +Also held here, at source level: the sign-in form no longer sends everyone +home, which is what made any link opened signed out land on the home page. +""" + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +SRC = STATIC / "group-link.js" + +IMPORT = re.compile(r"^\s*import\b", re.M) +EXPORT = re.compile(r"^export \{[^}]*\};?\s*$", re.M) + +needs_node = pytest.mark.skipif( + shutil.which("node") is None or not SRC.exists(), + reason="node or the SPA sources are not available") + + +@pytest.fixture(scope="module") +def module_source(): + text = SRC.read_text(encoding="utf-8") + assert not IMPORT.search(text), ( + "group-link.js has gained an import; this test runs it standalone") + stripped, n = EXPORT.subn("", text) + assert n == 1 + return stripped + + +def _run(tmp_path, module_source, expr): + script = tmp_path / "case.js" + script.write_text(f"{module_source}\nconsole.log(JSON.stringify({expr}));\n", + encoding="utf-8") + out = subprocess.run(["node", str(script)], capture_output=True, text=True, + encoding="utf-8", timeout=30) + assert out.returncode == 0, out.stderr + return json.loads(out.stdout) + + +GROUPS = [ + {"id": "g1", "name": "demo", "owner_username": "someowner"}, + {"id": "g2", "name": "demo", "owner_username": "otherowner"}, + {"id": "g3", "name": "trips@home", "owner_username": "someowner"}, + {"id": "g4", "name": "a/b c", "owner_username": "someowner"}, +] + +ENTRIES = [ + {"path": "backup/city_2015/backup", "name": "IMG_0001.JPG"}, + {"path": "backup/city_2015", "name": "notes.txt"}, + {"path": "music", "name": "track 01.flac"}, +] + + +@needs_node +@pytest.mark.parametrize("route, expected", [ + ("/demo@someowner", {"name": "demo", "owner": "someowner", "path": ""}), + ("/demo@someowner/backup/city_2015/backup/IMG_0001.JPG", + {"name": "demo", "owner": "someowner", + "path": "backup/city_2015/backup/IMG_0001.JPG"}), + # The owner is after the last `@`: a group name may hold one, a username not. + ("/trips@home@someowner", {"name": "trips@home", "owner": "someowner", "path": ""}), + # Each segment decoded on its own: an escaped `/` stays inside its segment. + ("/a%2Fb%20c@someowner/music/track%2001.flac", + {"name": "a/b c", "owner": "someowner", "path": "music/track 01.flac"}), + ("/demo@someowner/music/", {"name": "demo", "owner": "someowner", "path": "music"}), + # Every other route, and anything that is not a well-formed handle. + ("/group/0f8fad5b-d9cb-469f-a165-70867728950e", None), + ("/login", None), ("/", None), ("", None), + ("/@someowner", None), ("/demo@", None), + ("/demo@someowner/%E0%A4%A", None), + ("/demo@someowner/music/../../etc", None), +]) +def test_parse(tmp_path, module_source, route, expected): + assert _run(tmp_path, module_source, f"parseGroupLink({json.dumps(route)})") == expected + + +@needs_node +@pytest.mark.parametrize("group, path", [ + (GROUPS[0], ""), + (GROUPS[0], "backup/city_2015/backup/IMG_0001.JPG"), + (GROUPS[2], ""), + (GROUPS[3], "music/track 01.flac"), + ({"name": "Été à la mer", "owner_username": "someowner"}, "photos/plage #1.jpg"), +]) +def test_built_routes_parse_back(tmp_path, module_source, group, path): + out = _run(tmp_path, module_source, + f"(() => {{ const r = groupLinkRoute({json.dumps(group)}, {json.dumps(path)});" + f" return [r, parseGroupLink(r)]; }})()") + route, parsed = out + assert parsed == {"name": group["name"], "owner": group["owner_username"], "path": path} + # Nothing that ends or splits a fragment is left bare. + assert not re.search(r"[#?\s%](?![0-9A-F]{2})", route) + + +@needs_node +def test_a_plain_handle_stays_readable(tmp_path, module_source): + route = _run(tmp_path, module_source, + f"groupLinkRoute({json.dumps(GROUPS[0])}, 'backup/city_2015/IMG_1.JPG')") + assert route == "/demo@someowner/backup/city_2015/IMG_1.JPG" + + +@needs_node +@pytest.mark.parametrize("link, expected", [ + ({"name": "demo", "owner": "someowner"}, "g1"), + ({"name": "demo", "owner": "otherowner"}, "g2"), + # The hub keeps names unique on lower(name). + ({"name": "DEMO", "owner": "someowner"}, "g1"), + ({"name": "demo", "owner": "SomeOwner"}, "g1"), + # Not among the account's groups: nothing, and nothing asked of the hub. + ({"name": "demo", "owner": "stranger1"}, None), + ({"name": "secret", "owner": "someowner"}, None), +]) +def test_find_among_own_groups(tmp_path, module_source, link, expected): + out = _run(tmp_path, module_source, + f"(findLinkedGroup({json.dumps(GROUPS)}, {json.dumps(link)}) || {{}}).id || null") + assert out == expected + + +@needs_node +@pytest.mark.parametrize("path, expected", [ + ("backup/city_2015/backup/IMG_0001.JPG", + {"kind": "file", "entry": ENTRIES[0]}), + ("backup/city_2015/notes.txt", {"kind": "file", "entry": ENTRIES[1]}), + ("backup/city_2015", {"kind": "dir", "dir": "backup/city_2015"}), + ("backup", {"kind": "dir", "dir": "backup"}), + # An empty folder exists only in the node's own listing. + ("backup/empty", {"kind": "dir", "dir": "backup/empty"}), + # A prefix of a folder name is not that folder. + ("backup/city", None), + ("backup/city_2015/backup/img_0001.jpg", None), + ("", None), +]) +def test_resolve_in_index(tmp_path, module_source, path, expected): + out = _run(tmp_path, module_source, + f"resolveLinkedPath({json.dumps(ENTRIES)}, ['backup/empty'], {json.dumps(path)})") + assert out == expected + + +def test_signing_in_keeps_the_page_the_address_names(): + """A group or file link opened signed out shows the sign-in form in its + place; signing in must leave the address alone, not send everyone home.""" + source = (STATIC / "auth-page.js").read_text(encoding="utf-8") + body = source[source.index("export function LoginPage"):] + body = body[:body.index("\n}\n")] + assert "navigate('/')" not in body and 'navigate("/")' not in body + assert "if (loadPending()) navigate('/invite');" in body + + +def test_the_router_resolves_a_handle_and_shows_it(): + source = (STATIC / "app.js").read_text(encoding="utf-8") + body = source[source.index("\nfunction App() {"):] + assert "parseGroupLink(route)" in body + assert "findLinkedGroup(groups, groupLink)" in body + # Rewritten with `replace`: showing the handle is not a history entry. + assert "window.location.replace('#' + shownGroupRoute)" in body + # The sidebar highlights the group whichever form opened it. + assert re.search(r"<\$\{Sidebar\}[\s\S]*?route=\$\{groupRoute\}", body) diff --git a/packages/meshbay-hub/tests/test_group_link_flow.py b/packages/meshbay-hub/tests/test_group_link_flow.py new file mode 100644 index 0000000..eb6a353 --- /dev/null +++ b/packages/meshbay-hub/tests/test_group_link_flow.py @@ -0,0 +1,67 @@ +""" +A group link, opened in the real application (harness/group_link_probe.py). + +`test_group_link.py` holds the parsing and the lookups; this is where they meet +the router. A handle opens the group's page, and an id opens it with the handle +in the address; a path waits in the address for the index to say what it is; a +handle the account does not know is said to be unknown without the hub ever +being asked about it; and signed out, the sign-in form stands in for the page +with the address left alone, which is what lets signing in land there. +""" + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +HARNESS = Path(__file__).parent / "harness" / "group_link_probe.py" +GROUP_HREF = "#/group/0f8fad5b-d9cb-469f-a165-70867728950e" +FILE_LINK = "#/demo@someowner/backup/city_2015/backup/IMG_0001.JPG" + + +@pytest.fixture(scope="module") +def cases(): + if shutil.which("google-chrome") is None: + pytest.skip("Chrome is not available") + proc = subprocess.run([sys.executable, str(HARNESS)], + capture_output=True, text=True, timeout=240) + assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}" + out = {c["case"]: c for c in json.loads(proc.stdout)} + for c in out.values(): + assert "error" not in c, c["error"] + return out + + +@pytest.mark.parametrize("case", ["handle", "uuid", "file"]) +def test_a_handle_or_an_id_opens_the_group(cases, case): + c = cases[case] + assert c["group_page"] and c["group_title"] == "demo@someowner" + # Of two groups called "demo", the one whose owner the handle names. + assert c["active_sidebar"] == [GROUP_HREF] + + +@pytest.mark.parametrize("case", ["handle", "uuid"]) +def test_the_address_shows_the_handle_without_a_history_entry(cases, case): + assert cases[case]["hash"] == "#/demo@someowner" + assert cases[case]["history_length"] == 1 + + +def test_a_path_stays_in_the_address_until_it_has_been_acted_on(cases): + assert cases["file"]["hash"] == FILE_LINK + + +def test_an_unknown_handle_is_said_so_without_asking_the_hub(cases): + c = cases["unknown"] + assert not c["group_page"] and c["message"] and not c["spinner"] + assert c["hash"] == "#/demo@stranger1" + for case in cases.values(): + assert not any("stranger1" in u or "@" in u for u in case["hub_calls"]) + + +def test_signed_out_the_form_stands_in_for_the_page(cases): + c = cases["signed_out"] + assert c["login_form"] and not c["group_page"] + assert c["hash"] == FILE_LINK diff --git a/packages/meshbay-hub/tests/test_http_api_doc.py b/packages/meshbay-hub/tests/test_http_api_doc.py new file mode 100644 index 0000000..5568e63 --- /dev/null +++ b/packages/meshbay-hub/tests/test_http_api_doc.py @@ -0,0 +1,30 @@ +""" +docs/MESHBAY_HTTP_API.md is generated from the routes of the hub and of the +node's control API. A route added, removed or redescribed without running +`python docs/generate_http_api.py` fails here. +""" + +import importlib.util +from pathlib import Path + +GENERATOR = Path(__file__).resolve().parents[3] / "docs" / "generate_http_api.py" + + +def _generator(): + spec = importlib.util.spec_from_file_location("generate_http_api", GENERATOR) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_the_api_listing_matches_the_routes(): + gen = _generator() + assert gen.OUT.read_text(encoding="utf-8") == gen.render(), ( + "docs/MESHBAY_HTTP_API.md is out of date: run python docs/generate_http_api.py") + + +def test_every_route_says_what_it_does(): + gen = _generator() + bare = [f"{gen.method(r)} {r.path}" for r in gen.hub_routes() + gen.node_routes() + if not gen.summary(r)] + assert not bare, f"give these routes a docstring, it is their line in the listing: {bare}" diff --git a/packages/meshbay-hub/tests/test_invite_link_flow.py b/packages/meshbay-hub/tests/test_invite_link_flow.py index 42f461c..cc8b432 100644 --- a/packages/meshbay-hub/tests/test_invite_link_flow.py +++ b/packages/meshbay-hub/tests/test_invite_link_flow.py @@ -33,14 +33,14 @@ def cases(): return out -@pytest.mark.parametrize("case", ["signed_out", "signed_in"]) +@pytest.mark.parametrize("case", ["signed_out", "signed_in", "signed_in_listed"]) def test_the_code_is_out_of_the_address_and_kept_in_the_tab(cases, case): c = cases[case] assert c["hash_after_load"] == "#/invite" assert c["pending"] and c["pending"]["c"] == "K7P2-9WQX" -@pytest.mark.parametrize("case", ["signed_out", "signed_in"]) +@pytest.mark.parametrize("case", ["signed_out", "signed_in", "signed_in_listed"]) def test_the_code_never_reaches_the_hub(cases, case): assert cases[case]["code_in_a_hub_request"] is False @@ -59,3 +59,16 @@ def test_a_signed_in_reader_joins_with_one_click_and_lands_on_the_group(cases): assert c["join_button"] assert c["redeem_bodies"] == ['{"ticket":"AbCdEfGhIjKlMnOpQr-_12"}'] assert c["hash_after_click"] == "#/group/0f8fad5b-d9cb-469f-a165-70867728950e" + + +def test_once_listed_the_joined_group_opens_under_its_handle(cases): + """The group links (group-link.js) rewrite `#/group/<id>` to the handle as + soon as the hub lists the group. Joining from an invitation must land on + the group page all the same, under that handle, with the rewrite adding + no history entry of its own — and still without the code reaching the hub.""" + c = cases["signed_in_listed"] + assert c["join_button"] + assert c["hash_settled"] == "#/Some Group@the-owner" + assert c["group_page"] is True + # The page load, then the Join button's navigation; the rewrite replaces. + assert c["history_length"] == 2 diff --git a/packages/meshbay-hub/tests/test_search_unreachable_note.py b/packages/meshbay-hub/tests/test_search_unreachable_note.py new file mode 100644 index 0000000..41ed25c --- /dev/null +++ b/packages/meshbay-hub/tests/test_search_unreachable_note.py @@ -0,0 +1,33 @@ +""" +"N groups unreachable" on the cross-group Search page is said once a pass is +over, for a few seconds, in the same passing note as "Link copied" (note.js) — +not left above the results for as long as the page is open. + +Source-level, as the other Search wiring checks are: what is held is where the +line is said and that nothing renders it in the page any more. +""" + +import re +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" + + +def test_said_once_the_pass_is_over_and_not_rendered(): + source = (STATIC / "search-page.js").read_text(encoding="utf-8") + assert "import { say } from './note.js';" in source + after = source[source.index("const { unreachable } = await fetchAllIndexes("):] + after = after[:after.index("})();")] + assert re.search(r"if \(cancelled\) return;\s*setFetching\(false\);", after) + assert "say(t('search.unreachable', { n: unreachable.length }), UNREACHABLE_NOTE_MS)" in after + assert "search-unreachable" not in source + ms = int(re.search(r"const UNREACHABLE_NOTE_MS = (\d+);", source).group(1)) + assert 2000 <= ms <= 8000 + + +def test_one_note_for_the_whole_page(): + note = (STATIC / "note.js").read_text(encoding="utf-8") + assert "export function say(text, ms = 2500)" in note + assert "clearTimeout(_timer)" in note + copy = (STATIC / "copy-link.js").read_text(encoding="utf-8") + assert "import { say } from './note.js';" in copy and "_say" not in copy diff --git a/packages/meshbay-hub/tests/test_spa_ordering.py b/packages/meshbay-hub/tests/test_spa_ordering.py index 6f28aaa..44f98db 100644 --- a/packages/meshbay-hub/tests/test_spa_ordering.py +++ b/packages/meshbay-hub/tests/test_spa_ordering.py @@ -162,7 +162,7 @@ def _component(name: str) -> str: def test_the_group_settings_panel_renders_what_it_owns(): panel = _component("GroupSettingsPanel") - assert "members.map(" in panel, "the member list is not rendered" + assert "joined.map(" in panel, "the member list is not rendered" assert "onSubmit=${doInvite}" in panel, "the invite form is not rendered" assert "onSubmit=${doPair}" in panel, "the pairing form is not rendered" assert "device.mine_title" in panel, "the devices section is not rendered" @@ -175,7 +175,7 @@ def test_the_roster_comes_last(): order is for — asked for in those terms. """ panel = _component("GroupSettingsPanel") - listing = panel.index("members.map(") + listing = panel.index("joined.map(") for name, marker in (("the invite form", "onSubmit=${doInvite}"), ("the pairing form", "onSubmit=${doPair}"), ("the devices section", "device.mine_title"), diff --git a/packages/meshbay-node/LICENSE b/packages/meshbay-node/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/packages/meshbay-node/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/packages/meshbay-node/pyproject.toml b/packages/meshbay-node/pyproject.toml index e505048..3dd1188 100644 --- a/packages/meshbay-node/pyproject.toml +++ b/packages/meshbay-node/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["hatchling"] +requires = ["hatchling>=1.27"] # PEP 639: SPDX `license` + `license-files` build-backend = "hatchling.build" [project] @@ -7,6 +7,8 @@ name = "meshbay-node" version = "0.18.0" description = "MeshBay Node — local file host, streaming server, and group daemon" requires-python = ">=3.12" +license = "AGPL-3.0-or-later" +license-files = ["LICENSE"] dependencies = [ "meshbay-common>=0.10.0", "fastapi>=0.115", # local web UI on localhost:18000 diff --git a/packages/meshbay-node/src/meshbay_node/cli/status.py b/packages/meshbay-node/src/meshbay_node/cli/status.py index 162bd46..ebc6c77 100644 --- a/packages/meshbay-node/src/meshbay_node/cli/status.py +++ b/packages/meshbay-node/src/meshbay_node/cli/status.py @@ -34,7 +34,8 @@ def status(args) -> None: live = None if live: - print(f"daemon running — {live.get('status')}") + state = live.get("status") + print("daemon running" + (f" — {state}" if state and state != "running" else "")) print(f"node_id {live.get('endpoint_hint') or '—'}") print(f"groups {live.get('group_count', 0)}" f" files {live.get('total_files', 0)}" diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py index 1777bc3..d6293ee 100644 --- a/packages/meshbay-node/src/meshbay_node/daemon.py +++ b/packages/meshbay-node/src/meshbay_node/daemon.py @@ -1259,11 +1259,13 @@ class NodeDaemon(EnrichmentMixin): specs = [asdict(r) for r in group_cfg.roots] if self._roster: ejected = await self._roster.ejected_roots(group_cfg.id) + auto = await self._roster.auto_ejected_roots(group_cfg.id) if ejected: for spec in specs: name = spec.get("name") or Path(spec.get("path", "")).name if fold(name) in ejected: spec["ejected"] = True + spec["ejected_auto"] = fold(name) in auto return RootSet.build(specs) # Every application that keeps directories. This is the one list, and it @@ -1305,9 +1307,10 @@ class NodeDaemon(EnrichmentMixin): """`on_root_ejected` bound to one group, for that group's indexer.""" async def persist(root_name: str, ejected: bool) -> None: if self._roster: + # The indexer only reports the safety net's own changes. await self._roster.set_root_ejected( group_id, root_name, ejected, - set_by=self._state.get("node_user_id", "")) + set_by=self._state.get("node_user_id", ""), auto=ejected) return persist async def _on_index_change(self, indexer: DirectoryIndexer) -> None: diff --git a/packages/meshbay-node/src/meshbay_node/indexer/cache.py b/packages/meshbay-node/src/meshbay_node/indexer/cache.py index 6c87f40..5e328ef 100644 --- a/packages/meshbay-node/src/meshbay_node/indexer/cache.py +++ b/packages/meshbay-node/src/meshbay_node/indexer/cache.py @@ -23,6 +23,7 @@ only daemon.py's wiring changed. """ import logging +import os import time from dataclasses import dataclass from pathlib import Path @@ -191,6 +192,19 @@ class IndexCache: row = await cur.fetchone() return row[0] if row else 0 + async def sample_under(self, directory: str, limit: int) -> list[tuple[str, int, float]]: + """Up to `limit` cached files under `directory`, as (path, size, mtime). + + A prefix compared with `substr`, not `LIKE`: `_` and `%` are wildcards + there, and both are ordinary in a folder name. + """ + prefix = directory.rstrip("/\\") + os.sep + async with self._db.execute( + "SELECT path, size, mtime FROM files WHERE substr(path, 1, ?) = ? LIMIT ?", + (len(prefix), prefix, limit)) as cur: + rows = await cur.fetchall() + return [(row[0], row[1], row[2]) for row in rows] + async def all_paths(self) -> list[str]: """Every cached path, for a caller that decides staleness itself — this cache has no notion of which paths are still claimed by a diff --git a/packages/meshbay-node/src/meshbay_node/indexer/indexer.py b/packages/meshbay-node/src/meshbay_node/indexer/indexer.py index f0505f7..5e139bb 100644 --- a/packages/meshbay-node/src/meshbay_node/indexer/indexer.py +++ b/packages/meshbay-node/src/meshbay_node/indexer/indexer.py @@ -389,6 +389,7 @@ class DirectoryIndexer: async def _initial_scan(self) -> None: await off_disk(self.roots, self.roots.refresh_availability) + await self._plug_back_recognised() total = 0 waiting = [r.name for r in self.roots if r.available] self._queue(waiting) @@ -825,6 +826,8 @@ class DirectoryIndexer: except Exception: log.exception("Could not persist the auto-eject of root %r", name) + changed += [(root, True) for root in await self._plug_back_recognised()] + for root, available in changed: if available: log.info("Root %r is back — rescanning", root.name) @@ -1032,6 +1035,65 @@ class DirectoryIndexer: self._observer = None self._start_observer() + # How many of a root's known files are looked for before it is plugged back + # automatically. One found is enough: another drive, or an empty mount + # point, holds none of them at the same path with the same size and mtime. + RECOGNISE_SAMPLE = 5 + + async def _plug_back_recognised(self) -> list[Root]: + """ + Un-eject the roots the safety net ejected, once they hold their own files + again: a drive not mounted yet when the node started, or unplugged and + plugged back. An operator's eject is never undone here. + """ + back = [] + for root in [r for r in self.roots if r.ejected and r.auto]: + if not await off_disk(self.roots, self._recognises, root, + await self._known_files(root)): + continue + root.ejected = root.auto = False + root.available = True + log.info("Root %r is back with its files — plugged automatically", root.name) + if self.on_root_ejected: + try: + await self.on_root_ejected(root.name, False) + except Exception: + log.exception("Could not persist the return of root %r", root.name) + back.append(root) + return back + + async def _known_files(self, root: Root) -> list[tuple[str, int, float | None]]: + """Files this root is known to hold, as (path, size, mtime or None). + + The hash cache first: it survives a restart, when an ejected root has no + entry in the index at all. The index is the fallback for a node without + a cache. + """ + if self._cache is not None: + known = await self._cache.sample_under(str(root.path), self.RECOGNISE_SAMPLE) + if known: + return known + return [(str(path), e.size, None) + for e in self._entries_under(root)[:self.RECOGNISE_SAMPLE] + if (path := self._entry_path(root, e)) is not None] + + @staticmethod + def _recognises(root: Root, known: list[tuple[str, int, float | None]]) -> bool: + """Blocking: is this the root's own content, readable again?""" + if not root.is_live(): + return False + if not known: + # Nothing known under it, so nothing a wrong disk could pass for. + return True + for path, size, mtime in known: + try: + st = Path(path).stat() + except OSError: + continue + if st.st_size == size and (mtime is None or st.st_mtime == mtime): + return True + return False + def eject_root(self, root_name: str) -> None: """Stop watching a root without touching its entries.""" from meshbay_common.paths import fold @@ -1039,6 +1101,7 @@ class DirectoryIndexer: for root in self.roots: if fold(root.name) == target: root.ejected = True + root.auto = False root.available = False frozen = len(self._entries_under(root)) log.info("Root %r ejected — %d entries frozen", root.name, frozen) @@ -1058,7 +1121,7 @@ class DirectoryIndexer: break if root is None: return - root.ejected = False + root.ejected = root.auto = False root.available = await off_disk(self.roots, root.is_live) if not root.available: await self._finish_plug(None) diff --git a/packages/meshbay-node/src/meshbay_node/ops/roots.py b/packages/meshbay-node/src/meshbay_node/ops/roots.py index 9dbade4..b976e8f 100644 --- a/packages/meshbay-node/src/meshbay_node/ops/roots.py +++ b/packages/meshbay-node/src/meshbay_node/ops/roots.py @@ -240,6 +240,7 @@ async def eject_root(state: dict, group_id: str, root_name: str) -> dict: if indexer: indexer.eject_root(root_name) root.ejected = True + root.auto = False root.available = False await _roster(state).set_root_ejected( @@ -288,7 +289,7 @@ async def plug_root(state: dict, group_id: str, root_name: str) -> dict: indexer = state.get("indexers", {}).get(group_id) if indexer: await indexer.plug_root(root_name) - root.ejected = False + root.ejected = root.auto = False root.available = await off_disk(roots, root.is_live) log.info("Root plugged: %s in group %s", root_name, group_id[:8]) diff --git a/packages/meshbay-node/src/meshbay_node/roots.py b/packages/meshbay-node/src/meshbay_node/roots.py index 2de0708..2b48292 100644 --- a/packages/meshbay-node/src/meshbay_node/roots.py +++ b/packages/meshbay-node/src/meshbay_node/roots.py @@ -178,6 +178,10 @@ class Root: writable: bool = False removable: bool = False ejected: bool = False + # Ejected by the safety net in `refresh_availability`, not by the operator: + # such a root comes back on its own once its files are there again + # (`DirectoryIndexer._reconcile`). An operator's eject never does. + auto: bool = False available: bool = True @property @@ -323,6 +327,7 @@ class RootSet: writable=writable, removable=bool(spec.get("removable", False)), ejected=bool(spec.get("ejected", False)), + auto=bool(spec.get("ejected_auto", False)), available=not bool(spec.get("ejected", False))) _refuse_nesting(root, roots) roots.append(root) @@ -441,6 +446,7 @@ class RootSet: live = root.is_live() if not live and root.removable: root.ejected = True + root.auto = True # Recorded for the caller to persist. A flag that only lives # in memory would be forgotten on the next restart, and the # rescan that followed would read an empty mount point as an diff --git a/packages/meshbay-node/src/meshbay_node/roster.py b/packages/meshbay-node/src/meshbay_node/roster.py index 0116aaa..eb8c031 100644 --- a/packages/meshbay-node/src/meshbay_node/roster.py +++ b/packages/meshbay-node/src/meshbay_node/roster.py @@ -686,9 +686,11 @@ class Roster: return cls.SETTING_ROOT_EJECTED_PREFIX + fold(root_name) async def set_root_ejected(self, group_id: str, root_name: str, - ejected: bool, set_by: str = "") -> None: - await self.set_setting(group_id, self.root_ejected_key(root_name), - "1" if ejected else "0", set_by) + ejected: bool, set_by: str = "", + auto: bool = False) -> None: + """`auto`: ejected by the safety net, not by the operator.""" + value = ("auto" if auto else "1") if ejected else "0" + await self.set_setting(group_id, self.root_ejected_key(root_name), value, set_by) async def ejected_roots(self, group_id: str) -> set[str]: """ @@ -705,7 +707,17 @@ class Roster: (group_id,)) as cur: rows = await cur.fetchall() return {r["key"][len(prefix):] for r in rows - if r["key"].startswith(prefix) and r["value"] == "1"} + if r["key"].startswith(prefix) and r["value"] in ("1", "auto")} + + async def auto_ejected_roots(self, group_id: str) -> set[str]: + """The folded names of the roots the safety net ejected, a subset of the above.""" + prefix = self.SETTING_ROOT_EJECTED_PREFIX + async with self._db.execute( + "SELECT key, value FROM group_settings WHERE group_id = ?", + (group_id,)) as cur: + rows = await cur.fetchall() + return {r["key"][len(prefix):] for r in rows + if r["key"].startswith(prefix) and r["value"] == "auto"} async def get_setting(self, group_id: str, key: str, default: str | None = None) -> str | None: diff --git a/packages/meshbay-node/src/meshbay_node/ui/app.py b/packages/meshbay-node/src/meshbay_node/ui/app.py index db11a09..03db8b6 100644 --- a/packages/meshbay-node/src/meshbay_node/ui/app.py +++ b/packages/meshbay-node/src/meshbay_node/ui/app.py @@ -120,6 +120,10 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/status") async def api_status(): + """ + The daemon's state, and what it still needs: a linked key, a group, an operator, a group + key. + """ indexes = state.get("indexes", {}) total_files = sum(idx.count for idx in indexes.values()) groups_ctx = state.get("groups_ctx", {}) @@ -163,6 +167,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.delete("/api/unlink") async def api_unlink(): + """Unlink the node's key from its hub account.""" hub = state.get("hub") if not hub: raise HTTPException(status_code=503, detail="Hub not connected") @@ -171,9 +176,13 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/groups") async def api_groups(): + """The groups this node hosts, with live status, and whether an operator is paired.""" return await _op(lambda: ops.list_groups(state)) @app.post("/api/groups/attach") async def attach_group(payload: dict): + """ + Host a group that exists on the hub: add it to node.toml with its first folder, then reload. + """ result = await _op(lambda: ops.attach_group( state, (payload.get("name") or "").strip(), @@ -188,6 +197,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.post("/api/groups/detach") async def detach_group(payload: dict): + """Stop hosting a group: remove it from node.toml, then reload.""" result = await _op(lambda: ops.detach_group( state, (payload.get("name") or payload.get("group_id") or "").strip(), @@ -199,31 +209,41 @@ def create_ui_app(state: dict) -> FastAPI: @app.delete("/api/groups/{group_id}/files/{file_id}") async def delete_file(group_id: str, file_id: str): - """Milestone 14.11 — the last operator action that needed a browser.""" + """ + Delete a file from the group's folder on disk. + + Milestone 14.11 — the last operator action that needed a browser. + """ return await _op(lambda: ops.delete_file(state, group_id, file_id)) @app.get("/api/denylist") async def api_denylist(): + """What the node currently refuses.""" return await _op(lambda: ops.read_denylist(state)) @app.post("/api/denylist/clear") async def api_denylist_clear(subject: str = ""): + """Drop denylist entries: all of them, or one identifier.""" return await _op(lambda: ops.clear_denylist(state, subject=subject)) @app.get("/api/index-cache") async def api_index_cache_stats(): + """Size of the index cache.""" return await _op(lambda: ops.index_cache_stats(state)) @app.post("/api/index-cache/prune") async def api_index_cache_prune(): + """Drop index cache rows that no longer match a file on disk.""" return await _op(lambda: ops.prune_index_cache(state)) @app.post("/api/groups/{group_id}/video/rematch") async def api_video_rematch(group_id: str): + """Forget the automatic matches of the group's videos, so they are looked up again.""" return await _op(lambda: ops.rematch_video(state, group_id)) @app.get("/api/groups/{group_id}/files") async def api_group_files(group_id: str): + """The group's files, from its index.""" groups_ctx = state.get("groups_ctx", {}) ctx = groups_ctx.get(group_id) if not ctx: @@ -247,6 +267,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/peers") async def api_peers(): + """The connected peers.""" webrtc = state.get("webrtc") if not webrtc: return {"peers": []} @@ -275,6 +296,7 @@ def create_ui_app(state: dict) -> FastAPI: user_id: str | None = Query(default=None), event: str | None = Query(default=None), ): + """The audit log, filtered by time, account and event.""" audit = state.get("audit_store") if not audit: return {"entries": [], "offset": 0, "limit": limit, "has_more": False} @@ -316,66 +338,80 @@ def create_ui_app(state: dict) -> FastAPI: @app.post("/api/operator/pair") async def operator_pair(): + """A one-time code that pairs an application as this node's operator.""" return await _op(lambda: ops.pair_operator(state)) @app.get("/api/roster") async def api_roster(group_id: str = ""): + """The pinned identities, for one group or all.""" return await _op(lambda: ops.read_roster(state, group_id)) @app.post("/api/groups/{group_id}/invites") async def create_invite(group_id: str, username: str): + """An invitation code for one account, for this group.""" return await _op(lambda: ops.create_invite(state, group_id, username)) # Both halves, node and hub, for the CLI: an operator at the machine gets a # whole link, not a code without a ticket. @app.post("/api/groups/{group_id}/invite-links") async def create_link_invite(group_id: str, email: str = ""): + """A whole invitation link: the node's code, then the hub's ticket.""" return await _op(lambda: ops.create_link_invitation(state, group_id, email)) @app.delete("/api/groups/{group_id}/invite-links/{invite_id}") async def cancel_invite(group_id: str, invite_id: str): + """Take an invitation link back, on the node and on the hub.""" return await _op(lambda: ops.cancel_link_invitation(state, group_id, invite_id)) @app.get("/api/resolve") async def resolve_user(username: str): + """Map a username to an account id, through the hub.""" return await _op(lambda: ops.resolve_user(state, username)) @app.post("/api/members/{user_id}/revoke") async def revoke_member(user_id: str, group_id: str): + """Stop serving the group key to a member.""" return await _op(lambda: ops.revoke_member(state, user_id, group_id)) @app.post("/api/members/{user_id}/unpin") async def unpin_member(user_id: str): + """Forget a pinned identity, so the person can pair again with a new key.""" return await _op(lambda: ops.unpin_member(state, user_id)) # ── Chat encryption (operator only, localhost) ───────────────────────── @app.get("/api/groups/{group_id}/chat") async def chat_status(group_id: str): + """What the operator needs to decide anything about the group's chat.""" return await _op(lambda: ops.chat_status(state, group_id)) @app.post("/api/groups/{group_id}/chat/epoch") async def rotate_chat_epoch(group_id: str): + """Open a new chat epoch.""" return await _op(lambda: ops.open_chat_epoch(state, group_id)) @app.post("/api/groups/{group_id}/chat/encrypt-history") async def encrypt_chat_history(group_id: str): + """Re-encrypt the messages written before the group's chat was encrypted.""" return await _op(lambda: ops.encrypt_chat_history(state, group_id)) @app.post("/api/groups/{group_id}/chat/prune") async def prune_chat(group_id: str, max_age_days: int): + """Delete chat messages older than a number of days.""" return await _op(lambda: ops.prune_chat(state, group_id, max_age_days)) # ── GEK initialization (operator only, localhost) ────────────────────── @app.post("/api/groups/{group_id}/gek") async def init_gek(group_id: str, rotate: bool = False): + """Generate the group key, or rotate it with ?rotate=true.""" return await _op(lambda: ops.set_gek(state, group_id, rotate=rotate)) # ── Roots management (operator only, localhost) ──────────────────────── @app.post("/api/groups/{group_id}/roots") async def add_root(group_id: str, payload: dict): + """Add a folder to a group.""" result = await _op(lambda: ops.add_root( state, group_id, (payload.get("path") or "").strip(), @@ -392,6 +428,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.patch("/api/groups/{group_id}/roots/{root_name}") async def update_root(group_id: str, root_name: str, payload: dict): + """Make a folder writable or removable, or not.""" result = await _op(lambda: ops.update_root( state, group_id, root_name, writable=payload.get("writable"), @@ -404,14 +441,17 @@ def create_ui_app(state: dict) -> FastAPI: @app.put("/api/groups/{group_id}/roots/{root_name}/eject") async def eject_root(group_id: str, root_name: str): + """Eject a removable folder so its disk can be unplugged.""" return await _op(lambda: ops.eject_root(state, group_id, root_name)) @app.put("/api/groups/{group_id}/roots/{root_name}/plug") async def plug_root(group_id: str, root_name: str): + """Bring an ejected folder back.""" return await _op(lambda: ops.plug_root(state, group_id, root_name)) @app.delete("/api/groups/{group_id}/roots/{root_name}") async def remove_root(group_id: str, root_name: str): + """Remove a folder from a group. At least one must remain.""" result = await _op(lambda: ops.remove_root(state, group_id, root_name)) reload_fn = state.get("reload_fn") if reload_fn: @@ -427,6 +467,8 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/groups/{group_id}/index-status") async def index_status(group_id: str): """ + One group's indexing progress. + Polled by the Create Group wizard and by "add a directory" in Settings — the same source either way, since both just start a scan on this group's indexer. `current_dir` is a basename only, and is @@ -454,7 +496,9 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/index-status") async def index_status_all(): """ - Every group's indexing at once, for the client's progress band — which + Every group's indexing progress. + + All groups at once, for the client's progress band — which is on screen whatever page the operator is on, so it cannot ask per group. Names roots, like `current_dir` above: loopback only, the operator's own screen. Reads state["indexers"] for the same reason. @@ -488,6 +532,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.put("/api/groups/{group_id}/apps") async def set_enabled_apps(group_id: str, payload: dict): + """Which applications members see for the group.""" apps = payload.get("apps") if not isinstance(apps, list) or not apps: raise HTTPException(400, "apps must be a non-empty list") @@ -497,6 +542,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.post("/api/reload") async def reload_config(): + """Reload node.toml. Returns before the reload finishes.""" # start_reload, not reload_config: this must return before a # brand-new group's synchronous initial scan finishes (minutes, not # seconds, on a real library) — see ops.start_reload for why. @@ -506,6 +552,7 @@ def create_ui_app(state: dict) -> FastAPI: @app.post("/api/shutdown") async def shutdown(): + """Stop the daemon.""" # The graceful stop every front door tries first (the desktop app, the # CLI, the installer): it reaches a node in any session -- a service # node runs in session 0, where taskkill and CTRL_BREAK from the user's @@ -521,20 +568,24 @@ def create_ui_app(state: dict) -> FastAPI: @app.get("/api/node-settings") async def get_node_settings(): + """The node's effective settings.""" return await _op(lambda: ops.get_node_settings(state)) @app.put("/api/node-settings") async def update_node_settings(payload: dict): + """Change node settings, written to roster.db and node.toml.""" return await _op(lambda: ops.set_node_settings(state, payload)) # ── Transfers (operator only, localhost) ─────────────────────────────── @app.get("/api/transfers") async def get_transfers(): + """Live transfer leases and queue depth.""" return await _op(lambda: ops.list_transfers(state)) @app.put("/api/groups/{group_id}/transfer-limits") async def set_transfer_limits(group_id: str, payload: dict): + """How many transfers one member may run at once in this group.""" # The only door to `ops.set_transfer_limits` (the CLI uses it). It once # had only a signed MNP message, which nothing anywhere sent — so the # per-member cap sat at its default of 2 with no way to change it. diff --git a/packages/meshbay-node/tests/test_licensing.py b/packages/meshbay-node/tests/test_licensing.py new file mode 100644 index 0000000..6e50c80 --- /dev/null +++ b/packages/meshbay-node/tests/test_licensing.py @@ -0,0 +1,257 @@ +""" +Licensing: meshbay-common under the LGPL, everything else under the AGPL, and +every third-party piece a build ships accounted for. + +Reads files and installed metadata; builds nothing. What it guards against is +drift — a licence field nobody updates, a vendored file without its licence, a +GPL dependency creeping into the one package that must stay usable under the +LGPL. +""" + +import importlib.util +import json +import re +import tomllib +from importlib import metadata +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +PACKAGES = ROOT / "packages" +STATIC = PACKAGES / "meshbay-hub" / "src" / "meshbay_hub" / "static" +VENDOR = STATIC / "vendor" +DESKTOP = PACKAGES / "meshbay-client" / "src" +ANDROID = PACKAGES / "meshbay-android" / "app" / "src" / "main" / "kotlin" +KEYS = ANDROID / "org" / "meshbay" / "client" / "keys" +SPDX_LGPL = "// SPDX-License-Identifier: LGPL-3.0-or-later\n" +# The protocol layer in the clients (README, "Licence"): what a program needs to +# speak to a hub and a node, under the LGPL in every language it exists in. +LGPL_FILES = sorted( + [STATIC / f for f in ("keyderive.js", "crypto.js", "playlist-crypto.js")] + + [STATIC / "transport.js"] + + sorted(STATIC.glob("transport-*.js")) + + [DESKTOP / f for f in ("keyring.js", "transcripts.js", "argon2-wasm.js")] + + [KEYS / f for f in ("Kdf.kt", "Keyring.kt", "Transcripts.kt")] +) +EXPECTED = { + "meshbay-common": ("LGPL-3.0-or-later", ["COPYING", "COPYING.LESSER"]), + "meshbay-hub": ("AGPL-3.0-or-later", ["LICENSE"]), + "meshbay-node": ("AGPL-3.0-or-later", ["LICENSE"]), +} + + +def _notices(): + spec = importlib.util.spec_from_file_location( + "third_party_notices", ROOT / "packaging" / "third_party_notices.py" + ) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def test_each_python_package_declares_its_licence_and_ships_the_text(): + for pkg, (expr, files) in EXPECTED.items(): + project = tomllib.loads((PACKAGES / pkg / "pyproject.toml").read_text())["project"] + assert project["license"] == expr, pkg + assert project["license-files"] == files, pkg + for f in files: + assert (PACKAGES / pkg / f).is_file(), f"{pkg}/{f}" + + +def test_licence_texts_are_the_right_ones(): + agpl = (ROOT / "LICENSE").read_text() + assert "GNU AFFERO GENERAL PUBLIC LICENSE" in agpl and "Version 3" in agpl + # Copies, because a wheel's license-files cannot reach outside its package. + for pkg in ("meshbay-hub", "meshbay-node"): + assert (PACKAGES / pkg / "LICENSE").read_text() == agpl, pkg + common = PACKAGES / "meshbay-common" + assert "GNU LESSER GENERAL PUBLIC LICENSE" in (common / "COPYING.LESSER").read_text() + assert "GNU GENERAL PUBLIC LICENSE" in (common / "COPYING").read_text() + + +def test_rpm_specs_and_the_client_agree_with_the_packages(): + for pkg in ("meshbay-common", "meshbay-hub", "meshbay-node", "meshbay-client"): + spec = (ROOT / "packaging" / "rpm" / f"{pkg}.spec").read_text() + want = EXPECTED.get(pkg, ("AGPL-3.0-or-later",))[0] + assert re.search(rf"^License:\s+{re.escape(want)}\s*$", spec, re.M), pkg + assert "%license %{_licensedir}/%{name}" in spec, pkg + pkg_json = json.loads((PACKAGES / "meshbay-client" / "package.json").read_text()) + assert pkg_json["license"] == "AGPL-3.0-or-later" + + +def test_every_windows_target_ships_the_licence(): + pkg_json = json.loads((PACKAGES / "meshbay-client" / "package.json").read_text()) + assert {"from": "../../LICENSE", "to": "LICENSE.txt"} in pkg_json["build"]["win"][ + "extraResources" + ] + for yml in ("electron-builder.light.yml", "electron-builder.msix.yml"): + text = (ROOT / "packaging" / "win" / yml).read_text() + assert "- from: ../../LICENSE\n to: LICENSE.txt" in text, yml + ps1 = (ROOT / "packaging" / "win" / "build-node-runtime.ps1").read_text() + assert "third_party_notices.py" in ps1 and "THIRD-PARTY-NOTICES.txt" in ps1 + + +def test_common_depends_on_nothing_copyleft(): + """The LGPL is only worth something if the library can be taken alone.""" + for req in metadata.distribution("meshbay-common").requires or []: + if "extra ==" in req: + continue + name = re.split(r"[\s\[<>=!~;(]", req, maxsplit=1)[0] + md = metadata.distribution(name).metadata + label = " ".join( + [md.get("License-Expression") or "", md.get("License") or ""] + + (md.get_all("Classifier") or []) + ) + assert "GPL" not in label, f"{name}: {label[:120]}" + + +def test_notices_follow_what_the_node_actually_ships(): + mod = _notices() + dists = mod._closure(["meshbay-node"]) + assert "mutagen" in dists and "guessit" in dists and "av" in dists + # Extras the node does not ask for, and dev tools, stay out. + assert "pytest" not in dists and "piexif" not in dists + text = mod.render(["meshbay-node"], [], with_python=False) + assert re.search(r"^ mutagen [\d.]+ — GPL", text, re.M) + libs = mod._native_libs(dists["av"]) + if libs: # PyAV's FFmpeg is grafted in; the notice must say which + assert libs[0] in text + + +def test_every_vendored_file_has_its_provenance_and_licence(): + provenance = (VENDOR / "PROVENANCE.md").read_text() + licences = (VENDOR / "LICENSES.txt").read_text() + for f in VENDOR.iterdir(): + if f.name in ("PROVENANCE.md", "LICENSES.txt"): + continue + assert f"## {f.name}" in provenance or f"### {f.name}" in provenance, f.name + assert f.name in licences, f.name + + +def _sources(): + for tree, pattern in ((STATIC, "*.js"), (DESKTOP, "*.js"), (ANDROID, "**/*.kt")): + for f in tree.glob(pattern): + if "vendor" not in f.parts and "locales" not in f.parts: + yield f + + +def test_the_lgpl_files_are_exactly_the_ones_that_say_so(): + marked = sorted(f for f in _sources() if f.read_text().startswith(SPDX_LGPL)) + assert marked == LGPL_FILES + + +def test_every_client_carries_the_licence_texts(): + """static/ is the interface of the web, the desktop and Android alike.""" + texts = STATIC / "licenses" + assert (texts / "AGPL-3.0.txt").read_text() == (ROOT / "LICENSE").read_text() + common = PACKAGES / "meshbay-common" + assert (texts / "LGPL-3.0.txt").read_text() == (common / "COPYING.LESSER").read_text() + assert (texts / "GPL-3.0.txt").read_text() == (common / "COPYING").read_text() + + +def _strip_js(src: str) -> str: + src = re.sub(r"/\*[\s\S]*?\*/|//[^\n]*", "", src) + return re.sub(r"'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"", "''", src) + + +def test_the_lgpl_layer_depends_on_nothing_under_the_agpl(): + """ + One import of an AGPL module and a client built on the layer is under the + AGPL after all. What a host supplies (window.MeshBayPlatform, a Secrets + store) is an injected interface, and is not looked for here. + """ + lgpl = set(LGPL_FILES) + top = re.compile( + r"^(?:export\s+)?(?:async\s+)?(?:function\*?\s+|(?:const|let|var|class)\s+)" + r"([A-Za-z_$][\w$]*)", + re.M, + ) + defined_in_lgpl = {n for f in lgpl if f.suffix == ".js" for n in top.findall(f.read_text())} + agpl_globals = { + n: f.name + for f in STATIC.glob("*.js") + if f not in lgpl + for n in top.findall(f.read_text()) + if n not in defined_in_lgpl + } + kt_decl = re.compile(r"^\s*(?:\w+\s+)*(?:class|object|interface)\s+(\w+)", re.M) + defined_in_lgpl_kt = { + n for f in lgpl if f.suffix == ".kt" for n in kt_decl.findall(f.read_text()) + } + agpl_kotlin = { + n: f.name + for f in ANDROID.glob("**/*.kt") + if f not in lgpl + for n in kt_decl.findall(f.read_text()) + if n not in defined_in_lgpl_kt + } + for f in LGPL_FILES: + src = f.read_text() + if f.suffix == ".kt": + for imp in re.findall(r"^import (org\.meshbay\.[\w.]+)", src, re.M): + owner = ( + imp.split(".")[-2] if imp.split(".")[-1][0].islower() else imp.split(".")[-1] + ) + assert owner in {g.stem for g in lgpl}, f"{f.name} imports {imp}" + code = _strip_js(src) # Kotlin's comments and strings take the same shapes + for name, owner in agpl_kotlin.items(): + assert not re.search(rf"\b{name}\b", code), f"{f.name} uses {name} ({owner})" + continue + code = _strip_js(src) + uncommented = re.sub(r"/\*[\s\S]*?\*/|^\s*//[^\n]*", "", src, flags=re.M) + for spec in re.findall( + r"""(?:\bfrom|\bimport\(|\brequire\()\s*['"]([^'"\n]+)['"]""", uncommented + ): + if spec.startswith("node:") or "vendor" in spec: + continue + assert (f.parent / spec).resolve() in lgpl, f"{f.name} imports {spec}" + for name, owner in agpl_globals.items(): + assert not re.search(rf"(?<![\w$.]){re.escape(name)}\s*\(", code), ( + f"{f.name} calls {name}() from {owner}" + ) + + +APP_EXCEPTION = STATIC / "licenses" / "APPLICATION-EXCEPTION.txt" +REFERENCE_APP = [STATIC / "helloworld-app.js", STATIC / "helloworld-app-settings.js"] + + +def _interface_modules() -> set[str]: + """The modules the permission names — read from it, the one place they are listed.""" + text = APP_EXCEPTION.read_text() + block = text.split("2. the names exported by these modules", 1)[1].split("3.", 1)[0] + return set(re.findall(r"^\s+([\w-]+\.js)\s*$", block, re.M)) + + +def test_the_application_interface_names_modules_that_exist(): + modules = _interface_modules() + assert modules == {"i18n.js", "icon.js", "file-utils.js", "settings-ui.js", "folder-tree.js"} + for m in modules: + assert (STATIC / m).is_file(), m + assert not (STATIC / m).read_text().startswith(SPDX_LGPL), ( + f"{m} is LGPL already; the permission is for the AGPL part" + ) + + +def test_the_reference_application_is_free_to_copy_and_stays_inside_the_interface(): + """ + Copying helloworld is how an application starts. Were it to import anything + outside the application interface, every application started from it would + be a work based on the AGPL interface without anybody having chosen that. + """ + allowed = _interface_modules() | {f.name for f in LGPL_FILES if f.parent == STATIC} + for f in REFERENCE_APP: + src = f.read_text() + assert src.startswith("// SPDX-License-Identifier: 0BSD\n"), f.name + for spec in re.findall(r"""^import .* from ['"]\./([^'"]+)['"]""", src, re.M): + assert spec.startswith("vendor/") or spec in allowed, f"{f.name} imports {spec}" + assert "import(" not in _strip_js(src), f"{f.name}: a dynamic import escapes this check" + + +def test_every_spdx_line_is_one_of_the_known_licences(): + for f in _sources(): + first = f.read_text().split("\n", 1)[0] + if "SPDX-License-Identifier" not in first: + continue + if f in REFERENCE_APP: + assert first.endswith(": 0BSD"), f.name + else: + assert f in LGPL_FILES, f"{f.name}: {first}" diff --git a/packages/meshbay-node/tests/test_root_eject.py b/packages/meshbay-node/tests/test_root_eject.py index d73e71c..b6b50aa 100644 --- a/packages/meshbay-node/tests/test_root_eject.py +++ b/packages/meshbay-node/tests/test_root_eject.py @@ -264,3 +264,131 @@ async def test_the_ejected_key_is_case_folded(tmp_path): assert Roster.root_ejected_key("Films") == Roster.root_ejected_key("FILMS") finally: await roster.close() + + +# ── The safety net's eject undoes itself; the operator's does not ─────────── + +def _vanish(films: Path) -> None: + for f in films.iterdir(): + f.unlink() + films.rmdir() + + +async def test_an_auto_ejected_root_comes_back_with_its_own_files(tmp_path): + """ + The drive that was not mounted yet when the node started (found on a node + started with the session, its USB drives mounted a minute later): the + safety net ejected it, and once the same files are readable at the same + place it is plugged back without anyone having to. + """ + films = tmp_path / "Films" + films.mkdir() + (films / "a.mkv").write_bytes(b"a") + seen: list[tuple[str, bool]] = [] + + async def record(name: str, ejected: bool) -> None: + seen.append((name, ejected)) + + roots = _roots(films) + idx = await _indexer(roots, on_root_ejected=record) + hidden = tmp_path / "unmounted" + films.rename(hidden) + await idx.reconcile() + assert roots.roots[0].ejected is True + + hidden.rename(films) + await idx.reconcile() + assert roots.roots[0].ejected is False + assert roots.roots[0].available is True + assert _names(idx) == {"a.mkv"} + assert seen == [("Films", True), ("Films", False)] + + +@pytest.mark.parametrize("what_came_back", ["empty", "another drive"]) +async def test_an_auto_ejected_root_stays_out_when_its_files_are_not_there( + tmp_path, what_came_back): + """ + What the safety net exists for: an empty mount point, or another drive + mounted at the same place, is not the library. Plugging it back would + rescan it, and the rescan would read the library as erased. + """ + films = tmp_path / "Films" + films.mkdir() + (films / "a.mkv").write_bytes(b"a") + roots = _roots(films) + idx = await _indexer(roots) + _vanish(films) + await idx.reconcile() + + films.mkdir() + if what_came_back == "another drive": + (films / "other.mkv").write_bytes(b"something else") + await idx.reconcile() + assert roots.roots[0].ejected is True + assert _names(idx) == {"a.mkv"}, "the library was treated as erased" + + +async def test_an_operator_eject_is_never_undone_automatically(tmp_path): + films = tmp_path / "Films" + films.mkdir() + (films / "a.mkv").write_bytes(b"a") + roots = _roots(films) + idx = await _indexer(roots) + + idx.eject_root("Films") + await idx.reconcile() + assert roots.roots[0].ejected is True + + +async def test_after_a_restart_the_cache_recognises_the_drive(tmp_path): + """ + A restarted node has no index entry for an ejected root: the index is + rebuilt by scanning, and an ejected root is not scanned. What it does have is + the hash cache, with the size and mtime of every file it read there. + """ + import os + + from meshbay_node.indexer.cache import IndexCache + + films = tmp_path / "Films" + films.mkdir() + movie = films / "a.mkv" + movie.write_bytes(b"a") + st = movie.stat() + + def restarted_ejected() -> RootSet: + return RootSet.build([{"path": str(films), "removable": True, + "ejected": True, "ejected_auto": True}]) + + async with IndexCache(tmp_path / "cache.db") as cache: + await _indexer(_roots(films), cache=cache) + + # Another drive at the same place, with a file of the same name. + movie.write_bytes(b"another drive") + roots = restarted_ejected() + await _indexer(roots, cache=cache) + assert roots.roots[0].ejected is True + + # The drive itself. + movie.write_bytes(b"a") + os.utime(movie, ns=(st.st_atime_ns, st.st_mtime_ns)) + roots = restarted_ejected() + idx = await _indexer(roots, cache=cache) + assert roots.roots[0].ejected is False + assert _names(idx) == {"a.mkv"} + + +async def test_the_roster_keeps_an_auto_eject_apart(tmp_path): + roster = Roster(db_path=tmp_path / "roster.db") + await roster.open() + try: + await roster.set_root_ejected("g1", "Films", True, set_by="op", auto=True) + await roster.set_root_ejected("g1", "Music", True, set_by="op") + assert await roster.ejected_roots("g1") == {"films", "music"} + assert await roster.auto_ejected_roots("g1") == {"films"} + + # An operator eject of the same root replaces the safety net's. + await roster.set_root_ejected("g1", "Films", True, set_by="op") + assert await roster.auto_ejected_roots("g1") == set() + finally: + await roster.close() diff --git a/packaging/build/build-common.sh b/packaging/build/build-common.sh index 3045689..5f119c6 100755 --- a/packaging/build/build-common.sh +++ b/packaging/build/build-common.sh @@ -44,6 +44,11 @@ echo " installing all packages + dependencies" --find-links "$WHEEL_DIR" \ meshbay-common meshbay-hub meshbay-node 2>&1 | tail -3 +# --- Third-party notices: every package the venv ships, with its licence ------- +echo " writing THIRD-PARTY-NOTICES.txt" +"$VENV_BUILD/bin/python" "$REPO/packaging/third_party_notices.py" \ + -o "$ROOT/opt/meshbay-common/THIRD-PARTY-NOTICES.txt" meshbay-hub meshbay-node + # --- Strip build tools from the venv (not needed at runtime) --------------- echo " stripping build tools" "$VENV_BUILD/bin/pip" uninstall -y pip setuptools wheel 2>&1 | tail -1 diff --git a/packaging/build/build-packages.sh b/packaging/build/build-packages.sh index ccacb81..8ca0e23 100755 --- a/packaging/build/build-packages.sh +++ b/packaging/build/build-packages.sh @@ -84,6 +84,38 @@ echo "" echo "--- Packaging ($FORMAT) ---" if [ "$FORMAT" = "deb" ]; then + # Debian policy: /usr/share/doc/<pkg>/copyright, machine-readable. The LGPL + # is in /usr/share/common-licenses and is referred to; the AGPL is not, so + # its full text goes in, as a DEP-5 licence paragraph (indented, "." for a + # blank line). + install_copyright() { + local pkg="$1" root="$2" + local doc="$root/usr/share/doc/$pkg" + mkdir -p "$doc" + { + echo "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/" + echo "Upstream-Name: MeshBay" + echo "Source: https://git.meshbay.org/" + echo "" + echo "Files: *" + echo "Copyright: MeshBay contributors" + if [ "$pkg" = "meshbay-common" ]; then + echo "License: LGPL-3.0-or-later" + echo " On Debian systems, the full text of the GNU Lesser General Public" + echo " License version 3 is in /usr/share/common-licenses/LGPL-3, and the" + echo " GNU General Public License it builds on in /usr/share/common-licenses/GPL-3." + echo " ." + echo " The venv under /opt/meshbay-common carries the Python packages MeshBay" + echo " depends on, each under its own licence; they are listed, with their" + echo " licence texts, in /opt/meshbay-common/THIRD-PARTY-NOTICES.txt." + else + echo "License: AGPL-3.0-or-later" + sed -e 's/^$/./' -e 's/^/ /' "$REPO/LICENSE" + fi + } > "$doc/copyright" + chmod 644 "$doc/copyright" + } + build_deb() { local pkg="$1" local root="$STAGING/${pkg}-root" @@ -102,6 +134,8 @@ if [ "$FORMAT" = "deb" ]; then [ -f "$deb_dir/control" ] && chmod 644 "$deb_dir/control" [ -f "$deb_dir/conffiles" ] && chmod 644 "$deb_dir/conffiles" + install_copyright "$pkg" "$root" + dpkg-deb --build --root-owner-group "$root" "$OUT/${pkg}_${VERSION}_${ARCH}.deb" echo " -> $OUT/${pkg}_${VERSION}_${ARCH}.deb" } @@ -127,6 +161,7 @@ elif [ "$FORMAT" = "rpm" ]; then rpmbuild \ --define "_topdir $RPMBUILD_DIR" \ --define "_staging_root $root" \ + --define "_repo_root $REPO" \ -bb "$RPMBUILD_DIR/SPECS/${pkg}.spec" 2>&1 | tail -5 local rpm_file diff --git a/packaging/rpm/meshbay-client.spec b/packaging/rpm/meshbay-client.spec index 0816741..e4f9f03 100644 --- a/packaging/rpm/meshbay-client.spec +++ b/packaging/rpm/meshbay-client.spec @@ -2,7 +2,7 @@ Name: meshbay-client Version: __VERSION__ Release: 1%{?dist} Summary: MeshBay — peer-to-peer file sharing, streaming and group chat -License: AGPLv3+ +License: AGPL-3.0-or-later URL: https://meshbay.org AutoReqProv: no @@ -35,6 +35,7 @@ launcher named "MeshBay". %install cp -a %{_staging_root}/* %{buildroot}/ +install -Dm644 -t %{buildroot}%{_licensedir}/%{name} %{_repo_root}/LICENSE %post if [ -f /opt/meshbay-client/chrome-sandbox ]; then @@ -49,6 +50,7 @@ update-desktop-database /usr/share/applications 2>/dev/null || true gtk-update-icon-cache -f -t /usr/share/icons/hicolor 2>/dev/null || true %files +%license %{_licensedir}/%{name} /opt/meshbay-client /usr/bin/meshbay /usr/share/applications/meshbay.desktop diff --git a/packaging/rpm/meshbay-common.spec b/packaging/rpm/meshbay-common.spec index 147dc17..cad00b7 100644 --- a/packaging/rpm/meshbay-common.spec +++ b/packaging/rpm/meshbay-common.spec @@ -2,7 +2,9 @@ Name: meshbay-common Version: __VERSION__ Release: 1%{?dist} Summary: MeshBay shared Python runtime and libraries -License: AGPLv3+ +# The venv carries every Python dependency, each under its own licence: +# /opt/meshbay-common/THIRD-PARTY-NOTICES.txt lists them. +License: LGPL-3.0-or-later URL: https://meshbay.org AutoReqProv: no @@ -16,6 +18,9 @@ Installs to /opt/meshbay-common/venv/. %install cp -a %{_staging_root}/* %{buildroot}/ +install -Dm644 -t %{buildroot}%{_licensedir}/%{name} \ + %{_repo_root}/packages/meshbay-common/COPYING \ + %{_repo_root}/packages/meshbay-common/COPYING.LESSER # Bytecode written at run time into __pycache__ is not the package's, and would # keep rpm from removing a directory the new version no longer ships. @@ -32,6 +37,7 @@ if [ "$1" -eq 0 ]; then fi %files +%license %{_licensedir}/%{name} /opt/meshbay-common %changelog diff --git a/packaging/rpm/meshbay-hub.spec b/packaging/rpm/meshbay-hub.spec index ffd991a..141f6e6 100644 --- a/packaging/rpm/meshbay-hub.spec +++ b/packaging/rpm/meshbay-hub.spec @@ -2,7 +2,7 @@ Name: meshbay-hub Version: __VERSION__ Release: 1%{?dist} Summary: MeshBay Hub — identity authority and group registry server -License: AGPLv3+ +License: AGPL-3.0-or-later URL: https://meshbay.org AutoReqProv: no @@ -21,6 +21,7 @@ Runs as a systemd service behind Caddy for HTTPS. %install cp -a %{_staging_root}/* %{buildroot}/ +install -Dm644 -t %{buildroot}%{_licensedir}/%{name} %{_repo_root}/LICENSE %pre getent group meshbay >/dev/null || groupadd -r meshbay @@ -51,6 +52,7 @@ fi %systemd_postun_with_restart meshbay-hub.service %files +%license %{_licensedir}/%{name} /opt/meshbay-hub /opt/meshbay-common/venv/lib/python*/site-packages/meshbay_hub/ /opt/meshbay-common/venv/lib/python*/site-packages/meshbay_hub-*.dist-info/ diff --git a/packaging/rpm/meshbay-node.spec b/packaging/rpm/meshbay-node.spec index 89f3a0a..18d432e 100644 --- a/packaging/rpm/meshbay-node.spec +++ b/packaging/rpm/meshbay-node.spec @@ -2,7 +2,7 @@ Name: meshbay-node Version: __VERSION__ Release: 1%{?dist} Summary: MeshBay Node — local file host, streaming server, and group daemon -License: AGPLv3+ +License: AGPL-3.0-or-later URL: https://meshbay.org AutoReqProv: no @@ -29,6 +29,7 @@ Runs as a systemd user service. %install cp -a %{_staging_root}/* %{buildroot}/ +install -Dm644 -t %{buildroot}%{_licensedir}/%{name} %{_repo_root}/LICENSE %post if [ -d /run/systemd/system ]; then @@ -90,6 +91,7 @@ if [ "$1" -eq 0 ]; then fi %files +%license %{_licensedir}/%{name} /opt/meshbay-node /opt/meshbay-common/venv/lib/python*/site-packages/meshbay_node/ /opt/meshbay-common/venv/lib/python*/site-packages/meshbay_node-*.dist-info/ diff --git a/packaging/third_party_notices.py b/packaging/third_party_notices.py new file mode 100644 index 0000000..85a35a9 --- /dev/null +++ b/packaging/third_party_notices.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Write THIRD-PARTY-NOTICES.txt for the Python packages a MeshBay build ships. + +Run with the interpreter of the environment being shipped — the deb/rpm venv +(build-common.sh) or the PyInstaller build venv (build-node-runtime.ps1) — so +the list is the set actually installed there, read from each package's own +metadata, rather than a hand-kept list that drifts with every upgrade. + + python third_party_notices.py -o OUT ROOT... [--extra NAME...] [--with-python] + +ROOTS are walked through their runtime requirements (extras skipped). --extra +names packages that ship without being imported, PyInstaller's bootloader being +the case. Native libraries a wheel grafts into a `<name>.libs/` directory are +listed under the package that carries them: PyAV's FFmpeg build includes +libx264 and libx265, both GPL, and that is not visible in its own BSD licence. +""" + +import argparse +import re +import sys +from importlib import metadata +from pathlib import Path + +OWN = re.compile(r"^meshbay-") +LICENSE_NAME = re.compile(r"(LICEN[CS]E|COPYING|NOTICE|AUTHORS)", re.IGNORECASE) +RULE = "=" * 78 + + +def _norm(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _marker_applies(marker: str, extras: set[str]) -> bool: + try: + from packaging.markers import Marker + except ImportError: + # Better a notice too many than one missing. + return "extra" not in marker or any(f'"{e}"' in marker for e in extras) + return any(Marker(marker).evaluate({"extra": e}) for e in extras | {""}) + + +def _parse(req: str) -> tuple[str, set[str], str]: + spec, _, marker = req.partition(";") + m = re.match(r"\s*([A-Za-z0-9._-]+)\s*(?:\[([^\]]*)\])?", spec) + extras = {_norm(e) for e in (m.group(2) or "").split(",") if e.strip()} + return m.group(1), extras, marker.strip() + + +def _closure(roots: list[str]) -> dict[str, metadata.Distribution]: + seen: dict[str, metadata.Distribution] = {} + done: set[tuple[str, str]] = set() + todo = [_parse(r)[:2] for r in roots] + while todo: + name, extras = todo.pop() + name = _norm(name) + try: + dist = seen.get(name) or metadata.distribution(name) + except metadata.PackageNotFoundError: + continue # a requirement whose marker excludes this platform + seen[name] = dist + for extra in extras | {""}: + if (name, extra) in done: + continue + done.add((name, extra)) + for req in dist.requires or []: + dep, dep_extras, marker = _parse(req) + if marker and not _marker_applies(marker, {extra} - {""}): + continue + if not marker and extra: + continue # already taken with the base requirements + todo.append((dep, dep_extras)) + return seen + + +def _license_label(dist: metadata.Distribution) -> str: + md = dist.metadata + expr = md.get("License-Expression") + if expr: + return expr + classifiers = [ + c.split("::")[-1].strip() + for c in md.get_all("Classifier") or [] + if c.startswith("License ::") + ] + if classifiers: + return "; ".join(classifiers) + return (md.get("License") or "see licence text below").splitlines()[0] + + +def _license_texts(dist: metadata.Distribution) -> list[tuple[str, str]]: + texts = [] + for f in dist.files or []: + parts = f.parts + if not parts or not parts[0].endswith(".dist-info"): + continue + if not LICENSE_NAME.search(f.name) or f.suffix in (".py", ".pyc"): + continue + try: + texts.append(("/".join(parts[1:]), f.read_text(encoding="utf-8"))) + except (OSError, UnicodeDecodeError): + continue + return texts + + +def _native_libs(dist: metadata.Distribution) -> list[str]: + return sorted( + f.name for f in dist.files or [] if len(f.parts) > 1 and f.parts[0].endswith(".libs") + ) + + +def _homepage(dist: metadata.Distribution) -> str: + md = dist.metadata + if md.get("Home-page"): + return md["Home-page"] + for url in md.get_all("Project-URL") or []: + label, _, link = url.partition(",") + if label.strip().lower() in ("homepage", "source", "repository", "source code"): + return link.strip() + return "" + + +def render(roots: list[str], extra: list[str], with_python: bool) -> str: + dists = _closure(roots + extra) + own = sorted(n for n in dists if OWN.match(n)) + third = sorted(n for n in dists if not OWN.match(n)) + + out = [ + "MeshBay — third-party notices", + RULE, + "", + "MeshBay itself: meshbay-common is LGPL-3.0-or-later, every other MeshBay", + "component is AGPL-3.0-or-later. Source: https://git.meshbay.org/", + "", + "This build also carries the packages below, each under its own licence.", + "Each is distributed unmodified, as published on https://pypi.org/; the", + "corresponding source of every one is that release's source distribution", + "there, or the project home page given with it.", + "", + ] + if with_python: + out += [f"Python {sys.version.split()[0]} — PSF-2.0 — https://www.python.org/", ""] + for name in own: + out.append( + f" {dists[name].metadata['Name']} {dists[name].version}" + f" — {_license_label(dists[name])}" + ) + out.append("") + for name in third: + d = dists[name] + out.append(f" {d.metadata['Name']} {d.version} — {_license_label(d)}") + out.append("") + + for name in third: + d = dists[name] + out += [RULE, f"{d.metadata['Name']} {d.version}", f"Licence: {_license_label(d)}"] + if home := _homepage(d): + out.append(f"Home: {home}") + if libs := _native_libs(d): + out.append("Native libraries bundled in this package's wheel (each under its") + out.append("own licence, built and published by the project above):") + out += [f" {lib}" for lib in libs] + out.append(RULE) + texts = _license_texts(d) + if not texts: + out.append("(no licence file shipped in this package's metadata)") + for path, text in texts: + out += ["", f"--- {path} ---", "", text.rstrip(), ""] + out.append("") + + base_license = Path(sys.base_prefix) / "LICENSE.txt" + if with_python and base_license.is_file(): + out += [ + RULE, + f"Python {sys.version.split()[0]}", + RULE, + "", + base_license.read_text(encoding="utf-8", errors="replace").rstrip(), + "", + ] + return "\n".join(out) + "\n" + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("-o", "--output", type=Path, required=True) + ap.add_argument("roots", nargs="+") + ap.add_argument("--extra", nargs="*", default=[]) + ap.add_argument( + "--with-python", + action="store_true", + help="the interpreter itself ships too (a frozen build, not a system-python venv)", + ) + args = ap.parse_args() + args.output.write_text(render(args.roots, args.extra, args.with_python), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/packaging/win/build-node-runtime.ps1 b/packaging/win/build-node-runtime.ps1 index 371311b..1171146 100644 --- a/packaging/win/build-node-runtime.ps1 +++ b/packaging/win/build-node-runtime.ps1 @@ -109,6 +109,22 @@ if (-not (Test-Path (Join-Path $frozen "meshbay-node.exe"))) { throw "PyInstaller did not produce meshbay-node.exe at $frozen" } +# --- 3b. licences ---------------------------------------------------- +# The frozen tree is a distribution of every package in it, so each one's +# licence goes with it: MeshBay's own (AGPL for the node, LGPL for the common +# library it embeds) and THIRD-PARTY-NOTICES.txt, generated from the build +# venv's own metadata -- PyAV's wheel, for one, grafts in a GPL FFmpeg build +# (libx264, libx265) that its BSD licence does not mention. PyInstaller's +# bootloader and the interpreter ship too, without being a requirement. +Step "writing licence notices" +Copy-Item (Join-Path $Repo "LICENSE") (Join-Path $frozen "LICENSE.txt") +Copy-Item (Join-Path $Repo "packages\meshbay-common\COPYING.LESSER") (Join-Path $frozen "LICENSE-meshbay-common.txt") +Copy-Item (Join-Path $Repo "packages\meshbay-common\COPYING") (Join-Path $frozen "LICENSE-GPL-3.0.txt") +& $Python (Join-Path $Repo "packaging\third_party_notices.py") ` + -o (Join-Path $frozen "THIRD-PARTY-NOTICES.txt") ` + meshbay-node tzdata --extra pyinstaller --with-python +if ($LASTEXITCODE -ne 0) { throw "third_party_notices.py failed" } + # --- 4. ffmpeg (bundled by default) ----------------------------------- if ($SkipFfmpeg -or $env:MESHBAY_SKIP_FFMPEG -eq "1") { Write-Host " !! ffmpeg not bundled (-SkipFfmpeg) -- the node will look for it on PATH, and streaming needs it installed separately" -ForegroundColor Yellow diff --git a/packaging/win/electron-builder.light.yml b/packaging/win/electron-builder.light.yml index 502a3c5..6cd2b0d 100644 --- a/packaging/win/electron-builder.light.yml +++ b/packaging/win/electron-builder.light.yml @@ -36,6 +36,10 @@ win: # ICE + the 2 LAN-casting rules) and logs the node rule as skipped. - from: ../../packaging/win/firewall.ps1 to: firewall.ps1 + # The application's own licence, beside the app (Electron's LICENSE and + # LICENSES.chromium.html are put next to the exe by electron-builder). + - from: ../../LICENSE + to: LICENSE.txt nsis: oneClick: false diff --git a/packaging/win/electron-builder.msix.yml b/packaging/win/electron-builder.msix.yml index 5460267..d3adad6 100644 --- a/packaging/win/electron-builder.msix.yml +++ b/packaging/win/electron-builder.msix.yml @@ -69,6 +69,10 @@ win: # anticipated in the original plan). - from: ../../packaging/win/ensure-node-path.ps1 to: ensure-node-path.ps1 + # The application's own licence, beside the app (Electron's LICENSE and + # LICENSES.chromium.html are put next to the exe by electron-builder). + - from: ../../LICENSE + to: LICENSE.txt appx: # --- Real values, from Partner Center's "App identity" page (App |