commit 9508b6b6738e3db693459a000f9fcbc72a858562 equwal <truex@equwal.com> 2026-09-21 03:55:56 -0700 sbm-sync: a sync server for sbm bookmark files A device sends its bookmark file and the version that it got last time. The server merges the changes of the device into its copy by lines, keeps the result and sends it back. An edit on a device wins over the server. Without a known version, the merge is the union of both files. Accounts are an email address and a bcrypt password hash. Devices get a token; the server keeps only its SHA-256. Data is plain files: one JSON file of accounts and the last 50 versions of each bookmark file. Billing through Stripe Checkout, webhooks and the customer portal is off unless STRIPE_SECRET_KEY is set. The trial starts at sign-up, or at SBM_BILLING_START if that is later.
.gitattributes | 1 + .github/FUNDING.yml | 1 + .gitignore | 4 + LICENSE | 662 +++++++++++++++++++++ README.md | 117 ++++ contrib/nginx.conf | 14 + contrib/sbm-sync.service | 26 + go.mod | 7 + go.sum | 4 + main.go | 601 +++++++++++++++++++ merge.go | 123 ++++ merge_test.go | 192 ++++++ pages.html | 126 ++++ server_test.go | 457 ++++++++++++++ store.go | 399 +++++++++++++ stripe.go | 163 +++++ ...TestLocalAdditionsStay-20260921033717-1828.fail | 18 + ...nsStayWithoutConflict-20260921033649-16892.fail | 18 + 18 files changed, 2933 insertions(+)
diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..d303709 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: truex diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84c3a8c --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +data/ +/sbm-sync +/sbm-sync.exe +*.env diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fe6b903 --- /dev/null +++ b/LICENSE @@ -0,0 +1,662 @@ + 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/README.md b/README.md new file mode 100644 index 0000000..c46d54b --- /dev/null +++ b/README.md @@ -0,0 +1,117 @@ +# sbm-sync + +sbm-sync keeps your [sbm](https://github.com/equwal/sbm) bookmark file the +same on each of your devices: bm on your computers, the sbm app for Android +and the sbm add-on for Firefox and Chrome. + +It is one small Go program. It keeps its data in plain files: no database. +The only dependency is `golang.org/x/crypto` for bcrypt. + +The clients use **https://sbm.subread.space** unless you set another +server. That server is free for 30 days, then $3 a month or $30 a year. +Run your own server free of charge. + +## How sync works + +A device sends its whole bookmark file and the name of the version that it +got last time. The server merges the changes of the device into its own +copy, keeps the result and sends it back. The device writes the result to +its file and keeps the new version name. + +The merge compares whole lines: + +- A line that the device removed since its last version goes. +- A line that the device added comes in, at the end of the file, where bm + adds bookmarks. When the server has another line for the same bookmark + (the same URL, as bm compares URLs), the line of the device takes its + place. So an edit on a device wins. +- Lines that other devices added stay. + +When the server does not know the last version of a device (for its first +sync), nothing is removed: the result is the union of both files. + +## Protocol + +Plain HTTP, for any client with curl. + + POST /api/login form fields email, password + 200: a token, as text + POST /api/sync?base=V Authorization: Bearer <token> + body: the bookmark file + 200: the merged file; header Sbm-Version: <new V> + POST /api/logout Authorization: Bearer <token> + +Errors come as text: 401 (sign in again), 402 (the subscription or the +trial has ended), 413 (the file is larger than 4 MB), 429 (too many sign-in +attempts). + + curl -d email=me@example.org --data-urlencode password=... https://sbm.subread.space/api/login + curl -H "Authorization: Bearer $token" --data-binary @bookmarks \ + "https://sbm.subread.space/api/sync?base=$version" + +## Run your own server + + go build + SBM_URL=https://sbm.example.org ./sbm-sync + +Then put it behind a web server that does TLS. `contrib/` has a systemd unit +and an nginx site. With Go installed elsewhere: + + GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build + +Settings, all through the environment: + + SBM_URL public address of the server (default http://localhost:8750) + SBM_ADDR address to listen on (default 127.0.0.1:8750) + SBM_DATA data directory (default ./data) + SBM_CONTACT email address on the privacy page (optional) + SBM_TRIAL_DAYS days of sync before payment, with billing on (default 30) + SBM_BILLING_START date when billing starts, as 2026-10-01: accounts + from before it get the full trial from that date + +Accounts need no email check. To reset a password, the operator deletes the +account in `accounts.json` (with the server stopped), and the user signs up +again. The bookmark files stay on the devices. + +## Billing + +Billing is off unless `STRIPE_SECRET_KEY` is set. Without billing, sync +is free for all accounts. To turn it on: + +1. In Stripe, make a product with two recurring prices, for example $3 a + month and $30 a year. +2. Add a webhook endpoint `https://<your server>/stripe` for the events + `checkout.session.completed`, `customer.subscription.created`, + `customer.subscription.updated` and `customer.subscription.deleted`. +3. Turn on the customer portal in the Stripe settings, so that customers + can cancel and change their card. +4. Set these variables, then restart the server: + + STRIPE_SECRET_KEY sk_test_... or sk_live_... + STRIPE_WEBHOOK_SECRET whsec_... of the endpoint + STRIPE_PRICE_MONTH price_... of the monthly price + STRIPE_PRICE_YEAR price_... of the yearly price + +Keep the keys out of git: put them in the environment file of the service. + +## Data + + data/accounts.json accounts: email, bcrypt hash, token hashes, + Stripe customer and subscription state + data/files/<account>/<sha256> the last 50 versions of each bookmark file + data/files/<account>/HEAD name of the current version + +To back up, copy the directory. + +## Test + + go vet ./... && go test ./... + +The merge has property tests (with [rapid](https://github.com/flyingmutant/rapid)). + +## License + +AGPL-3.0. If you run a changed version for other people, give them its +source code. + +If sbm is useful to you, you can support it on [Ko-fi](https://ko-fi.com/truex). diff --git a/contrib/nginx.conf b/contrib/nginx.conf new file mode 100644 index 0000000..812787f --- /dev/null +++ b/contrib/nginx.conf @@ -0,0 +1,14 @@ +# nginx site for sbm-sync. TLS: certbot --nginx -d sbm.example.org +server { + listen 80; + listen [::]:80; + server_name sbm.example.org; + + client_max_body_size 5m; + + location / { + proxy_pass http://127.0.0.1:8750; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } +} diff --git a/contrib/sbm-sync.service b/contrib/sbm-sync.service new file mode 100644 index 0000000..072044a --- /dev/null +++ b/contrib/sbm-sync.service @@ -0,0 +1,26 @@ +# systemd unit for sbm-sync. Install: +# useradd --system --home-dir /var/lib/sbm-sync --create-home sbm +# install -m 755 sbm-sync /usr/local/bin/ +# install -m 644 contrib/sbm-sync.service /etc/systemd/system/ +# install -m 640 -g sbm /dev/null /etc/sbm-sync.env # then edit it +# systemctl enable --now sbm-sync +[Unit] +Description=sbm Sync server +After=network.target + +[Service] +User=sbm +Group=sbm +EnvironmentFile=/etc/sbm-sync.env +Environment=SBM_DATA=/var/lib/sbm-sync +ExecStart=/usr/local/bin/sbm-sync +Restart=on-failure +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ReadWritePaths=/var/lib/sbm-sync + +[Install] +WantedBy=multi-user.target diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ff05613 --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module github.com/equwal/sbm-sync + +go 1.26.0 + +require golang.org/x/crypto v0.57.0 + +require pgregory.net/rapid v1.3.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fb30561 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +pgregory.net/rapid v1.3.0 h1:vBvO0VSqti75J1jjYqpgPNBLKMd1+gxa9fYo7vk/Exc= +pgregory.net/rapid v1.3.0/go.mod h1:dPlE4OBBxgXPqkP79flB6sJL1dx5azpI7HQ9MY9Z7uk= diff --git a/main.go b/main.go new file mode 100644 index 0000000..44f4e7f --- /dev/null +++ b/main.go @@ -0,0 +1,601 @@ +// sbm-sync keeps the sbm bookmark file of a user the same on each device. +// +// A device sends its copy of the file and the name of the version that it +// got last time. The server merges the changes of the device into its own +// copy, keeps the result and sends it back. Accounts are an email address +// and a password. Billing through Stripe is off unless STRIPE_SECRET_KEY is +// set. +package main + +import ( + _ "embed" + "encoding/json" + "errors" + "html/template" + "io" + "log" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" +) + +const maxFile = 4 << 20 // bytes in a bookmark file + +//go:embed pages.html +var pagesHTML string + +var pages = template.Must(template.New("").Parse(pagesHTML)) + +type server struct { + store *Store + stripe *Stripe // nil when billing is off + site string // public address, such as https://sbm.example.org + origin string // scheme and host of site + secure bool // site is https + trial time.Duration + since time.Time // start of billing: no trial ends before since + trial + contact string + prices map[string]string // plan ("month", "year"): Stripe price ID + labels map[string]string // plan: price as text + limit limiter +} + +func main() { + site := strings.TrimRight(env("SBM_URL", "http://localhost:8750"), "/") + u, err := url.Parse(site) + if err != nil || u.Host == "" { + log.Fatalf("SBM_URL: not an address: %q", site) + } + days, err := strconv.Atoi(env("SBM_TRIAL_DAYS", "30")) + if err != nil { + log.Fatalf("SBM_TRIAL_DAYS: %v", err) + } + var since time.Time + if v := os.Getenv("SBM_BILLING_START"); v != "" { + if since, err = time.Parse("2006-01-02", v); err != nil { + log.Fatalf("SBM_BILLING_START: %v", err) + } + } + store, err := openStore(env("SBM_DATA", "data")) + if err != nil { + log.Fatal(err) + } + s := &server{ + store: store, + site: site, + origin: u.Scheme + "://" + u.Host, + secure: u.Scheme == "https", + trial: time.Duration(days) * 24 * time.Hour, + since: since, + contact: os.Getenv("SBM_CONTACT"), + prices: map[string]string{"month": os.Getenv("STRIPE_PRICE_MONTH"), "year": os.Getenv("STRIPE_PRICE_YEAR")}, + labels: map[string]string{"month": "monthly", "year": "yearly"}, + } + if key := os.Getenv("STRIPE_SECRET_KEY"); key != "" { + for _, v := range []string{"STRIPE_WEBHOOK_SECRET", "STRIPE_PRICE_MONTH", "STRIPE_PRICE_YEAR"} { + if os.Getenv(v) == "" { + log.Fatalf("STRIPE_SECRET_KEY is set, so %s must be set too", v) + } + } + s.stripe = &Stripe{Key: key, Webhook: os.Getenv("STRIPE_WEBHOOK_SECRET"), + API: "https://api.stripe.com", Client: &http.Client{Timeout: 20 * time.Second}} + for plan, price := range s.prices { + if l, err := s.stripe.label(price); err != nil { + log.Printf("price of the %s plan: %v", plan, err) + } else { + s.labels[plan] = l + } + } + } + addr := env("SBM_ADDR", "127.0.0.1:8750") + log.Printf("sbm-sync on %s for %s, billing %v", addr, site, s.stripe != nil) + hs := &http.Server{ + Addr: addr, + Handler: s.routes(), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + IdleTimeout: 120 * time.Second, + MaxHeaderBytes: 16 << 10, + } + log.Fatal(hs.ListenAndServe()) +} + +func env(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} + +func (s *server) routes() http.Handler { + m := http.NewServeMux() + m.HandleFunc("GET /{$}", s.home) + m.HandleFunc("GET /privacy", s.privacy) + m.HandleFunc("GET /signup", s.form("signup")) + m.HandleFunc("POST /signup", s.signup) + m.HandleFunc("GET /login", s.form("login")) + m.HandleFunc("POST /login", s.login) + m.HandleFunc("POST /logout", s.logout) + m.HandleFunc("GET /account", s.account) + m.HandleFunc("POST /account/checkout", s.checkout) + m.HandleFunc("POST /account/portal", s.portal) + m.HandleFunc("POST /account/delete", s.remove) + m.HandleFunc("POST /stripe", s.webhook) + m.HandleFunc("POST /api/login", s.apiLogin) + m.HandleFunc("POST /api/logout", s.apiLogout) + m.HandleFunc("POST /api/sync", s.sync) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; "+ + "form-action 'self' https://checkout.stripe.com https://billing.stripe.com; "+ + "frame-ancestors 'none'; base-uri 'none'") + h.Set("Referrer-Policy", "same-origin") + h.Set("X-Content-Type-Options", "nosniff") + if s.secure { + h.Set("Strict-Transport-Security", "max-age=31536000") + } + m.ServeHTTP(w, r) + }) +} + +// ---- web pages ---- + +type page struct { + Title, Error, Email, State, URL, Contact string + Month, Year string + TrialDays int + Billing, CanSubscribe bool + Customer string +} + +func (s *server) page(title string) page { + return page{Title: title, URL: s.site, Contact: s.contact, Billing: s.stripe != nil, + Month: s.labels["month"], Year: s.labels["year"], TrialDays: int(s.trial.Hours() / 24)} +} + +func (s *server) render(w http.ResponseWriter, status int, name string, p page) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + if err := pages.ExecuteTemplate(w, name, p); err != nil { + log.Printf("page %s: %v", name, err) + } +} + +func (s *server) home(w http.ResponseWriter, r *http.Request) { + p := s.page("") + if a := s.user(r); a != nil { + p.Email = a.Email + } + s.render(w, http.StatusOK, "home", p) +} + +func (s *server) privacy(w http.ResponseWriter, r *http.Request) { + s.render(w, http.StatusOK, "privacy", s.page("Privacy")) +} + +func (s *server) form(name string) http.HandlerFunc { + title := map[string]string{"signup": "Create an account", "login": "Sign in"}[name] + return func(w http.ResponseWriter, r *http.Request) { + s.render(w, http.StatusOK, name, s.page(title)) + } +} + +// user gives the account of the sign-in cookie, or nil. +func (s *server) user(r *http.Request) *Account { + c, err := r.Cookie("sbm") + if err != nil { + return nil + } + return s.store.byTok(c.Value) +} + +// sameSite refuses a form that a page of another site sent. The cookie is +// SameSite=Lax too; this is the second guard. +func (s *server) sameSite(w http.ResponseWriter, r *http.Request) bool { + if o := r.Header.Get("Origin"); o != "" && o != s.origin { + http.Error(w, "this form must come from "+s.origin, http.StatusForbidden) + return false + } + return true +} + +func (s *server) setCookie(w http.ResponseWriter, token string, age int) { + http.SetCookie(w, &http.Cookie{Name: "sbm", Value: token, Path: "/", MaxAge: age, + HttpOnly: true, Secure: s.secure, SameSite: http.SameSiteLaxMode}) +} + +func (s *server) signup(w http.ResponseWriter, r *http.Request) { + if !s.sameSite(w, r) { + return + } + email := r.PostFormValue("email") + p := s.page("Create an account") + p.Email = email + if !s.limit.allow("signup "+clientIP(r), 10, time.Hour) { + p.Error = "Too many new accounts from your address. Try again later." + s.render(w, http.StatusTooManyRequests, "signup", p) + return + } + a, err := s.store.signup(email, r.PostFormValue("password")) + if errors.Is(err, errTaken) || errors.Is(err, errEmail) || errors.Is(err, errPassword) { + p.Error = strings.ToUpper(err.Error()[:1]) + err.Error()[1:] + "." + s.render(w, http.StatusBadRequest, "signup", p) + return + } else if err != nil { + s.fail(w, err) + return + } + log.Printf("new account %s", a.ID) + s.startSession(w, r, a) +} + +func (s *server) login(w http.ResponseWriter, r *http.Request) { + if !s.sameSite(w, r) { + return + } + email := r.PostFormValue("email") + p := s.page("Sign in") + p.Email = email + if !s.limit.allow("login "+clientIP(r), 20, 15*time.Minute) { + p.Error = "Too many attempts. Try again later." + s.render(w, http.StatusTooManyRequests, "login", p) + return + } + a, err := s.store.check(email, r.PostFormValue("password")) + if err != nil { + p.Error = "Wrong email or password." + s.render(w, http.StatusUnauthorized, "login", p) + return + } + s.startSession(w, r, a) +} + +func (s *server) startSession(w http.ResponseWriter, r *http.Request, a *Account) { + token, err := s.store.signIn(a) + if err != nil { + s.fail(w, err) + return + } + s.setCookie(w, token, 365*24*3600) + http.Redirect(w, r, "/account", http.StatusSeeOther) +} + +func (s *server) logout(w http.ResponseWriter, r *http.Request) { + if !s.sameSite(w, r) { + return + } + if c, err := r.Cookie("sbm"); err == nil { + if err := s.store.signOut(c.Value); err != nil { + s.fail(w, err) + return + } + } + s.setCookie(w, "", -1) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func paid(status string) bool { + return status == "active" || status == "trialing" || status == "past_due" +} + +// active tells if sync works for the account: always without billing, else +// during the free trial or with a subscription. +func (s *server) active(a Account) bool { + return s.stripe == nil || paid(a.Status) || s.trialLeft(a) > 0 +} + +// trialLeft gives the time until the free trial ends. The trial starts at +// sign-up, or when billing starts, if that is later: accounts from before +// billing get the full trial too. +func (s *server) trialLeft(a Account) time.Duration { + start := a.Created + if s.since.After(start) { + start = s.since + } + return s.trial - time.Since(start) +} + +func (s *server) account(w http.ResponseWriter, r *http.Request) { + u := s.user(r) + if u == nil { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + s.showAccount(w, http.StatusOK, s.store.view(u), "") +} + +func (s *server) showAccount(w http.ResponseWriter, status int, a Account, problem string) { + p := s.page("Your account") + p.Email, p.Error, p.Customer = a.Email, problem, a.Customer + left := s.trialLeft(a) + switch { + case s.stripe == nil: + p.State = "Sync is on." + case a.Status == "past_due": + p.State = "Your last payment failed. Update your card in Manage billing." + case paid(a.Status): + p.State = "Your subscription is active." + case left > 0: + days := int(left.Hours()/24) + 1 + p.State = "Free trial: " + strconv.Itoa(days) + " days left." + if days == 1 { + p.State = "Free trial: 1 day left." + } + default: + p.State = "Your free trial has ended. Sync is paused until you subscribe." + } + p.CanSubscribe = s.stripe != nil && !paid(a.Status) + s.render(w, status, "account", p) +} + +func (s *server) checkout(w http.ResponseWriter, r *http.Request) { + u := s.user(r) + if !s.sameSite(w, r) { + return + } + if u == nil || s.stripe == nil { + http.Redirect(w, r, "/account", http.StatusSeeOther) + return + } + price := s.prices[r.PostFormValue("plan")] + if price == "" { + http.Error(w, "no such plan", http.StatusBadRequest) + return + } + to, err := s.stripe.checkout(s.store.view(u), price, s.site) + if err != nil { + log.Printf("checkout for %s: %v", u.ID, err) + s.showAccount(w, http.StatusBadGateway, s.store.view(u), "Stripe did not answer. Try again later.") + return + } + http.Redirect(w, r, to, http.StatusSeeOther) +} + +func (s *server) portal(w http.ResponseWriter, r *http.Request) { + u := s.user(r) + if !s.sameSite(w, r) { + return + } + if u == nil || s.stripe == nil { + http.Redirect(w, r, "/account", http.StatusSeeOther) + return + } + a := s.store.view(u) + if a.Customer == "" { + http.Redirect(w, r, "/account", http.StatusSeeOther) + return + } + to, err := s.stripe.portal(a.Customer, s.site) + if err != nil { + log.Printf("portal for %s: %v", u.ID, err) + s.showAccount(w, http.StatusBadGateway, a, "Stripe did not answer. Try again later.") + return + } + http.Redirect(w, r, to, http.StatusSeeOther) +} + +func (s *server) remove(w http.ResponseWriter, r *http.Request) { + u := s.user(r) + if !s.sameSite(w, r) { + return + } + if u == nil { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + a := s.store.view(u) + if _, err := s.store.check(a.Email, r.PostFormValue("password")); err != nil { + s.showAccount(w, http.StatusUnauthorized, a, "Wrong password. The account is not deleted.") + return + } + // End the subscription first: a deleted account must not pay. + if a.Customer != "" && s.stripe != nil { + if err := s.stripe.deleteCustomer(a.Customer); err != nil { + log.Printf("delete customer of %s: %v", a.ID, err) + s.showAccount(w, http.StatusBadGateway, a, "Stripe did not answer, so the account is not deleted. Try again later.") + return + } + } + if err := s.store.remove(u); err != nil { + s.fail(w, err) + return + } + log.Printf("deleted account %s", a.ID) + s.setCookie(w, "", -1) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +// webhook takes the events of Stripe that change a subscription. +func (s *server) webhook(w http.ResponseWriter, r *http.Request) { + if s.stripe == nil { + http.NotFound(w, r) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + http.Error(w, "cannot read the event", http.StatusBadRequest) + return + } + if err := verify(body, r.Header.Get("Stripe-Signature"), s.stripe.Webhook, time.Now()); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var ev struct { + Type string `json:"type"` + Created int64 `json:"created"` + Data struct { + Object struct { + Customer string `json:"customer"` + Reference string `json:"client_reference_id"` + Status string `json:"status"` + Metadata map[string]string `json:"metadata"` + } `json:"object"` + } `json:"data"` + } + if err := json.Unmarshal(body, &ev); err != nil { + http.Error(w, "cannot read the event", http.StatusBadRequest) + return + } + o := ev.Data.Object + switch ev.Type { + case "checkout.session.completed": + if a := s.store.byID(o.Reference); a != nil && o.Customer != "" { + err = s.store.setCustomer(a, o.Customer) + } + case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted": + a := s.store.byCustomer(o.Customer) + if a == nil { + if a = s.store.byID(o.Metadata["account"]); a != nil { + err = s.store.setCustomer(a, o.Customer) + } + } + if a != nil && err == nil { + status := o.Status + if ev.Type == "customer.subscription.deleted" { + status = "canceled" + } + err = s.store.setStatus(a, status, ev.Created) + log.Printf("account %s: subscription %s", a.ID, status) + } + } + if err != nil { + s.fail(w, err) // Stripe sends the event again later + return + } + w.WriteHeader(http.StatusOK) +} + +// ---- API for bm-sync, the app and the add-on ---- + +// apiUser gives the account of the "Authorization: Bearer <token>" header. +func (s *server) apiUser(r *http.Request) *Account { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok { + return nil + } + return s.store.byTok(strings.TrimSpace(token)) +} + +// apiLogin takes the form fields email and password and gives a token. +func (s *server) apiLogin(w http.ResponseWriter, r *http.Request) { + if !s.limit.allow("login "+clientIP(r), 20, 15*time.Minute) { + http.Error(w, "too many attempts: try again later", http.StatusTooManyRequests) + return + } + a, err := s.store.check(r.PostFormValue("email"), r.PostFormValue("password")) + if err != nil { + http.Error(w, "wrong email or password", http.StatusUnauthorized) + return + } + token, err := s.store.signIn(a) + if err != nil { + s.fail(w, err) + return + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + io.WriteString(w, token+"\n") +} + +func (s *server) apiLogout(w http.ResponseWriter, r *http.Request) { + token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if err := s.store.signOut(strings.TrimSpace(token)); err != nil { + s.fail(w, err) + return + } + w.WriteHeader(http.StatusNoContent) +} + +// sync takes the bookmark file of a device as the body, and the version that +// the device got last time as ?base=. It gives the merged file, with the +// name of its version in the Sbm-Version header. The device writes the file +// and sends that name as base next time. +func (s *server) sync(w http.ResponseWriter, r *http.Request) { + u := s.apiUser(r) + if u == nil { + http.Error(w, "not signed in: sign in again", http.StatusUnauthorized) + return + } + if !s.active(s.store.view(u)) { + http.Error(w, "sbm Sync is paused for this account: see "+s.site+"/account", http.StatusPaymentRequired) + return + } + base := r.URL.Query().Get("base") + if base != "" && !hashName.MatchString(base) { + http.Error(w, "base is not a version name", http.StatusBadRequest) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxFile)) + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + http.Error(w, "the bookmark file is too large", http.StatusRequestEntityTooLarge) + return + } else if err != nil { + http.Error(w, "cannot read the bookmark file", http.StatusBadRequest) + return + } + text, version, err := s.store.sync(u, base, string(body)) + if errors.Is(err, errGone) { + http.Error(w, "not signed in: sign in again", http.StatusUnauthorized) + return + } else if err != nil { + s.fail(w, err) + return + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Header().Set("Sbm-Version", version) + w.Header().Set("Access-Control-Expose-Headers", "Sbm-Version") + io.WriteString(w, text) +} + +func (s *server) fail(w http.ResponseWriter, err error) { + log.Print(err) + http.Error(w, "server error: try again later", http.StatusInternalServerError) +} + +// clientIP gives the address of the client. Behind a proxy on the same +// machine, the proxy gives it in X-Real-IP. +func clientIP(r *http.Request) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + if real := r.Header.Get("X-Real-IP"); real != "" { + return real + } + } + return host +} + +// limiter counts attempts for each key in a sliding window. +type limiter struct { + mu sync.Mutex + hits map[string][]time.Time +} + +func (l *limiter) allow(key string, n int, per time.Duration) bool { + l.mu.Lock() + defer l.mu.Unlock() + now := time.Now() + if l.hits == nil || len(l.hits) > 10000 { + l.hits = map[string][]time.Time{} + } + recent := l.hits[key][:0] + for _, t := range l.hits[key] { + if now.Sub(t) < per { + recent = append(recent, t) + } + } + if len(recent) >= n { + l.hits[key] = recent + return false + } + l.hits[key] = append(recent, now) + return true +} diff --git a/merge.go b/merge.go new file mode 100644 index 0000000..2ecc979 --- /dev/null +++ b/merge.go @@ -0,0 +1,123 @@ +package main + +import ( + "regexp" + "strings" +) + +var scheme = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*://`) + +// norm gives the form of a URL that bm uses to find duplicates: two URLs are +// the same bookmark when they differ only in scheme, a leading "www.", +// trailing slashes or the case of the host. +func norm(u string) string { + u = scheme.ReplaceAllString(u, "") + host, rest := u, "" + if i := strings.IndexByte(u, '/'); i >= 0 { + host, rest = u[:i], u[i:] + } + host = strings.TrimPrefix(strings.ToLower(host), "www.") + return host + strings.TrimRight(rest, "/") +} + +// key gives the bookmark that a line holds: the normal form of its URL, the +// first field. Comments and empty lines hold no bookmark and give "". +func key(line string) string { + if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "#") { + return "" + } + u, _, _ := strings.Cut(line, "\t") + return norm(u) +} + +// lines splits a file into lines without their ends. CRLF counts as LF. +func lines(text string) []string { + text = strings.ReplaceAll(text, "\r\n", "\n") + if text == "" { + return nil + } + return strings.Split(strings.TrimSuffix(text, "\n"), "\n") +} + +// join is the reverse of lines: each line ends with LF. +func join(ls []string) string { + if len(ls) == 0 { + return "" + } + return strings.Join(ls, "\n") + "\n" +} + +func set(ls []string) map[string]bool { + m := make(map[string]bool, len(ls)) + for _, l := range ls { + m[l] = true + } + return m +} + +// merge combines two versions of a bookmark file that both come from base: +// local, which a device sends, and remote, which the server holds. +// +// The result is remote with the changes that local made since base. A line +// that local removed goes. A line that local added comes in: at the end, +// where bm adds bookmarks, or in the place of the remote line for the same +// bookmark, so that an edit on the device wins. Lines are compared whole. +// When base is unknown, pass "": nothing is removed, and the result is the +// union of both files. +func merge(base, local, remote string) string { + b := set(lines(base)) + l := lines(local) + inLocal := set(l) + r := lines(remote) + inRemote := set(r) + + var added []string + first := map[string]int{} // key of an added line: its index in added + for _, x := range l { + if b[x] { + continue + } + if k := key(x); k != "" { + if _, ok := first[k]; !ok { + first[k] = len(added) + } + } + added = append(added, x) + } + used := make([]bool, len(added)) + + // replacement gives the added line that takes the place of x, if any. + replacement := func(x string) (string, bool) { + k := key(x) + if k == "" { + return "", false + } + i, ok := first[k] + if !ok || used[i] || inRemote[added[i]] { + return "", false + } + used[i] = true + return added[i], true + } + + var out []string + for _, x := range r { + if inLocal[x] { + out = append(out, x) + continue + } + // Local does not have x: local removed or changed it since base, or + // x is new on the server. + if y, ok := replacement(x); ok { + out = append(out, y) + } else if !b[x] { + out = append(out, x) + } + } + for i, y := range added { + if !used[i] && !inRemote[y] { + out = append(out, y) + } + } + return join(out) +} diff --git a/merge_test.go b/merge_test.go new file mode 100644 index 0000000..e109a6e --- /dev/null +++ b/merge_test.go @@ -0,0 +1,192 @@ +package main + +import ( + "slices" + "strings" + "testing" + + "pgregory.net/rapid" +) + +// file draws a bookmark file from few URLs and descriptions, so that files +// share lines, and lines share bookmarks, as often as real files do. +func file(t *rapid.T, label string) string { + pool := []string{ + "https://suckless.org/\tsuckless\ttools", + "https://suckless.org\tsuckless software\ttools c", + "http://www.suckless.org\tsuckless", + "https://example.org/a\tA\t", + "https://example.org/a\tA, edited\tx", + "https://example.org/b\tB\t", + "https://jisho.org\tJisho: 日本語の辞書\tja", + "https://jisho.org\tJisho\t", + "# comment", + "", + } + ls := rapid.SliceOfN(rapid.SampledFrom(pool), 0, 8).Draw(t, label) + return join(ls) +} + +// unique draws a file without two equal lines. +func unique(t *rapid.T, label string) string { + ls := lines(file(t, label)) + var out []string + for _, l := range ls { + if !slices.Contains(out, l) { + out = append(out, l) + } + } + return join(out) +} + +func sorted(text string) []string { + ls := lines(text) + slices.Sort(ls) + return ls +} + +func TestNoLocalChangeGivesRemote(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, remote := file(t, "base"), file(t, "remote") + if got := merge(base, base, remote); got != join(lines(remote)) { + t.Fatalf("merge(base, base, remote) = %q, want %q", got, remote) + } + }) +} + +func TestNoRemoteChangeGivesLocal(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, local := unique(t, "base"), unique(t, "local") + if got := sorted(merge(base, local, base)); !slices.Equal(got, sorted(local)) { + t.Fatalf("merge(base, local, base) has lines %q, want %q", got, sorted(local)) + } + }) +} + +func TestMergeOfOneFileIsThatFile(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + f := file(t, "f") + if got := merge(f, f, f); got != join(lines(f)) { + t.Fatalf("merge(f, f, f) = %q", got) + } + }) +} + +func TestLocalAdditionsStay(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, local, remote := file(t, "base"), file(t, "local"), file(t, "remote") + got := set(lines(merge(base, local, remote))) + b := set(lines(base)) + for _, l := range lines(local) { + if !b[l] && !got[l] { + t.Fatalf("line %q that local added is lost", l) + } + } + }) +} + +func TestLocalRemovalsStay(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, local, remote := file(t, "base"), file(t, "local"), file(t, "remote") + got := set(lines(merge(base, local, remote))) + l := set(lines(local)) + for _, x := range lines(base) { + if !l[x] && got[x] { + t.Fatalf("line %q that local removed came back", x) + } + } + }) +} + +func TestRemoteAdditionsStayWithoutConflict(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, local, remote := file(t, "base"), file(t, "local"), file(t, "remote") + got := set(lines(merge(base, local, remote))) + b := set(lines(base)) + changed := map[string]bool{} // bookmarks that local added or edited + for _, l := range lines(local) { + if !b[l] { + changed[key(l)] = true + } + } + for _, x := range lines(remote) { + if !b[x] && !changed[key(x)] && !got[x] { + t.Fatalf("line %q that the server added is lost", x) + } + } + }) +} + +func TestNoNewLines(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base, local, remote := file(t, "base"), file(t, "local"), file(t, "remote") + have := set(append(lines(local), lines(remote)...)) + for _, x := range lines(merge(base, local, remote)) { + if !have[x] { + t.Fatalf("line %q comes from neither side", x) + } + } + }) +} + +// Two devices that sync in turn end with the same file. +func TestDevicesConverge(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + start := file(t, "start") + a, b := file(t, "device a"), file(t, "device b") + m1 := merge(start, a, start) // a syncs: a now has m1 + m2 := merge(start, b, m1) // b syncs: b now has m2 + m3 := merge(m1, m1, m2) // a syncs again + if m3 != m2 { + t.Fatalf("device a has %q, device b has %q", m3, m2) + } + }) +} + +func TestNorm(t *testing.T) { + same := []string{"https://suckless.org/", "http://suckless.org", "suckless.org//", "https://WWW.Suckless.ORG"} + for _, u := range same { + if norm(u) != "suckless.org" { + t.Errorf("norm(%q) = %q, want suckless.org", u, norm(u)) + } + } + if norm("https://example.org/A") == norm("https://example.org/a") { + t.Error("the case of the path must count") + } +} + +func TestMergeExamples(t *testing.T) { + cases := []struct{ name, base, local, remote, want string }{ + {"first device", "", "a\t1\n", "", "a\t1\n"}, + {"second device: union", "", "b\t2\n", "a\t1\n", "a\t1\nb\t2\n"}, + {"local add goes to the end", "a\t1\n", "a\t1\nc\t3\n", "a\t1\nb\t2\n", "a\t1\nb\t2\nc\t3\n"}, + {"local delete", "a\t1\nb\t2\n", "b\t2\n", "a\t1\nb\t2\nc\t3\n", "b\t2\nc\t3\n"}, + {"local edit keeps its place", "a\t1\nb\t2\n", "a\tone\nb\t2\n", "a\t1\nb\t2\n", "a\tone\nb\t2\n"}, + {"both edit: the device wins", "a\t1\n", "a\tlocal\n", "a\tremote\n", "a\tlocal\n"}, + {"local delete, remote edit: the edit stays", "a\t1\n", "", "a\tremote\n", "a\tremote\n"}, + {"CRLF", "", "a\t1\r\nb\t2\r\n", "", "a\t1\nb\t2\n"}, + {"no final newline", "", "a\t1", "", "a\t1\n"}, + {"a file of one empty line", "", "\n", "", "\n"}, + {"an empty line from the server", "a\n", "", "a\n\n", "\n"}, + {"same page, other form", "", "https://www.x.org/\tx\n", "http://x.org\tx\n", "https://www.x.org/\tx\n"}, + } + for _, c := range cases { + if got := merge(c.base, c.local, c.remote); got != c.want { + t.Errorf("%s: got %q, want %q", c.name, got, c.want) + } + } +} + +func TestKey(t *testing.T) { + for _, l := range []string{"", " ", "# https://x.org"} { + if key(l) != "" { + t.Errorf("key(%q) = %q, want none", l, key(l)) + } + } + if k := key("https://x.org/a/\tdesc\ttag"); k != "x.org/a" { + t.Errorf("key = %q", k) + } + if !strings.Contains(key("https://jisho.org/word/日本"), "日本") { + t.Error("key loses non-ASCII text") + } +} diff --git a/pages.html b/pages.html new file mode 100644 index 0000000..04ee27e --- /dev/null +++ b/pages.html @@ -0,0 +1,126 @@ +{{define "head"}}<!doctype html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>{{if .Title}}{{.Title}} · {{end}}sbm Sync</title> +<style> +body { max-width: 36em; margin: 2em auto; padding: 0 1em; font: 16px/1.5 sans-serif; color: #222; background: #fff; } +a { color: #005577; } +h1 { font-size: 1.5em; } h2 { font-size: 1.15em; margin-top: 2em; } +label { display: block; } +input { display: block; width: 100%; box-sizing: border-box; margin: .2em 0 1em; padding: .4em; font: inherit; } +button { font: inherit; padding: .4em 1em; margin: .2em .5em .2em 0; } +.error { color: #a00; } .note, footer { color: #555; } footer { margin-top: 3em; font-size: .9em; } +@media (prefers-color-scheme: dark) { + body { background: #111; color: #ddd; } a { color: #4fb3d9; } .note, footer { color: #999; } .error { color: #f77; } +} +</style> +</head> +<body> +<header><a href="/"><b>sbm Sync</b></a></header> +{{end}} + +{{define "foot"}} +<footer> +<a href="https://github.com/equwal/sbm-sync">Source code</a> · +<a href="/privacy">Privacy</a> · +<a href="https://ko-fi.com/truex">Support sbm on Ko-fi</a> +</footer> +</body> +</html> +{{end}} + +{{define "home"}}{{template "head" .}} +<h1>Your bookmarks, the same everywhere</h1> +<p><a href="https://github.com/equwal/sbm">sbm</a> keeps your bookmarks in one plain +text file. sbm Sync keeps that file the same on each of your devices: bm on +your computers, the sbm app for Android, and the sbm add-on for Firefox and +Chrome.</p> +{{if .Billing}}<p>Free for {{.TrialDays}} days. Then {{.Year}} or {{.Month}}. Cancel at any time.</p>{{end}} +<p>{{if .Email}}<a href="/account">Your account</a>{{else}}<a href="/signup">Create an account</a> or <a href="/login">sign in</a>.{{end}}</p> +<p class="note">sbm Sync is free software under the AGPL-3.0. You can +<a href="https://github.com/equwal/sbm-sync">run your own server</a>.</p> +{{template "foot" .}}{{end}} + +{{define "signup"}}{{template "head" .}} +<h1>Create an account</h1> +{{with .Error}}<p class="error">{{.}}</p>{{end}} +<form method="post" action="/signup"> +<label>Email <input type="email" name="email" value="{{.Email}}" required autocomplete="email"></label> +<label>Password, 8 characters or more <input type="password" name="password" minlength="8" maxlength="72" required autocomplete="new-password"></label> +<button>Create account</button> +</form> +<p class="note">See the <a href="/privacy">privacy policy</a>. You have an account? <a href="/login">Sign in</a>.</p> +{{template "foot" .}}{{end}} + +{{define "login"}}{{template "head" .}} +<h1>Sign in</h1> +{{with .Error}}<p class="error">{{.}}</p>{{end}} +<form method="post" action="/login"> +<label>Email <input type="email" name="email" value="{{.Email}}" required autocomplete="email"></label> +<label>Password <input type="password" name="password" required autocomplete="current-password"></label> +<button>Sign in</button> +</form> +<p class="note">No account yet? <a href="/signup">Create one</a>.</p> +{{template "foot" .}}{{end}} + +{{define "account"}}{{template "head" .}} +<h1>Your account</h1> +<p>Signed in as {{.Email}}.</p> +{{with .Error}}<p class="error">{{.}}</p>{{end}} +<p><b>{{.State}}</b></p> +{{if .CanSubscribe}}<form method="post" action="/account/checkout"> +<button name="plan" value="year">Subscribe: {{.Year}}</button> +<button name="plan" value="month">Subscribe: {{.Month}}</button> +</form>{{end}} +{{if .Customer}}<form method="post" action="/account/portal"><button>Manage billing</button></form>{{end}} + +<h2>Connect your devices</h2> +<p>Sign in with this email and password on each device:</p> +<ul> +<li>bm on a computer: run <code>bm-sync login</code></li> +<li>the sbm app for Android: menu, Sign in to sync</li> +<li>the sbm add-on for Firefox or Chrome: its options page</li> +</ul> +<p>Server: <code>{{.URL}}</code></p> +<form method="post" action="/logout"><button>Sign out</button></form> + +<h2>Delete your account</h2> +<form method="post" action="/account/delete"> +<p>This deletes your account and the copy of your bookmarks on this server at +once.{{if .Customer}} It also ends your subscription.{{end}} Your devices keep +their bookmark files.</p> +<label>Password <input type="password" name="password" required autocomplete="current-password"></label> +<button>Delete my account</button> +</form> +{{template "foot" .}}{{end}} + +{{define "privacy"}}{{template "head" .}} +<h1>Privacy</h1> +<p>This policy is for this sbm Sync server, the sbm app for Android and the +sbm add-on for Firefox and Chrome.</p> +<h2>What the server keeps, and why</h2> +<ul> +<li>Your email address and a bcrypt hash of your password, never the password itself: to sign you in.</li> +<li>Your bookmark file, the last 50 versions that your devices sent: to sync your devices.</li> +<li>A hash of the sign-in token of each device: to know your devices.</li> +<li>When you subscribe: your Stripe customer ID and the state of your subscription: to bill you.</li> +</ul> +<p>The server does not sell or share this data, and does not use it for ads. +There are no analytics and no trackers. The only cookie keeps you signed in.</p> +<p>Data goes to and from the server over HTTPS. On the server it is not +encrypted: the operator of the server can read it.</p> +<h2>Payments</h2> +<p>Stripe takes the payments. This server never sees your card. See the +<a href="https://stripe.com/privacy">Stripe privacy policy</a>.</p> +<h2>Delete your data</h2> +<p>Delete your account on the <a href="/account">account page</a>. The +server deletes the account and all versions of your bookmark file at once.</p> +<h2>The app and the add-on</h2> +<p>They keep your bookmarks on your device. They send them only to the sync +server that you sign in to, and only after you sign in. Without an account, +no data leaves your device.</p> +{{with .Contact}}<h2>Contact</h2> +<p><a href="mailto:{{.}}">{{.}}</a></p>{{end}} +{{template "foot" .}}{{end}} diff --git a/server_test.go b/server_test.go new file mode 100644 index 0000000..08b35f9 --- /dev/null +++ b/server_test.go @@ -0,0 +1,457 @@ +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// fakeStripe records the calls to the Stripe API and answers them. +type fakeStripe struct { + mu sync.Mutex + calls []string // "METHOD /path form" +} + +func (f *fakeStripe) ServeHTTP(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + f.mu.Lock() + f.calls = append(f.calls, r.Method+" "+r.URL.Path+" "+r.PostForm.Encode()) + f.mu.Unlock() + switch { + case r.URL.Path == "/v1/checkout/sessions": + io.WriteString(w, `{"url": "https://checkout.stripe.test/s1"}`) + case r.URL.Path == "/v1/billing_portal/sessions": + io.WriteString(w, `{"url": "https://billing.stripe.test/p1"}`) + case strings.HasPrefix(r.URL.Path, "/v1/customers/"): + io.WriteString(w, `{"deleted": true}`) + default: + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, `{"error": {"message": "no such thing"}}`) + } +} + +func (f *fakeStripe) called(prefix string) string { + f.mu.Lock() + defer f.mu.Unlock() + for _, c := range f.calls { + if strings.HasPrefix(c, prefix) { + return c + } + } + return "" +} + +type harness struct { + t *testing.T + s *server + web *httptest.Server + stripe *fakeStripe +} + +func newEnv(t *testing.T, billing bool) *harness { + store, err := openStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + s := &server{store: store, trial: 30 * 24 * time.Hour, + prices: map[string]string{"month": "price_m", "year": "price_y"}, + labels: map[string]string{"month": "$3 a month", "year": "$30 a year"}} + e := &harness{t: t, s: s} + if billing { + e.stripe = &fakeStripe{} + api := httptest.NewServer(e.stripe) + t.Cleanup(api.Close) + s.stripe = &Stripe{Key: "sk_test_x", Webhook: "whsec_test", API: api.URL, Client: api.Client()} + } + e.web = httptest.NewServer(s.routes()) + t.Cleanup(e.web.Close) + s.site, s.origin = e.web.URL, e.web.URL + return e +} + +// browser gives a client that keeps cookies and does not follow redirects. +func (e *harness) browser() *http.Client { + jar, _ := cookiejar.New(nil) + return &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }} +} + +func (e *harness) post(c *http.Client, path string, form url.Values) *http.Response { + req, _ := http.NewRequest("POST", e.web.URL+path, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Origin", e.web.URL) + resp, err := c.Do(req) + if err != nil { + e.t.Fatal(err) + } + return resp +} + +func (e *harness) signup(email string) *http.Client { + c := e.browser() + resp := e.post(c, "/signup", url.Values{"email": {email}, "password": {"password1"}}) + if resp.StatusCode != http.StatusSeeOther { + e.t.Fatalf("signup: %s", resp.Status) + } + return c +} + +func (e *harness) token(email string) string { + resp := e.post(http.DefaultClient, "/api/login", url.Values{"email": {email}, "password": {"password1"}}) + b, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + e.t.Fatalf("api login: %s %s", resp.Status, b) + } + return strings.TrimSpace(string(b)) +} + +// sync sends a file as a device does and gives the answer. +func (e *harness) sync(token, base, text string) (int, string, string) { + req, _ := http.NewRequest("POST", e.web.URL+"/api/sync?base="+base, strings.NewReader(text)) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + e.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b), resp.Header.Get("Sbm-Version") +} + +func (e *harness) body(c *http.Client, path string) string { + resp, err := c.Get(e.web.URL + path) + if err != nil { + e.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return string(b) +} + +func TestTwoDevicesSync(t *testing.T) { + e := newEnv(t, false) + e.signup("Me@Example.org") + a, b := e.token("me@example.org"), e.token(" me@example.org") + + code, text, va := e.sync(a, "", "https://a.org\tA\t\n") + if code != 200 || text != "https://a.org\tA\t\n" || len(va) != 64 { + t.Fatalf("first sync: %d %q %q", code, text, va) + } + _, text, vb := e.sync(b, "", "https://b.org\tB\t\n") + if text != "https://a.org\tA\t\nhttps://b.org\tB\t\n" { + t.Fatalf("second device: %q", text) + } + // Device a removes its bookmark and adds another. + _, text, _ = e.sync(a, va, "https://c.org\tC\t\n") + if text != "https://b.org\tB\t\nhttps://c.org\tC\t\n" { + t.Fatalf("remove and add: %q", text) + } + // Device b has no changes and gets the file of device a. + _, text, _ = e.sync(b, vb, "https://a.org\tA\t\nhttps://b.org\tB\t\n") + if text != "https://b.org\tB\t\nhttps://c.org\tC\t\n" { + t.Fatalf("pull: %q", text) + } +} + +func TestSyncRefusals(t *testing.T) { + e := newEnv(t, false) + e.signup("me@example.org") + tok := e.token("me@example.org") + if code, _, _ := e.sync("wrong", "", "x\n"); code != http.StatusUnauthorized { + t.Errorf("bad token: %d", code) + } + if code, _, _ := e.sync(tok, "../../accounts.json", "x\n"); code != http.StatusBadRequest { + t.Errorf("bad base: %d", code) + } + if code, _, _ := e.sync(tok, "", strings.Repeat("x", maxFile+1)); code != http.StatusRequestEntityTooLarge { + t.Errorf("large file: %d", code) + } + // An unknown base is no error: nothing is removed. + if code, text, _ := e.sync(tok, strings.Repeat("0", 64), "a\n"); code != 200 || text != "a\n" { + t.Errorf("unknown base: %d %q", code, text) + } +} + +func TestSignupAndLogin(t *testing.T) { + e := newEnv(t, false) + c := e.signup("me@example.org") + if !strings.Contains(e.body(c, "/account"), "Signed in as me@example.org") { + t.Error("the account page does not show the account") + } + if resp := e.post(e.browser(), "/signup", url.Values{"email": {"ME@example.org"}, "password": {"password2"}}); resp.StatusCode != http.StatusBadRequest { + t.Errorf("second signup with the same email: %s", resp.Status) + } + for _, bad := range []url.Values{ + {"email": {"not an address"}, "password": {"password1"}}, + {"email": {"Me <x@example.org>"}, "password": {"password1"}}, + {"email": {"y@example.org"}, "password": {"short"}}, + {"email": {"y@example.org"}, "password": {strings.Repeat("p", 73)}}, + } { + if resp := e.post(e.browser(), "/signup", bad); resp.StatusCode != http.StatusBadRequest { + t.Errorf("signup %v: %s", bad, resp.Status) + } + } + if resp := e.post(e.browser(), "/login", url.Values{"email": {"me@example.org"}, "password": {"wrong-password"}}); resp.StatusCode != http.StatusUnauthorized { + t.Errorf("wrong password: %s", resp.Status) + } + e.post(c, "/logout", nil) + if strings.Contains(e.body(c, "/"), "Your account") { + t.Error("still signed in after sign out") + } +} + +func TestOtherSiteCannotPostForms(t *testing.T) { + e := newEnv(t, false) + c := e.signup("me@example.org") + req, _ := http.NewRequest("POST", e.web.URL+"/account/delete", strings.NewReader("password=password1")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Origin", "https://evil.example") + resp, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusForbidden { + t.Errorf("post from another site: %s", resp.Status) + } + if e.s.store.byTok(e.token("me@example.org")) == nil { + t.Error("the account is gone") + } +} + +func TestLoginLimit(t *testing.T) { + e := newEnv(t, false) + e.signup("me@example.org") + var last int + for range 21 { + resp := e.post(http.DefaultClient, "/api/login", url.Values{"email": {"me@example.org"}, "password": {"guess"}}) + last = resp.StatusCode + } + if last != http.StatusTooManyRequests { + t.Errorf("attempt 21: %d", last) + } +} + +func TestDeleteAccount(t *testing.T) { + e := newEnv(t, true) + c := e.signup("me@example.org") + tok := e.token("me@example.org") + e.sync(tok, "", "a\n") + a := e.s.store.byTok(tok) + e.s.store.setCustomer(a, "cus_1") + + if resp := e.post(c, "/account/delete", url.Values{"password": {"wrong-password"}}); resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("delete with a wrong password: %s", resp.Status) + } + if resp := e.post(c, "/account/delete", url.Values{"password": {"password1"}}); resp.StatusCode != http.StatusSeeOther { + t.Fatalf("delete: %s", resp.Status) + } + if e.stripe.called("DELETE /v1/customers/cus_1") == "" { + t.Error("the Stripe customer is not deleted") + } + if code, _, _ := e.sync(tok, "", "a\n"); code != http.StatusUnauthorized { + t.Errorf("sync after delete: %d", code) + } + if _, err := os.Stat(filepath.Join(e.s.store.dir, "files", a.ID)); !os.IsNotExist(err) { + t.Errorf("the files of the account are still there: %v", err) + } +} + +func TestTrialAndSubscription(t *testing.T) { + e := newEnv(t, true) + c := e.signup("me@example.org") + tok := e.token("me@example.org") + if code, _, _ := e.sync(tok, "", "a\n"); code != 200 { + t.Fatalf("sync in the trial: %d", code) + } + if !strings.Contains(e.body(c, "/account"), "Free trial: 30 days left.") { + t.Error("the account page does not show the trial") + } + a := e.s.store.byTok(tok) + a.Created = time.Now().Add(-31 * 24 * time.Hour) + if code, text, _ := e.sync(tok, "", "a\n"); code != http.StatusPaymentRequired { + t.Fatalf("sync after the trial: %d %q", code, text) + } + + resp := e.post(c, "/account/checkout", url.Values{"plan": {"year"}}) + if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "https://checkout.stripe.test/s1" { + t.Fatalf("checkout: %s to %q", resp.Status, resp.Header.Get("Location")) + } + call := e.stripe.called("POST /v1/checkout/sessions") + for _, want := range []string{"client_reference_id=" + a.ID, "price%5D=price_y", "customer_email=me%40example.org", "mode=subscription"} { + if !strings.Contains(call, want) { + t.Errorf("checkout call %q lacks %q", call, want) + } + } + + now := time.Now().Unix() + e.event(now, "checkout.session.completed", fmt.Sprintf(`{"customer":"cus_9","client_reference_id":%q}`, a.ID)) + e.event(now+2, "customer.subscription.updated", `{"customer":"cus_9","status":"active"}`) + e.event(now+1, "customer.subscription.created", `{"customer":"cus_9","status":"incomplete"}`) // late + if code, _, _ := e.sync(tok, "", "a\n"); code != 200 { + t.Fatalf("sync with a subscription: %d", code) + } + if page := e.body(c, "/account"); !strings.Contains(page, "Your subscription is active.") || strings.Contains(page, "Subscribe:") { + t.Error("the account page does not show the subscription") + } + if resp := e.post(c, "/account/portal", nil); resp.Header.Get("Location") != "https://billing.stripe.test/p1" { + t.Errorf("portal: %s", resp.Status) + } + e.event(now+3, "customer.subscription.deleted", `{"customer":"cus_9","status":"canceled"}`) + if code, _, _ := e.sync(tok, "", "a\n"); code != http.StatusPaymentRequired { + t.Errorf("sync after the end of the subscription: %d", code) + } +} + +func TestTrialStartsWithBilling(t *testing.T) { + e := newEnv(t, true) + e.signup("me@example.org") + tok := e.token("me@example.org") + a := e.s.store.byTok(tok) + a.Created = time.Now().Add(-100 * 24 * time.Hour) // from before billing + e.s.since = time.Now().Add(-10 * 24 * time.Hour) + if code, _, _ := e.sync(tok, "", "a\n"); code != 200 { + t.Errorf("sync 10 days after billing started: %d", code) + } + e.s.since = time.Now().Add(-31 * 24 * time.Hour) + if code, _, _ := e.sync(tok, "", "a\n"); code != http.StatusPaymentRequired { + t.Errorf("sync 31 days after billing started: %d", code) + } +} + +func TestSubscriptionFoundByMetadata(t *testing.T) { + e := newEnv(t, true) + e.signup("me@example.org") + a := e.s.store.byTok(e.token("me@example.org")) + e.event(time.Now().Unix(), "customer.subscription.created", + fmt.Sprintf(`{"customer":"cus_5","status":"active","metadata":{"account":%q}}`, a.ID)) + if v := e.s.store.view(a); v.Customer != "cus_5" || v.Status != "active" { + t.Errorf("account: customer %q, status %q", v.Customer, v.Status) + } +} + +// event sends a signed webhook event as Stripe does. +func (e *harness) event(created int64, typ, object string) { + body := fmt.Sprintf(`{"type":%q,"created":%d,"data":{"object":%s}}`, typ, created, object) + req, _ := http.NewRequest("POST", e.web.URL+"/stripe", strings.NewReader(body)) + req.Header.Set("Stripe-Signature", sign([]byte(body), "whsec_test", time.Now().Unix())) + resp, err := http.DefaultClient.Do(req) + if err != nil { + e.t.Fatal(err) + } + if resp.StatusCode != 200 { + e.t.Fatalf("event %s: %s", typ, resp.Status) + } +} + +func sign(body []byte, secret string, t int64) string { + mac := hmac.New(sha256.New, []byte(secret)) + fmt.Fprintf(mac, "%d.%s", t, body) + return fmt.Sprintf("t=%d,v1=%s", t, hex.EncodeToString(mac.Sum(nil))) +} + +func TestVerify(t *testing.T) { + body := []byte(`{"type":"x"}`) + now := time.Unix(1_800_000_000, 0) + good := sign(body, "whsec_a", now.Unix()) + if err := verify(body, good, "whsec_a", now); err != nil { + t.Errorf("good signature: %v", err) + } + if err := verify(body, "t=1,v1=00,"+strings.TrimPrefix(good, "t=1800000000,"), "whsec_a", now); err == nil { + t.Error("a signature for another time passes") + } + if err := verify(body, "v1=00,"+good, "whsec_a", now); err != nil { + t.Errorf("one good signature among more: %v", err) + } + for name, c := range map[string]struct { + body string + header string + secret string + now time.Time + }{ + "changed body": {`{"type":"y"}`, good, "whsec_a", now}, + "other secret": {string(body), good, "whsec_b", now}, + "old": {string(body), good, "whsec_a", now.Add(6 * time.Minute)}, + "no header": {string(body), "", "whsec_a", now}, + "no secret set": {string(body), good, "", now}, + } { + if err := verify([]byte(c.body), c.header, c.secret, c.now); err == nil { + t.Errorf("%s: passes", name) + } + } + e := newEnv(t, true) + req, _ := http.NewRequest("POST", e.web.URL+"/stripe", strings.NewReader(`{}`)) + req.Header.Set("Stripe-Signature", "t=1,v1=00") + if resp, _ := http.DefaultClient.Do(req); resp.StatusCode != http.StatusBadRequest { + t.Errorf("webhook with a bad signature: %s", resp.Status) + } +} + +func TestMoney(t *testing.T) { + for cents, want := range map[int64]string{300: "$3", 3000: "$30", 299: "$2.99", 5: "$0.05"} { + if got := money(cents, "usd"); got != want { + t.Errorf("money(%d) = %q, want %q", cents, got, want) + } + } + if got := money(500, "eur"); got != "5 EUR" { + t.Errorf("euro: %q", got) + } +} + +func TestStoreSurvivesRestart(t *testing.T) { + dir := t.TempDir() + s, _ := openStore(dir) + a, err := s.signup("me@example.org", "password1") + if err != nil { + t.Fatal(err) + } + tok, _ := s.signIn(a) + s.sync(a, "", "a\n") + s2, err := openStore(dir) + if err != nil { + t.Fatal(err) + } + b := s2.byTok(tok) + if b == nil || b.Email != "me@example.org" { + t.Fatal("the account or its token is lost") + } + if text, _, _ := s2.sync(b, "", ""); text != "a\n" { + t.Errorf("the file is lost: %q", text) + } +} + +func TestOldVersionsGo(t *testing.T) { + s, _ := openStore(t.TempDir()) + a, _ := s.signup("me@example.org", "password1") + base := "" + for i := range maxVersions + 10 { + _, v, err := s.sync(a, base, fmt.Sprintf("line %d\n", i)) + if err != nil { + t.Fatal(err) + } + base = v + time.Sleep(2 * time.Millisecond) // distinct times of change + } + entries, _ := os.ReadDir(filepath.Join(s.dir, "files", a.ID)) + n := 0 + for _, e := range entries { + if hashName.MatchString(e.Name()) { + n++ + } + } + if n != maxVersions { + t.Errorf("%d versions kept, want %d", n, maxVersions) + } +} diff --git a/store.go b/store.go new file mode 100644 index 0000000..04fcd11 --- /dev/null +++ b/store.go @@ -0,0 +1,399 @@ +package main + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io/fs" + "net/mail" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + + "golang.org/x/crypto/bcrypt" +) + +const ( + maxTokens = 20 // sign-ins kept per account; the oldest goes first + maxVersions = 50 // versions of the bookmark file kept per account +) + +var ( + errTaken = errors.New("an account with this email exists already") + errEmail = errors.New("this is not an email address") + errPassword = errors.New("the password must have 8 to 72 characters") + errWrong = errors.New("wrong email or password") + errGone = errors.New("the account does not exist") + hashName = regexp.MustCompile(`^[0-9a-f]{64}$`) +) + +// Account is one user. The file of the user is in files/<ID>. +type Account struct { + ID string `json:"id"` + Email string `json:"email"` + Hash string `json:"hash"` // bcrypt hash of the password + Created time.Time `json:"created"` + Tokens []string `json:"tokens"` // SHA-256 of each sign-in token + Customer string `json:"customer,omitempty"` + Status string `json:"status,omitempty"` // of the Stripe subscription + StatusAt int64 `json:"status_at,omitempty"` // time of the Stripe event that set Status +} + +// Store keeps the accounts in one JSON file, accounts.json, and the versions +// of each bookmark file in files/<account ID>/<SHA-256 of the text>. The file +// HEAD beside the versions names the current one. +type Store struct { + dir string + mu sync.Mutex // for the maps, the accounts and accounts.json + accounts map[string]*Account + byEmail map[string]*Account + byToken map[string]*Account + locks map[string]*sync.Mutex // one for the files of each account +} + +func openStore(dir string) (*Store, error) { + if err := os.MkdirAll(filepath.Join(dir, "files"), 0o700); err != nil { + return nil, err + } + s := &Store{ + dir: dir, + accounts: map[string]*Account{}, + byEmail: map[string]*Account{}, + byToken: map[string]*Account{}, + locks: map[string]*sync.Mutex{}, + } + b, err := os.ReadFile(filepath.Join(dir, "accounts.json")) + if errors.Is(err, fs.ErrNotExist) { + return s, nil + } else if err != nil { + return nil, err + } + var list []*Account + if err := json.Unmarshal(b, &list); err != nil { + return nil, err + } + for _, a := range list { + s.index(a) + } + return s, nil +} + +func (s *Store) index(a *Account) { + s.accounts[a.ID] = a + s.byEmail[a.Email] = a + for _, t := range a.Tokens { + s.byToken[t] = a + } +} + +// save writes accounts.json. The caller holds s.mu. +func (s *Store) save() error { + list := make([]*Account, 0, len(s.accounts)) + for _, a := range s.accounts { + list = append(list, a) + } + sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) }) + b, err := json.MarshalIndent(list, "", "\t") + if err != nil { + return err + } + return writeFile(filepath.Join(s.dir, "accounts.json"), b) +} + +// writeFile replaces a file in one step: a crash leaves the old file or the +// new one, never a part of one. +func writeFile(name string, data []byte) error { + tmp := name + ".tmp" + f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return err + } + _, err = f.Write(data) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(tmp) + return err + } + return os.Rename(tmp, name) +} + +func random(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) // crypto/rand does not fail on supported systems + } + return hex.EncodeToString(b) +} + +func digest(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +// cleanEmail gives the email address in the form that the store keeps. +func cleanEmail(email string) (string, error) { + email = strings.ToLower(strings.TrimSpace(email)) + a, err := mail.ParseAddress(email) + if err != nil || a.Name != "" || a.Address != email || len(email) > 254 { + return "", errEmail + } + return email, nil +} + +func (s *Store) signup(email, password string) (*Account, error) { + email, err := cleanEmail(email) + if err != nil { + return nil, err + } + if len(password) < 8 || len(password) > 72 { + return nil, errPassword + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if s.byEmail[email] != nil { + return nil, errTaken + } + a := &Account{ID: random(16), Email: email, Hash: string(hash), Created: time.Now().UTC()} + s.index(a) + if err := s.save(); err != nil { + delete(s.accounts, a.ID) + delete(s.byEmail, a.Email) + return nil, err + } + return a, nil +} + +// dummy is compared when the email is unknown, so that a wrong email takes +// as long as a wrong password. +var dummy, _ = bcrypt.GenerateFromPassword([]byte("sbm-sync dummy password"), bcrypt.DefaultCost) + +func (s *Store) check(email, password string) (*Account, error) { + email = strings.ToLower(strings.TrimSpace(email)) + s.mu.Lock() + a := s.byEmail[email] + hash := dummy + if a != nil { + hash = []byte(a.Hash) + } + s.mu.Unlock() + if bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil || a == nil { + return nil, errWrong + } + return a, nil +} + +// signIn gives a new token for the account. Only its hash is kept. +func (s *Store) signIn(a *Account) (string, error) { + token := random(32) + s.mu.Lock() + defer s.mu.Unlock() + if s.accounts[a.ID] == nil { + return "", errGone + } + a.Tokens = append(a.Tokens, digest(token)) + s.byToken[digest(token)] = a + for len(a.Tokens) > maxTokens { + delete(s.byToken, a.Tokens[0]) + a.Tokens = a.Tokens[1:] + } + return token, s.save() +} + +func (s *Store) signOut(token string) error { + h := digest(token) + s.mu.Lock() + defer s.mu.Unlock() + a := s.byToken[h] + if a == nil { + return nil + } + delete(s.byToken, h) + for i, t := range a.Tokens { + if t == h { + a.Tokens = append(a.Tokens[:i], a.Tokens[i+1:]...) + break + } + } + return s.save() +} + +func (s *Store) byTok(token string) *Account { + if token == "" { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + return s.byToken[digest(token)] +} + +func (s *Store) byID(id string) *Account { + s.mu.Lock() + defer s.mu.Unlock() + return s.accounts[id] +} + +func (s *Store) byCustomer(customer string) *Account { + if customer == "" { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + for _, a := range s.accounts { + if a.Customer == customer { + return a + } + } + return nil +} + +// view gives a copy of the account, safe to read without the lock. +func (s *Store) view(a *Account) Account { + s.mu.Lock() + defer s.mu.Unlock() + c := *a + c.Tokens = nil + return c +} + +func (s *Store) setCustomer(a *Account, customer string) error { + s.mu.Lock() + defer s.mu.Unlock() + a.Customer = customer + return s.save() +} + +// setStatus records the state of the subscription, unless the store has a +// newer event already: Stripe does not send events in order. +func (s *Store) setStatus(a *Account, status string, at int64) error { + s.mu.Lock() + defer s.mu.Unlock() + if at < a.StatusAt { + return nil + } + a.Status, a.StatusAt = status, at + return s.save() +} + +func (s *Store) lock(id string) *sync.Mutex { + s.mu.Lock() + defer s.mu.Unlock() + m := s.locks[id] + if m == nil { + m = &sync.Mutex{} + s.locks[id] = m + } + return m +} + +// remove deletes the account and all versions of its file. +func (s *Store) remove(a *Account) error { + m := s.lock(a.ID) + m.Lock() + defer m.Unlock() + s.mu.Lock() + delete(s.accounts, a.ID) + delete(s.byEmail, a.Email) + for _, t := range a.Tokens { + delete(s.byToken, t) + } + err := s.save() + s.mu.Unlock() + if err != nil { + return err + } + return os.RemoveAll(filepath.Join(s.dir, "files", a.ID)) +} + +// sync merges the file that a device sends into the current version, keeps +// the result as the new current version and gives it with its name. base +// names the version that the device got last time, or is "" for none. +func (s *Store) sync(a *Account, base, local string) (string, string, error) { + m := s.lock(a.ID) + m.Lock() + defer m.Unlock() + if s.byID(a.ID) == nil { + return "", "", errGone + } + dir := filepath.Join(s.dir, "files", a.ID) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", "", err + } + remote := "" + head, err := os.ReadFile(filepath.Join(dir, "HEAD")) + if err == nil { + b, err := os.ReadFile(filepath.Join(dir, strings.TrimSpace(string(head)))) + if err != nil { + return "", "", err + } + remote = string(b) + } else if !errors.Is(err, fs.ErrNotExist) { + return "", "", err + } + old := "" + if hashName.MatchString(base) { + if b, err := os.ReadFile(filepath.Join(dir, base)); err == nil { + old = string(b) + } + } + merged := merge(old, local, remote) + name := digest(merged) + path := filepath.Join(dir, name) + if _, err := os.Stat(path); err == nil { + now := time.Now() + err = os.Chtimes(path, now, now) // the newest versions are kept + if err != nil { + return "", "", err + } + } else if err := writeFile(path, []byte(merged)); err != nil { + return "", "", err + } + if err := writeFile(filepath.Join(dir, "HEAD"), []byte(name+"\n")); err != nil { + return "", "", err + } + return merged, name, prune(dir, name) +} + +// prune deletes all but the newest versions in dir, and never keep. +func prune(dir, keep string) error { + entries, err := os.ReadDir(dir) + if err != nil { + return err + } + type version struct { + name string + time time.Time + } + var vs []version + for _, e := range entries { + if !hashName.MatchString(e.Name()) || e.Name() == keep { + continue + } + info, err := e.Info() + if err != nil { + return err + } + vs = append(vs, version{e.Name(), info.ModTime()}) + } + sort.Slice(vs, func(i, j int) bool { return vs[i].time.After(vs[j].time) }) + for i := maxVersions - 1; i < len(vs); i++ { + if err := os.Remove(filepath.Join(dir, vs[i].name)); err != nil { + return err + } + } + return nil +} diff --git a/stripe.go b/stripe.go new file mode 100644 index 0000000..7e73a4b --- /dev/null +++ b/stripe.go @@ -0,0 +1,163 @@ +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// Stripe calls the few parts of the Stripe API that billing needs. The API +// takes form fields and gives JSON, so the standard library is enough. +type Stripe struct { + Key string // secret API key + Webhook string // signing secret of the webhook endpoint + API string // https://api.stripe.com; tests replace it + Client *http.Client +} + +func (s *Stripe) call(method, path string, form url.Values) (map[string]any, error) { + req, err := http.NewRequest(method, s.API+path, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.SetBasicAuth(s.Key, "") + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := s.Client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + return nil, fmt.Errorf("stripe %s %s: %s", method, path, resp.Status) + } + if resp.StatusCode >= 300 { + msg := resp.Status + if e, ok := out["error"].(map[string]any); ok { + msg, _ = e["message"].(string) + } + return nil, fmt.Errorf("stripe %s %s: %s", method, path, msg) + } + return out, nil +} + +// checkout starts a Stripe Checkout session for a subscription to price and +// gives the address of its page. +func (s *Stripe) checkout(a Account, price, site string) (string, error) { + form := url.Values{ + "mode": {"subscription"}, + "line_items[0][price]": {price}, + "line_items[0][quantity]": {"1"}, + "client_reference_id": {a.ID}, + "subscription_data[metadata][account]": {a.ID}, + "success_url": {site + "/account"}, + "cancel_url": {site + "/account"}, + } + if a.Customer != "" { + form.Set("customer", a.Customer) + } else { + form.Set("customer_email", a.Email) + } + out, err := s.call("POST", "/v1/checkout/sessions", form) + if err != nil { + return "", err + } + u, _ := out["url"].(string) + if u == "" { + return "", errors.New("stripe gave no checkout address") + } + return u, nil +} + +// portal gives the address of a Stripe customer portal session, where the +// customer changes the card, sees invoices or cancels. +func (s *Stripe) portal(customer, site string) (string, error) { + out, err := s.call("POST", "/v1/billing_portal/sessions", + url.Values{"customer": {customer}, "return_url": {site + "/account"}}) + if err != nil { + return "", err + } + u, _ := out["url"].(string) + if u == "" { + return "", errors.New("stripe gave no portal address") + } + return u, nil +} + +// deleteCustomer deletes the customer in Stripe. That ends the +// subscriptions of the customer at once. +func (s *Stripe) deleteCustomer(customer string) error { + _, err := s.call("DELETE", "/v1/customers/"+url.PathEscape(customer), nil) + return err +} + +// label gives a price as text, such as "$3 a month". +func (s *Stripe) label(price string) (string, error) { + out, err := s.call("GET", "/v1/prices/"+url.PathEscape(price), nil) + if err != nil { + return "", err + } + amount, _ := out["unit_amount"].(float64) + currency, _ := out["currency"].(string) + interval := "" + if r, ok := out["recurring"].(map[string]any); ok { + interval, _ = r["interval"].(string) + } + return money(int64(amount), currency) + " a " + interval, nil +} + +func money(cents int64, currency string) string { + n := strconv.FormatInt(cents/100, 10) + if cents%100 != 0 { + n = fmt.Sprintf("%d.%02d", cents/100, cents%100) + } + if currency == "usd" { + return "$" + n + } + return n + " " + strings.ToUpper(currency) +} + +var errSignature = errors.New("bad Stripe signature") + +// verify checks the Stripe-Signature header of a webhook request: an +// HMAC-SHA256 of "<time>.<body>" with the signing secret. A request older +// than five minutes is refused, so that a copy cannot be sent again later. +func verify(body []byte, header, secret string, now time.Time) error { + var t string + var sigs []string + for _, part := range strings.Split(header, ",") { + k, v, _ := strings.Cut(strings.TrimSpace(part), "=") + switch k { + case "t": + t = v + case "v1": + sigs = append(sigs, v) + } + } + ts, err := strconv.ParseInt(t, 10, 64) + if err != nil || secret == "" { + return errSignature + } + if d := now.Sub(time.Unix(ts, 0)); d > 5*time.Minute || d < -5*time.Minute { + return errSignature + } + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(t + ".")) + mac.Write(body) + want := mac.Sum(nil) + for _, sig := range sigs { + got, err := hex.DecodeString(sig) + if err == nil && hmac.Equal(got, want) { + return nil + } + } + return errSignature +} diff --git a/testdata/rapid/TestLocalAdditionsStay/TestLocalAdditionsStay-20260921033717-1828.fail b/testdata/rapid/TestLocalAdditionsStay/TestLocalAdditionsStay-20260921033717-1828.fail new file mode 100644 index 0000000..f44db09 --- /dev/null +++ b/testdata/rapid/TestLocalAdditionsStay/TestLocalAdditionsStay-20260921033717-1828.fail @@ -0,0 +1,18 @@ +# 2026/09/21 03:37:17.082965 [TestLocalAdditionsStay] [rapid] draw base: []string{"https://suckless.org/\tsuckless\ttools"} +# 2026/09/21 03:37:17.082965 [TestLocalAdditionsStay] [rapid] draw local: []string{"https://suckless.org/\tsuckless\ttools", ""} +# 2026/09/21 03:37:17.082965 [TestLocalAdditionsStay] [rapid] draw remote: []string{} +# 2026/09/21 03:37:17.082965 [TestLocalAdditionsStay] line "" that local added is lost +# +v0.4.8#16217358014360582265 +0x6666666666666 +0x0 +0x0 +0x0 +0x6666666666666 +0x0 +0x0 +0x6666666666666 +0x9867f1f40f739 +0x9 +0x0 +0x0 \ No newline at end of file diff --git a/testdata/rapid/TestRemoteAdditionsStayWithoutConflict/TestRemoteAdditionsStayWithoutConflict-20260921033649-16892.fail b/testdata/rapid/TestRemoteAdditionsStayWithoutConflict/TestRemoteAdditionsStayWithoutConflict-20260921033649-16892.fail new file mode 100644 index 0000000..5a6cbe6 --- /dev/null +++ b/testdata/rapid/TestRemoteAdditionsStayWithoutConflict/TestRemoteAdditionsStayWithoutConflict-20260921033649-16892.fail @@ -0,0 +1,18 @@ +# 2026/09/21 03:36:49.132391 [TestRemoteAdditionsStayWithoutConflict] [rapid] draw base: []string{"https://suckless.org\tsuckless software\ttools c"} +# 2026/09/21 03:36:49.132391 [TestRemoteAdditionsStayWithoutConflict] [rapid] draw local: []string{} +# 2026/09/21 03:36:49.132391 [TestRemoteAdditionsStayWithoutConflict] [rapid] draw remote: []string{"https://suckless.org\tsuckless software\ttools c", ""} +# 2026/09/21 03:36:49.132391 [TestRemoteAdditionsStayWithoutConflict] line "" that the server added is lost +# +v0.4.8#1060941482528800742 +0x6666666666666 +0x0 +0x1 +0x0 +0x0 +0x6666666666666 +0x0 +0x1 +0x6666666666666 +0x1f2b5a0e61c3a6 +0x0 +0x0 \ No newline at end of file