commit 9f7718ad8f4fd71e382905453efde5622b39b69a5f0de33722d0b0503a031bc7 Author: Linus Björnstam Date: Sat Nov 21 21:06:11 2026 +0100 bjomarks: bookmarks, their store, search and import Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..703539e --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.bjo/ +*.dll +*.exe +*.pdb +*.bjobuild +*.runtimeconfig.json +*.deps.json +# Native executables, and the output of bjo publish. +/src/main +/tests/app +/tests/screenshots +/publish/ +/publish-android/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d22367a --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Readme.org b/Readme.org new file mode 100644 index 0000000..dc1bca5 --- /dev/null +++ b/Readme.org @@ -0,0 +1,534 @@ +* bjomarks — bookmarks in an encrypted store + +Bookmarks that sync between devices through a folder that any file syncer or +WebDAV share carries. The folder holds only encrypted files: the storage +provider sees how many devices there are and roughly how large the vault is, +and nothing else. Encryption and password hashing are [[file:../bjosodium/Readme.org][bjosodium]]'s. + +#+BEGIN_SRC sh +export BJOMARKS_PASSWORD="correct horse" +bjo build examples/marks.bjo +M="dotnet examples/marks.exe" +$M ~/Sync/bookmarks ~/.local/share/bjomarks create +$M ~/Sync/bookmarks ~/.local/share/bjomarks add https://example.org/ rust async +# on the second device, once the syncer has copied the folder: +$M ~/Sync/bookmarks ~/.local/share/bjomarks join +$M ~/Sync/bookmarks ~/.local/share/bjomarks list +#+END_SRC + +| Module | What it has | +|-----------------------+----------------------------------------------------------------| +| ~(bjomarks bookmark)~ | bookmarks, stamps, entries, the merge, and their JSON | +| ~(bjomarks keys)~ | ~keys.bin~: the vault's key, wrapped for a password | +| ~(bjomarks store)~ | device files, storage, and the vault that syncs | +| ~(bjomarks title)~ | the title of a web page, fetched from its address | +| ~(bjomarks wayback)~ | the latest snapshot of a page in the Wayback Machine | +| ~(bjomarks import)~ | Firefox's JSON backup, read, and its bookmarks put in a vault | +| ~(bjomarks draft)~ | the dialog of a bookmark as it is typed | +| ~(bjomarks search)~ | the search of the list: words, typos, tags, domains and days | +| ~(bjomarks duplicates)~ | one bookmark for a page that two devices bookmarked | +| ~(bjomarks binary)~ | big-endian integers and the cipher byte, for the binary files | + +** Using it + +#+BEGIN_SRC scheme +(depends + (package (name (bjomarks)) + (version (version-at-least "0.1.0")) + (source (path (dir "../bjomarks"))))) +#+END_SRC + +#+BEGIN_SRC scheme +(import (std prelude)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +;; Adds a bookmark, changes its tags, and syncs. +(: (-> Storage string string (Result string int))) +(defun (add-one storage local password) + (match (open-vault storage local password) + ((Err WrongPassword) (Err "The password is wrong.")) + ((Err _) (Err "The vault does not open.")) + ((Ok opened) + (def (Tuple v report) (vault-sync opened)) ; merge the other devices + (def (Ok (Tuple v2 b)) (vault-add v "https://example.org/" #:tags ["rust"]) :propagate) + (def v3 (vault-put v2 (bookmark-with-tags b ["rust" "web"]))) + (def (Tuple v4 _) (vault-sync v3)) ; write this device's file + (vault-close v4) + (Ok (vec-length (.problems report)))))) + +(add-one (folder-storage "/home/me/Sync/bookmarks") "/home/me/.local/share/bjomarks" password) +#+END_SRC + +| ~(create-vault storage local pw #:cost)~ | a new vault, with this device as its first | +| ~(join-vault storage local pw)~ | this device as a new device of a vault; synced | +| ~(open-vault storage local pw)~ | the vault of this device, from its own files | +| ~(vault-sync v)~ | merges the other devices, writes this device's file if it changed; with a ~SyncReport~ | +| ~(vault-save v)~ | writes this device's file, if there are changes | +| ~(vault-merge current done)~ | ~current~, with what a sync or save that ran in the background on an earlier copy of it did; it has changes to write when ~current~ changed meanwhile | +| ~(vault-bookmarks v)~ ~(vault-find v id)~ | the bookmarks, the newest first | +| ~(vault-add v url #:title #:tags #:archive #:added)~ | a new bookmark, or ~Err~ for an address that is not an absolute URL | +| ~(vault-put v b)~ | a changed bookmark | +| ~(vault-delete v id)~ | a deleted one | +| ~(vault-restore v entry)~ | the entry as it was before a delete, at a new stamp: an undo | +| ~(vault-change-password v pw #:cost)~ | ~(Ok v)~ with a new key and keys.bin; or ~(Err why)~ | +| ~(vault-close v)~ | sets the key to zeros | + +A vault is a value: a change returns a new vault, and nothing is written +until ~vault-save~ or ~vault-sync~. ~open-vault~, ~create-vault~ and +~join-vault~ return a ~StoreError~: ~WrongPassword~, ~NoVault~, +~VaultExists~, ~OtherVault~ or ~BadFile~, each with a text that says where. +A file of another device that cannot be read does not stop a sync: it is +skipped, and the report's ~problems~ name it. What the file system raises is +raised. + +*In a bjoroutine*, the file operations of the store do not block the thread, +and Argon2id runs on a thread of its own. ~Storage~ is a union, not a record +of functions, for that reason: a function in a record field cannot be of +either colour. + +*A folder without a path*, such as a folder of Android's Storage Access +Framework, is a storage of three functions: + +#+BEGIN_SRC scheme +(function-storage "Documents/bookmarks" + (fun (name) ...) ; (Some bytes), or None: no such file + (fun (name bytes) ...) ; writes it, and the folders on the way + (fun (dir) ...)) ; the names of the files in dir +#+END_SRC + +- A name is relative, with ~/~ between its parts, as for a folder. +- In a bjoroutine the functions block the thread. Call the vault's + functions in ~blocking~. +- A write need not replace the file in one step. A device that reads half + of a device file skips it, names it in the report's ~problems~, and reads + it at the next sync. +- bjomarks-android makes one from a folder of bjogui's ~(bjogui storage)~. + +** A bookmark + +A bookmark has an id, an address, an optional title, the instant it was +added, a set of tags, and an optional link to a copy in a web archive: + +#+BEGIN_SRC json +{"id": "0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f", + "stamp": "019a722fb300-0002-3f9c0d2a-1111-4222-8333-444455556666", + "url": "https://example.org/", + "title": "Example Domain", + "added": "2026-11-11T09:12:00Z", + "tags": ["async", "rust"], + "archive": "https://web.archive.org/web/20261111091200/https://example.org/"} +#+END_SRC + +| Field | Rules | +|-----------+---------------------------------------------------------------------------| +| ~id~ | a uuid; it does not change | +| ~stamp~ | when the entry last changed, and on which device: see /Merging/ | +| ~url~ | an absolute URL by RFC 3986: it has a scheme | +| ~title~ | one line of at most 300 characters, or ~null~, or absent. Read cleaned: white space made one space, the ends trimmed; empty is no title | +| ~added~ | ISO 8601 with an offset; read as UTC | +| ~tags~ | strings that are not empty; read as a set, written sorted. Can be absent | +| ~archive~ | an absolute URL, or ~null~, or absent | +| ~deleted~ | ~true~ for a tombstone, which has only ~id~ and ~stamp~ | + +*Fields from a newer version are kept.* A field that this version does not +know, such as a ~note~ that a later version adds, is kept in the entry's +~extra~, in the order it was read, and written back after the known fields. +~vault-put~ keeps the extra fields of the entry it replaces. So an older +version that changes the tags does not remove the note. A version from +before titles keeps a ~title~ in the same way. + +~parse-device-doc~ and ~json->entry~ return ~(Err why)~ with where: +~records[3]: tags[1]: expected a string~. + +** Importing from Firefox + +#+BEGIN_SRC scheme +(import (bjomarks import)) + +(match (read-firefox-backup (file-read-text "bookmarks-2026-11-11.json")) + ((Ok backup) + (def (Tuple v2 report) (vault-import v (.bookmarks backup))) + ;; (.added report), (.already report); (.not-web backup), (.invalid backup) + v2) + ((Err why) ...)) +#+END_SRC + +~read-firefox-backup~ reads the JSON backup that Firefox writes (Library, +Import and Backup, Backup…), not the HTML export: for that it returns an +~Err~ that says which file to use. +- Only http and https addresses are read; the others are counted in + ~not-web~. An http address that is not a URL by RFC 3986 is named, with + the reason, in ~invalid~: a bookmark must be one. +- Each folder of the user's that holds a bookmark is a tag of it, at any + depth; Firefox's four top folders are not. Firefox's tags are tags too. + ~tag-name~ makes a name a tag: lower case, ~-~ for each run of white + space and commas. +- An address bookmarked more than once is one bookmark, with the tags of + all its copies, the earliest date and the first title; ~copies~ counts + the others. +- Dates are Firefox's ~dateAdded~, in microseconds. + +~vault-import~ adds the bookmarks whose address the vault does not have, +and changes none that it has. So a backup can be imported again, and only +what is new comes in. The vault is saved as after any change. +~(import-summary name backup report)~ returns the line that the apps show: +"Imported 1 bookmark from bookmarks.json. 1 was here already." + +** Fetching a title + +#+BEGIN_SRC scheme +(import (bjomarks title)) + +(fetch-title "https://example.org/") ; (Ok "Example Domain") +(fetch-title "https://example.org/" #:within 5) ; a deadline of 5 seconds, not 10 +#+END_SRC + +~fetch-title~ is a ~defbjo~: call it in a bjoroutine. It returns the text +of the page's ~~ element, cleaned as the ~title~ field is, or +~(Err why)~: + +- for an address that is not http or https; nothing is fetched, +- for a request that fails, or a status that is not 2xx, +- for a type that is not HTML (no type is taken as HTML), +- when there is no title in the first 512 KiB, +- when the fetch does not end in the deadline: 10 seconds, or ~#:within~. + The fetch is then cancelled. + +Redirects are followed. Reading stops at the end of the title. The title is +decoded by the charset of the ~Content-Type~ header, else of a ~<meta>~ +element in the first 4 KiB, else as UTF-8; bytes that do not decode are read +as Windows-1252. Character references such as ~&~ are decoded. +~page-title~ does the same for bytes got another way. + +*A fetch tells the site.* The site sees the request: this machine's address, +the time, and the User-Agent ~Mozilla/5.0 (compatible; bjomarks/0.1; ++title)~. The storage provider sees nothing of it. Only ~<title>~ is read, +not ~og:title~ or other metadata. + +** Looking up an archive link + +#+BEGIN_SRC scheme +(import (bjomarks wayback)) + +(fetch-archive "https://example.com/") +;; (Ok "https://web.archive.org/web/20261118035140/https://example.com/") +(fetch-archive "https://example.com/" #:within 5) ; a deadline of 5 seconds, not 20 +#+END_SRC + +~fetch-archive~ is a ~defbjo~: call it in a bjoroutine. It asks the +availability API of the Wayback Machine (~wayback-api~, +~https://archive.org/wayback/available~) for the page, and returns the +address of its latest snapshot, made https. It returns ~(Err why)~: + +- for an address that is not http or https; nothing is asked, +- for a request that fails, or a status that is not 2xx, +- for an answer that is not JSON, +- when the Wayback Machine has no snapshot of the page, +- when the lookup does not end in the deadline: 20 seconds, or ~#:within~. + The API is often slow. The lookup is then cancelled. + +~#:api~ gives another address for the API, as the tests do. ~snapshot-in~ +reads the snapshot from an answer got another way. + +*A lookup tells the Internet Archive.* It sees the address of the page, +this machine's address and the User-Agent ~Mozilla/5.0 (compatible; +bjomarks/0.1; +archive)~. The page itself is not fetched, and no snapshot +is made. + +** The dialog + +(bjomarks draft) has what the apps' dialog of a bookmark does, so that the +desktop and Android do the same. The apps only show it. + +#+BEGIN_SRC scheme +(import (bjomarks draft)) + +(def d (with-address v empty-draft "https://example.org/")) ; loads its bookmark, if one has it +(match (apply-draft v d) + ((Ok (Tuple v2 bookmark)) v2) + ((Err why) ...)) ; not an absolute URL +#+END_SRC + +- A ~Draft~ is a bookmark being made (~editing~ is ~None~) or changed, with + its fields as typed. +- ~with-address~: in the dialog of a new bookmark, an address that a + bookmark has loads that bookmark. Another address brings back what was + typed. +- A fetch of the title or of the archive link has a number: + ~start-title-fetch~ starts it, and ~with-title-fetched~ puts its result in + the draft only when the draft still waits for that number. The same for + ~start-archive-fetch~ and ~with-archive-fetched~. + +** The search + +(bjomarks search) has the search of the list, for both apps. + +#+BEGIN_SRC scheme +(import (bjomarks search)) + +(search-bookmarks v "rust -t:docs d:github.com a:2024:") ; the bookmarks that the search shows +(query-problem (parse-query "a:2012-13")) ; "Not a date: 2012-13" +#+END_SRC + +| Term | A bookmark matches it when | +|-------------------+---------------------------------------------------------------------| +| ~rust~ | the word is in the title, the address or a tag, maybe with a typo | +| ~t:rust~ | it has the tag "rust", the whole tag (~tag:rust~ is the same) | +| ~d:github~ | its domain has "github" in it | +| ~d:github.com~ | its domain is github.com or one under it, such as gist.github.com | +| ~a:2012-06~ | it was added in June 2012 (a year, a month or a day) | +| ~a:2011:2012-06~ | it was added from 1 January 2011 to 30 June 2012 (~a:2011:~, ~a::2012~) | +| ~"two words"~ | it has exactly that text | +| ~-~ before a term | it does not match the term | + +- A word matches a whole word, the start of a word, a part of one, or a + word with typos: one in a word of 4 to 7 letters, two in a longer one. A + swap of two letters side by side is one typo. The other terms are exact. +- Capitals and accents do not matter, but å, ä, ö, æ and ø are letters of + their own. +- With words, the best matches come first: a whole word before a part, and + the title before the tags and the address. Otherwise the newest first. +- The days are in the clock's time zone. A date that is not one matches + nothing. +- What the search looks at is made once for each vault, and the last result + is kept, so the apps may search on each redraw. + +** Duplicates + +(bjomarks duplicates): two devices that bookmark a page before they sync +make two bookmarks of it. ~vault-join-duplicates~, after a sync, makes them +one, with the tags of both, the earliest time added and an archive link if +either has one. Bookmarks with different titles stay two, with the joined +tags, and are returned as a ~Duplicate~; ~vault-choose-title~ joins them +with the title chosen. Each device joins them the same way, so devices that +do it before they sync agree. + +** Merging + +Each device's file holds every entry it knows. A device reads the files of +the others and merges by id: *the entry with the later stamp wins*. A +deleted bookmark keeps its entry as a tombstone, so a delete reaches the +other devices and an older copy cannot bring the bookmark back. A change +after the delete does bring it back. + +A stamp is a hybrid logical clock: the wall-clock time in milliseconds, a +counter, and the device. A new stamp is later than every stamp the device has +made or merged, also when its wall clock is behind the others'. Its text is +~<12 hex digits of ms>-<4 hex digits of counter>-<device uuid>~, so the order +of the texts is the order of the stamps. + +Two different entries with the same stamp come only from a fault. Then the +entry with the greater JSON text wins, so all devices still choose the same +one. The tests check with generated entries that the merge gives the same +result in any order and grouping, that merging twice changes nothing, and +that each id keeps its latest stamp. + +A bookmark is merged as a whole: when two devices change the same bookmark +before they sync, the later change wins and the other is lost, also when one +changed the tags and the other the archive link. + +** The files + +*** In the shared storage + +#+BEGIN_SRC text +keys.bin the vault's key, wrapped for each password +devices/<device uuid>.bin one file for each device; only that device writes it +#+END_SRC + +*** In this device's folder (not shared) + +#+BEGIN_SRC text +device.json {"format": 1, "vault": "<uuid>", "device": "<uuid>"} +state.bin the same bytes as this device's file in the storage +keys.bin a copy of the storage's, so that the vault opens without it +#+END_SRC + +~(device-folder root shared storage)~ gives a folder in ~root/vaults~ for +each shared folder, named by a hash of ~shared~, so that a device can have +the vaults of several shared folders. The files of a device folder of the +older layout, ~root~ itself, move to the folder of the shared folder whose +~keys.bin~ is of their vault. + +~open-vault~ reads ~state.bin~ and this device's file in the storage, and +uses the one with the higher revision; it writes the other again at the next +save. A storage that lost this device's file, or ~keys.bin~, gets it again +at the next sync. + +The local copy of ~keys.bin~ is replaced only by one that this device has +the current key of, after it wrote its file with a key that the new one +holds. A ~keys.bin~ that an attacker put in the storage, with keys of their +own, therefore never replaces it: the device opens from its copy, and the +sync names the problem. See /A new password/. + +*Do not copy this device's folder to another machine.* Two devices with one +device id write the same file, and the syncer keeps one of them. + +*** keys.bin, version 1 + +Integers are big-endian. + +#+BEGIN_SRC text +offset size field +0 4 "BMKV" +4 2 version: 1 +6 16 vault id +22 1 number of slots, from 1 +23 the slots, one after the other + +A password slot: +0 1 kind: 1 = password +1 4 key id: the data key that the slot wraps +5 1 kdf: 1 = Argon2id (version 1.3, one lane) +6 4 iterations +10 4 memory, in KiB +14 16 salt +30 1 cipher: 1 = AEGIS-256, 2 = XChaCha20-Poly1305 +31 n nonce: 32 bytes, or 24 +31+n 32+t the data key, encrypted, and the tag: 32 bytes, or 16 + +A slot of an earlier key, the same length: +0 1 kind: 2 = an earlier key +1 4 key id: the earlier data key that the slot holds +5 1 kdf: 0 = none +6 4 the key id of the data key that wraps it: the current one +10 20 zeros +30 1 cipher +31 n nonce +31+n 32+t the earlier data key, encrypted with the current one, and the tag +#+END_SRC + +- The data key (DEK) is 32 random bytes. It encrypts every device file. +- A password slot wraps the DEK with a key that Argon2id makes from the + password, the salt and the cost. The associated data is bytes 0 to 21 of + the file and bytes 0 to 30 of the slot, so a change to the vault id, the + cost or the salt makes the slot fail. +- The password slots come first, and wrap the same DEK: the current one. + The earlier keys follow, the latest first, at most 200. A version that + knows only password slots skips them. +- A reader tries at most 4 password slots, and refuses a cost above 100 + iterations or 1 GiB, because a file from an attacker could otherwise stop + the device. +- The default cost is 3 iterations over 64 MiB, about 75 ms on a desktop CPU + of 2020. Measure on the slowest device, and give ~#:cost~ more if it allows. + +*** A new password + +~vault-change-password~ makes a new DEK, with a random key id, and a new +~keys.bin~: a password slot for the new DEK, and the earlier DEKs wrapped +with it. The device then writes its file with the new DEK. An old copy of +~keys.bin~ (in a syncer's versions, a backup or a trash folder) and the old +password then open only what was written before the change. + +- The other devices, while they are open, read on with the keys they have, + and write with their key, which the new ~keys.bin~ holds as an earlier + one, so that all of them read it. Their sync tells them that the password + changed; the old password no longer opens the vault, also from their copy + of ~keys.bin~. +- A device that does not have every key of the storage's ~keys.bin~ cannot + change the password: it would leave a key out. +- Two devices that change it at the same time: the syncer keeps one + ~keys.bin~. The other device writes its file with a key that the kept one + holds, so that the others read it, and opens with its own password from + its copy of ~keys.bin~ until it opens with the other one. With the same + password, both files open, and their keys are joined. + +*** A device file, version 1 + +#+BEGIN_SRC text +offset size field +0 4 "BMK1" +4 2 version: 1 +6 16 vault id +22 16 device id: the same as in the file's name +38 8 revision: 1 for the first file, then 1 more each time +46 4 key id: the DEK that encrypts the file +50 1 cipher: 1 = AEGIS-256, 2 = XChaCha20-Poly1305 +51 n nonce: 32 bytes, or 24; new for each file +51+n the contents, encrypted, then the tag + +The contents: +0 1 compression: 0 = none, 1 = Brotli +1 4 length of the stored document +5 4 length of the document +9 the stored document, then bytes of 0 +#+END_SRC + +- The associated data is the header, bytes 0 to 50+n. A file whose header + was changed does not decrypt. +- The contents are padded to a multiple of 16 KiB, so that the size of a + file shows only roughly how many bookmarks there are. +- The document is UTF-8 JSON: + #+BEGIN_SRC json + {"format": 1, "device": "<uuid>", "seen": {"<uuid>": 41}, "records": [<entry>, ...]} + #+END_SRC + ~records~ are in the order of their ids, so the same entries give the same + text. ~seen~ is the highest revision of each other device's file that this + device has merged. +- Each device writes with the cipher it prefers (see bjosodium's + ~preferred-cipher~), and reads both. + +*** What a sync checks + +A file of another device is skipped, and reported, when: + +- its name is not ~<uuid>.bin~ (a syncer's conflicted copy, for example); +- it is not a device file, or of a newer version; +- it is of another vault, or encrypted with a key this device does not have; +- it does not decrypt: it was changed, or written with another key; +- its header or its document names another device than its file name. + +A file whose revision is older than one this device merged before is merged, +and reported: the storage gave back an older copy. It cannot undo anything, +since its entries lose to the newer ones. + +** What the storage provider sees + +- The number of devices, from the number of files, and their random ids. +- The size of each file, in steps of 16 KiB. +- When each file changes. +- The vault id and each file's revision, in the headers. + +Not the addresses, the titles, the tags, the archive links, the times or +the exact number of bookmarks. + +** Changes from the plan + +The format we agreed on, with these changes: + +- The cipher is AEGIS-256 or XChaCha20-Poly1305, not AES-256-GCM. So the + header has a cipher byte, and the nonce is 32 or 24 bytes, not 12. +- The contents have a header of their own: the compression, and the two + lengths that Brotli needs and that padding hides. +- ~seen~ is in the document, as planned, so ~device.json~ holds only the + two ids. The local folder holds a copy of ~keys.bin~ too. +- The field for the instant is ~added~, and the archive link is ~archive~. + There is no folder, order or note yet. A later version can add them, and + this one keeps them (see /Fields from a newer version are kept/). + +** Not done + +- WebDAV: a second case of ~Storage~. +- A second secret for the password slot (a key in a QR code, to pair a + device), and a slot for a recovery code. The slot kinds leave room for both. +- Removing old tombstones. +- A way to change the password in the two apps. +- Merging field by field, so that changes to different fields of one + bookmark both win. + +** Try it + +#+BEGIN_SRC sh +bjo run tests/bookmark.bjo # stamps, JSON, and the merge's properties +bjo run tests/keys.bjo # keys.bin, and changes to it that must fail +bjo run tests/store.bjo # two and three devices in folders of the temp directory +bjo run tests/title.bjo # titles in bytes, and fetched from a server on the loopback +bjo run tests/import.bjo # a Firefox backup, read, and imported into a vault +bjo run tests/draft.bjo # the dialog of a bookmark +bjo run tests/search.bjo # the search: parsing, typos, tags, domains and days +bjo run tests/duplicates.bjo # a page bookmarked on two devices before they synced +#+END_SRC + +All eight run on Linux x64. Nothing is run on Windows, macOS, Android or iOS +yet. diff --git a/examples/marks.bjo b/examples/marks.bjo new file mode 100644 index 0000000..bd26b8b --- /dev/null +++ b/examples/marks.bjo @@ -0,0 +1,124 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/examples/marks.bjo — bookmarks from the command line. +;; +;; marks SHARED LOCAL create +;; marks SHARED LOCAL join +;; marks SHARED LOCAL add URL [TAG ...] +;; marks SHARED LOCAL list +;; marks SHARED LOCAL tag ID [TAG ...] +;; marks SHARED LOCAL archive ID URL +;; marks SHARED LOCAL delete ID +;; marks SHARED LOCAL sync +;; +;; SHARED is the folder that the devices share, LOCAL this device's own +;; folder. The password is read from BJOMARKS_PASSWORD, or from the first +;; line of the input. An ID can be its first characters, if only one +;; bookmark starts with them. Each command syncs before and after it. + +(import (std prelude)) +(import (std uuid)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +(: (-> string)) +(defun (password) + (match (get-environment-variable "BJOMARKS_PASSWORD") + ((Some p) p) + (None (print "Password: ") (read-line (parameter-ref current-input-port))))) + +(: (-> StoreError string)) +(defun (describe e) + (match e + (WrongPassword "The password is wrong.") + ((NoVault why) why) + ((VaultExists why) why) + ((OtherVault why) why) + ((BadFile why) why))) + +(: (-> SyncReport void)) +(defun (report r) + (loop (:for p (.problems r)) (:do (println (str "warning: " p))))) + +(: (-> Bookmark void)) +(defun (show b) + (def tags (if (vec-empty? (.tags b)) "" (str " [" (string-join (.tags b) " ") "]"))) + (def archive (match (.archive b) ((Some a) (str "\n archived: " a)) (None ""))) + (println (str (string-take (uuid->string (.id b)) 8) " " (.url b) tags archive))) + +;; The one bookmark whose id starts with `prefix`. +(: (-> Vault string (Option Bookmark))) +(defun (find-bookmark v prefix) + (def found (vec-filter (fun (b) (string-starts-with? (uuid->string (.id b)) prefix)) (vault-bookmarks v))) + (if (= (vec-length found) 1) (Some (vec-ref found 0)) None)) + +;; Runs a change on the open, synced vault, and syncs again. +(: (-> Storage string (-> Vault (Result string Vault)) int)) +(defun (with-vault storage local change) + (match (open-vault storage local (password)) + ((Err e) (println (describe e)) 1) + ((Ok opened) + (def (Tuple v r) (vault-sync opened)) + (report r) + (match (change v) + ((Err why) (println why) (vault-close v) 1) + ((Ok changed) + (def (Tuple done r2) (vault-sync changed)) + (report r2) + (vault-close done) + 0))))) + +(: (-> (Vec string) int)) +(defun (main args) + (if (< (vec-length args) 3) + (begin (println "usage: marks SHARED LOCAL create|join|add|list|tag|archive|delete|sync ...") 2) + (let ((storage (folder-storage (vec-ref args 0))) + (local (vec-ref args 1)) + (command (vec-ref args 2)) + (rest (vec-drop args 3))) + (cond + ((= command "create") + (match (create-vault storage local (password)) + ((Ok v) (println (str "A new vault, " (uuid->string (vault-id v)))) (vault-close v) 0) + ((Err e) (println (describe e)) 1))) + ((= command "join") + (match (join-vault storage local (password)) + ((Ok (Tuple v r)) + (report r) + (println (str "Joined: " (int->string (vec-length (vault-bookmarks v))) " bookmarks")) + (vault-close v) + 0) + ((Err e) (println (describe e)) 1))) + ((= command "list") + (with-vault storage local (fun (v) (loop (:for b (vault-bookmarks v)) (:do (show b))) (Ok v)))) + ((= command "sync") (with-vault storage local (fun (v) (Ok v)))) + ((and (= command "add") (>= (vec-length rest) 1)) + (with-vault storage local + (fun (v) + (match (vault-add v (vec-ref rest 0) #:tags (vec-drop rest 1)) + ((Ok (Tuple v2 b)) (show b) (Ok v2)) + ((Err why) (Err why)))))) + ((and (= command "tag") (>= (vec-length rest) 1)) + (with-vault storage local + (fun (v) + (match (find-bookmark v (vec-ref rest 0)) + ((Some b) (Ok (vault-put v (bookmark-with-tags b (vec-drop rest 1))))) + (None (Err (str "No one bookmark has the id " (vec-ref rest 0)))))))) + ((and (= command "archive") (= (vec-length rest) 2)) + (with-vault storage local + (fun (v) + (match (find-bookmark v (vec-ref rest 0)) + ((Some b) + (match (bookmark-with-archive b (Some (vec-ref rest 1))) + ((Ok b2) (Ok (vault-put v b2))) + ((Err why) (Err why)))) + (None (Err (str "No one bookmark has the id " (vec-ref rest 0)))))))) + ((and (= command "delete") (= (vec-length rest) 1)) + (with-vault storage local + (fun (v) + (match (find-bookmark v (vec-ref rest 0)) + ((Some b) (Ok (vault-delete v (.id b)))) + (None (Err (str "No one bookmark has the id " (vec-ref rest 0)))))))) + (else (println (str "Unknown command, or the wrong arguments: " command)) 2))))) diff --git a/manifest.bjodat b/manifest.bjodat new file mode 100644 index 0000000..95f9b2b --- /dev/null +++ b/manifest.bjodat @@ -0,0 +1,13 @@ +(package + (name (bjomarks)) + (version "0.1.0") + (description "Bookmarks in an encrypted store: one file for each device, in any folder that a file syncer or WebDAV shares.") + (license "MPL-2.0") + + (depends + (package (name (bjosodium)) + (version (version-at-least "0.1.0")) + (source (path (dir "../bjosodium"))))) + + ;; A library: there is no src/main.bjo. + ) diff --git a/packages.lock.json b/packages.lock.json new file mode 100644 index 0000000..bfa59f1 --- /dev/null +++ b/packages.lock.json @@ -0,0 +1,27 @@ +{ + "version": 1, + "dependencies": { + "net11.0": { + "libsodium": { + "type": "Transitive", + "resolved": "1.0.20.2", + "contentHash": "FButtPK6HZvOewaE20F1HXNJn4qOoGAf7FEDm0VbWJ+xBX9pN9+2nkQQnfaLz+Ae5KuEzRoe1GHO00UpabgNxA==" + }, + "LibSodium.Net": { + "type": "Transitive", + "resolved": "0.16.0-alpha", + "contentHash": "uNW5uuT2QEu5zUSDAbNyXM/RPZjnLjMEp88uYMCkH2yr9+jX7LpZsV9JZimdIABKiHivfGqSJAXmj3Bd2tmJUQ==", + "dependencies": { + "libsodium": "1.0.20.1" + } + }, + "bjopackage.bjosodium": { + "type": "Project", + "dependencies": { + "LibSodium.Net": "[0.16.0-alpha, 0.16.0-alpha]", + "libsodium": "[1.0.20.2, 1.0.21)" + } + } + } + } +} \ No newline at end of file diff --git a/src/binary.bjo b/src/binary.bjo new file mode 100644 index 0000000..6742127 --- /dev/null +++ b/src/binary.bjo @@ -0,0 +1,104 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/binary.bjo — the module (bjomarks binary): what the binary +;; files of a vault are made of. +;; +;; - Integers are big-endian. A u16 and a u32 are read as an int, a u64 as a +;; long; the formats never write a value above what those types hold. +;; - The `put` functions write into an array at an offset. The `get` +;; functions read from one. An offset outside the array raises +;; `ArgumentOutOfRangeException`; the readers check lengths first. +;; - A cipher is written as one byte: 1 for AEGIS-256, 2 for +;; XChaCha20-Poly1305. + +(export + put-u8! put-u16! put-u32! put-u64! put-bytes! + get-u8 get-u16 get-u32 get-u64 get-bytes + bytes-concat bytes=? bytes-at? + cipher->code code->cipher) + +(import (std prelude)) +(import (only (std crypto hash) constant-time-equal?)) +(import (bjosodium core)) + +(import/extern + (clr-write-u16 (: System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian (-> (Span byte) ushort void))) + (clr-write-i32 (: System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian (-> (Span byte) int void))) + (clr-write-i64 (: System.Buffers.Binary.BinaryPrimitives.WriteInt64BigEndian (-> (Span byte) long void))) + (clr-read-u16 (: System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian (-> (RoSpan byte) ushort))) + (clr-read-i32 (: System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian (-> (RoSpan byte) int))) + (clr-read-i64 (: System.Buffers.Binary.BinaryPrimitives.ReadInt64BigEndian (-> (RoSpan byte) long)))) + +(: (-> (Array byte) int int void)) +(defun (put-u8! a at v) (array-set! a at (cast byte v))) + +(: (-> (Array byte) int int void)) +(defun (put-u16! a at v) (clr-write-u16 (array->span a #:from at) (cast ushort v))) + +;; `v` is from 0 to 2^31 - 1. +(: (-> (Array byte) int int void)) +(defun (put-u32! a at v) (clr-write-i32 (array->span a #:from at) v)) + +;; `v` is from 0 to 2^63 - 1. +(: (-> (Array byte) int long void)) +(defun (put-u64! a at v) (clr-write-i64 (array->span a #:from at) v)) + +;; Copies all of `bytes` into `a` from `at`. +(: (-> (Array byte) int (Array byte) void)) +(defun (put-bytes! a at bytes) + (.CopyTo (array->ro-span bytes) (array->span a #:from at #:to (+ at (array-length bytes))))) + +(: (-> (Array byte) int int)) +(defun (get-u8 a at) (cast int (array-ref a at))) + +(: (-> (Array byte) int int)) +(defun (get-u16 a at) (cast int (clr-read-u16 (array->ro-span a #:from at)))) + +;; A value above 2^31 - 1 is read as a negative int, which every reader +;; rejects. +(: (-> (Array byte) int int)) +(defun (get-u32 a at) (clr-read-i32 (array->ro-span a #:from at))) + +;; A value above 2^63 - 1 is read as a negative long, which every reader +;; rejects. +(: (-> (Array byte) int long)) +(defun (get-u64 a at) (clr-read-i64 (array->ro-span a #:from at))) + +;; A copy of the `n` bytes of `a` from `at`. +(: (-> (Array byte) int int (Array byte))) +(defun (get-bytes a at n) (ro-span->array (array->ro-span a #:from at #:to (+ at n)))) + +;; `a`, then `b`, in a new array. +(: (-> (Array byte) (Array byte) (Array byte))) +(defun (bytes-concat a b) + (def out (: (make-array (+ (array-length a) (array-length b))) (Array byte))) + (put-bytes! out 0 a) + (put-bytes! out (array-length a) b) + out) + +;; True when the two arrays hold the same bytes. `=` on arrays compares the +;; arrays, not their bytes. The time does not depend on where they differ. +(: (-> (Array byte) (Array byte) bool)) +(defun (bytes=? a b) (constant-time-equal? a b)) + +;; True when `a` holds `bytes` from `at`. +(: (-> (Array byte) int (Array byte) bool)) +(defun (bytes-at? a at bytes) + (def n (array-length bytes)) + (and (<= (+ at n) (array-length a)) + (bytes=? (get-bytes a at n) bytes))) + +(: (-> Cipher int)) +(defun (cipher->code c) + (match c + (Aegis256 1) + (XChaCha20Poly1305 2))) + +(: (-> int (Option Cipher))) +(defun (code->cipher code) + (match code + (1 (Some Aegis256)) + (2 (Some XChaCha20Poly1305)) + (_ None))) diff --git a/src/bookmark.bjo b/src/bookmark.bjo new file mode 100644 index 0000000..06f9867 --- /dev/null +++ b/src/bookmark.bjo @@ -0,0 +1,583 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/bookmark.bjo — the module (bjomarks bookmark): bookmarks, the +;; stamps that order their changes, how two sets of them merge, and their +;; JSON. +;; +;; - A bookmark has an id, an address (`url`), an optional title, the instant +;; it was added, a set of tags, and an optional link to a copy in a web +;; archive. +;; - An entry is one bookmark as one device last knew it: the bookmark, or +;; the fact that it was deleted (a tombstone), with the stamp of the change. +;; - Two devices merge their entries by id. For each id the entry with the +;; later stamp wins (last writer wins). The merge gives the same result in +;; any order, and merging twice changes nothing. +;; - The JSON of an entry keeps the fields that this version does not know, +;; so that an older version does not remove what a newer one wrote. + +(export + ;; Bookmarks + Bookmark make-bookmark bookmark-with-tags bookmark-with-archive bookmark-with-title + clean-tags clean-title absolute-url? + ;; Stamps + Stamp stamp->string string->stamp stamp-compare + Clock clock-zero clock-observe clock-next + ;; Entries + Entry EntryState entry-id entry-live? live-entry deleted-entry + ;; Merging + merge-entry merge-entries merge-entries/count merge-maps entries->map entries-clock live-bookmarks + ;; JSON + entry->json json->entry + DeviceDoc document-format device-doc->string parse-device-doc) + +(import (std prelude)) +(import (std datetime)) +(import (std uuid)) +(import (std url)) +(import (text json)) + +(import/extern + ;; The input, a pattern and its replacement. + (clr-collapse (: System.Text.RegularExpressions.Regex.Replace (-> string string string string)))) + +;; --------------------------------------------------------------------------- +;; Bookmarks +;; --------------------------------------------------------------------------- + +;; `title` is the page's title, as given or fetched: one line, not empty. +;; `tags` is sorted and has each tag once. `archive` is the address of a copy +;; in a web archive, such as https://web.archive.org/web/2026.../https://... +(type (: Bookmark (Record (: id Uuid) + (: url string) + (: title (Option string)) + (: added Instant) + (: tags (Vec string)) + (: archive (Option string))))) + +;; The most characters a title keeps. +(: int) +(def max-title-length 300) + +;; A title as kept: each run of white space, line breaks too, made one +;; space, the ends trimmed, and at most 300 characters. `None` for a title +;; that is then empty. +(: (-> string (Option string))) +(defun (clean-title text) + (def one-line (string-trim (clr-collapse text "\\s+" " "))) + (cond + ((string-empty? one-line) None) + ((> (string-count one-line) max-title-length) + (Some (string-trim (string-take one-line max-title-length)))) + (else (Some one-line)))) + +;; True when `text` is an absolute URL by RFC 3986: it has a scheme, as +;; https://example.org/ and mailto:a@example.org have. +(: (-> string bool)) +(defun (absolute-url? text) + (match (parse-url text) + ((Ok u) (url-absolute? u)) + ((Err _) #f))) + +;; Each tag once, in order. The caller removes the empty ones. +(: (-> (Vec string) (Vec string))) +(defun (sorted-unique tags) + (def sorted (vec-sort tags)) + (def n (vec-length sorted)) + (let go ((i 0) (out [])) + (cond + ((= i n) out) + ((and (> i 0) (= (vec-ref sorted i) (vec-ref sorted (- i 1)))) (go (+ i 1) out)) + (else (go (+ i 1) (vec-add out (vec-ref sorted i))))))) + +;; The tags trimmed, without the empty ones, each once and in order. +(: (-> (Vec string) (Vec string))) +(defun (clean-tags tags) + (sorted-unique (vec-filter #(not (string-empty? &)) (vec-map string-trim tags)))) + +;; A new bookmark with a new random id. `Err` when `url` or `archive` is not +;; an absolute URL. The title is cleaned with `clean-title`, and the tags +;; with `clean-tags`. +(: (-> string (#:title (Option string)) (#:tags (Vec string)) (#:added Instant) + (#:archive (Option string)) + (Result string Bookmark))) +(defun (make-bookmark url #:title None #:tags [] #:added (now) #:archive None) + (def address (string-trim url)) + (cond + ((not (absolute-url? address)) (Err (str "Not an absolute URL: " url))) + (:def link (match archive ((Some a) (Some (string-trim a))) (None None))) + ((match link ((Some a) (not (absolute-url? a))) (None #f)) + (Err (str "The archive link is not an absolute URL: " (match link ((Some a) a) (None ""))))) + (else (Ok (Bookmark (id (uuid-v4)) (url address) + (title (match title ((Some t) (clean-title t)) (None None))) + (added added) (tags (clean-tags tags)) (archive link)))))) + +;; The bookmark with another title, cleaned with `clean-title`, or none. +(: (-> Bookmark (Option string) Bookmark)) +(defun (bookmark-with-title b text) + (record-set b (title (match text ((Some t) (clean-title t)) (None None))))) + +;; The bookmark with other tags, cleaned with `clean-tags`. +(: (-> Bookmark (Vec string) Bookmark)) +(defun (bookmark-with-tags b tags) (record-set b (tags (clean-tags tags)))) + +;; The bookmark with another archive link, or none. `Err` when the link is +;; not an absolute URL. +(: (-> Bookmark (Option string) (Result string Bookmark))) +(defun (bookmark-with-archive b link) + (match link + ((Some a) + (def address (string-trim a)) + (if (absolute-url? address) + (Ok (record-set b (archive (Some address)))) + (Err (str "The archive link is not an absolute URL: " a)))) + (None (Ok (record-set b (archive None)))))) + +;; --------------------------------------------------------------------------- +;; Stamps +;; --------------------------------------------------------------------------- +;; +;; A stamp is a hybrid logical clock: the wall-clock time in milliseconds, a +;; counter for changes in the same millisecond or while the wall clock is +;; behind, and the device that made the change. Stamps are ordered by the +;; three, in that order, so two devices never make equal stamps. +;; +;; The text of a stamp is `<ms>-<counter>-<device>`: 12 and 4 lower-case hex +;; digits and the device's uuid. All three have a fixed width, so the order +;; of the texts is the order of the stamps. + +(type (: Stamp (Record (: ms long) + (: counter int) + (: device Uuid)))) + +;; The largest time that 12 hex digits hold: 2^48 - 1 ms, in the year 10889. +(: long) +(def max-ms 281474976710655L) + +(: int) +(def max-counter 65535) + +(: (Array byte)) +(def hex-digits (string->bytes "0123456789abcdef")) + +;; `v` as `width` lower-case hex digits. `v` is from 0 and fits. +(: (-> long int string)) +(defun (hex-of v width) + (def out (: (make-array width) (Array byte))) + (let go ((i (- width 1)) (rest v)) + (when (>= i 0) + (set! out i (get hex-digits (cast int (bitwise-and rest 15L)))) + (go (- i 1) (shift-right rest 4)))) + (bytes->string out)) + +;; The value of the lower-case hex digits of `bytes` from `start` to `end`. +;; `None` for any other byte. +(: (-> (Array byte) int int (Option long))) +(defun (hex-value bytes start end) + (let go ((i start) (v 0L)) + (if (= i end) + (Some v) + (let ((b (cast int (array-ref bytes i)))) + (cond + ((and (>= b 48) (<= b 57)) + (go (+ i 1) (+ (* v 16L) (cast long (- b 48))))) + ((and (>= b 97) (<= b 102)) + (go (+ i 1) (+ (* v 16L) (cast long (- b 87))))) + (else None)))))) + +(: (-> Stamp string)) +(defun (stamp->string s) + (str (hex-of (.ms s) 12) "-" (hex-of (cast long (.counter s)) 4) "-" (uuid->string (.device s)))) + +;; `None` unless `text` is exactly what `stamp->string` writes. +(: (-> string (Option Stamp))) +(defun (string->stamp text) + (def bytes (string->bytes text)) + (if (not (and (= (array-length bytes) 54) + (= (cast int (array-ref bytes 12)) 45) + (= (cast int (array-ref bytes 17)) 45))) + None + (match (Tuple (hex-value bytes 0 12) + (hex-value bytes 13 17) + (string->uuid (string-drop text 18))) + ((Tuple (Some ms) (Some counter) (Some device)) + ;; Lower case only, so that the text has one spelling. + (if (= (uuid->string device) (string-drop text 18)) + (Some (Stamp (ms ms) (counter (cast int counter)) (device device))) + None)) + (_ None)))) + +;; Negative when `a` is earlier than `b`, 0 when they are equal, positive when +;; `a` is later. +(: (-> Stamp Stamp int)) +(defun (stamp-compare a b) + (compare (Tuple (.ms a) (.counter a) (uuid->string (.device a))) + (Tuple (.ms b) (.counter b) (uuid->string (.device b))))) + +;; The latest time and counter a device has made or seen. A new stamp is +;; always later than all of them. +(type (: Clock (Record (: last-ms long) + (: last-counter int)))) + +(: Clock) +(def clock-zero (Clock (last-ms 0L) (last-counter 0))) + +;; The clock after seeing `s`. +(: (-> Clock Stamp Clock)) +(defun (clock-observe c s) + (if (> (compare (Tuple (.ms s) (.counter s)) (Tuple (.last-ms c) (.last-counter c))) 0) + (Clock (last-ms (.ms s)) (last-counter (.counter s))) + c)) + +;; A new stamp of `device` at the wall-clock time `wall-ms`, later than all +;; that `c` has seen, and the clock after it. +;; - The wall clock is used when it is ahead of the clock. +;; - Else the counter goes up, and after 65535 the time goes up by 1 ms. +(: (-> Clock long Uuid (Tuple Clock Stamp))) +(defun (clock-next c wall-ms device) + (def ms (.last-ms c)) + (def counter (.last-counter c)) + (def s (cond + ((> wall-ms ms) + (Stamp (ms (if (> wall-ms max-ms) max-ms wall-ms)) (counter 0) (device device))) + ((< counter max-counter) (Stamp (ms ms) (counter (+ counter 1)) (device device))) + (else (Stamp (ms (+ ms 1L)) (counter 0) (device device))))) + (Tuple (clock-observe c s) s)) + +;; --------------------------------------------------------------------------- +;; Entries +;; --------------------------------------------------------------------------- + +;; A bookmark, or the id of one that was deleted. +(type (: EntryState (Union (: Live Bookmark) + (: Deleted Uuid)))) + +;; `extra` is the fields of the JSON that this version does not know, in the +;; order they were read. They are written back after the known fields. A +;; deleted entry has none. +(type (: Entry (Record (: stamp Stamp) + (: state EntryState) + (: extra (Vec (Tuple string Json)))))) + +(: (-> Entry Uuid)) +(defun (entry-id e) + (match (.state e) + ((Live b) (.id b)) + ((Deleted id) id))) + +(: (-> Entry bool)) +(defun (entry-live? e) + (match (.state e) + ((Live _) #t) + ((Deleted _) #f))) + +;; A changed or new bookmark, with no extra fields. +(: (-> Stamp Bookmark Entry)) +(defun (live-entry s b) (Entry (stamp s) (state (Live b)) (extra []))) + +;; A tombstone: the bookmark with this id was deleted. +(: (-> Stamp Uuid Entry)) +(defun (deleted-entry s id) (Entry (stamp s) (state (Deleted id)) (extra []))) + +;; --------------------------------------------------------------------------- +;; Merging +;; --------------------------------------------------------------------------- +;; +;; Entries are kept in a map by the text of their id. For each id the entry +;; with the later stamp wins. Two different entries with the same stamp come +;; only from a fault, as a device never makes a stamp twice; then the one with +;; the greater JSON text wins, so that all devices still choose the same one. + +;; True when `a` wins over `b`. +(: (-> Entry Entry bool)) +(defun (wins? a b) + (def order (stamp-compare (.stamp a) (.stamp b))) + (cond + ((> order 0) #t) + ((< order 0) #f) + ((= a b) #f) + (else (> (compare (json->string (entry->json a)) + (json->string (entry->json b))) + 0)))) + +;; `entries` with `e` in it, when `e` wins over the entry it has for that id. +(: (-> (Map string Entry) Entry (Map string Entry))) +(defun (merge-entry entries e) + (def key (uuid->string (entry-id e))) + (match (map-try-ref entries key) + ((Some old) (if (wins? e old) (map-set entries key e) entries)) + (None (map-set entries key e)))) + +(: (-> (Map string Entry) (Vec Entry) (Map string Entry))) +(defun (merge-entries entries es) + (vec-fold (fun (e acc) (merge-entry acc e)) entries es)) + +;; `merge-entries`, and how many entries of `es` won: 0 when the merge +;; changed nothing. +(: (-> (Map string Entry) (Vec Entry) (Tuple (Map string Entry) int))) +(defun (merge-entries/count entries es) + (vec-fold (fun (e acc) + (def (Tuple m n) acc) + (def key (uuid->string (entry-id e))) + (match (map-try-ref m key) + ((Some old) (if (wins? e old) (Tuple (map-set m key e) (+ n 1)) acc)) + (None (Tuple (map-set m key e) (+ n 1))))) + (Tuple entries 0) es)) + +;; Every entry of `b` merged into `a`. +(: (-> (Map string Entry) (Map string Entry) (Map string Entry))) +(defun (merge-maps a b) + (map-fold (fun (k e acc) (merge-entry acc e)) a b)) + +(: (-> (Vec Entry) (Map string Entry))) +(defun (entries->map es) (merge-entries (map-empty) es)) + +;; The clock after seeing every stamp of `entries`. +(: (-> (Map string Entry) Clock)) +(defun (entries-clock entries) + (map-fold (fun (k e c) (clock-observe c (.stamp e))) clock-zero entries)) + +;; The bookmarks that are not deleted, the newest first. +(: (-> (Map string Entry) (Vec Bookmark))) +(defun (live-bookmarks entries) + (def live (map-fold (fun (k e acc) + (match (.state e) + ((Live b) (vec-add acc b)) + ((Deleted _) acc))) + [] entries)) + (vec-sort-by (fun (a b) + (compare (Tuple (- 0L (instant->unix-milliseconds (.added a))) + (uuid->string (.id a))) + (Tuple (- 0L (instant->unix-milliseconds (.added b))) + (uuid->string (.id b))))) + live)) + +;; --------------------------------------------------------------------------- +;; JSON of an entry +;; --------------------------------------------------------------------------- +;; +;; {"id": "<uuid>", "stamp": "<stamp>", "url": "https://...", +;; "title": "Example Domain", "added": "2026-11-11T09:12:00Z", +;; "tags": ["a", "b"], "archive": "https://web.archive.org/web/..."} +;; {"id": "<uuid>", "stamp": "<stamp>", "deleted": true} +;; +;; - `title`, `tags` and `archive` can be absent. `title` and `archive` can +;; be null. A title is read as `clean-title` makes it. +;; - `added` is ISO 8601 with an offset. It is read as UTC. +;; - Any other field of a bookmark is kept in `extra`. + +(: (Vec string)) +(def known-fields ["id" "stamp" "deleted" "url" "title" "added" "tags" "archive"]) + +(: (-> (IArray (Tuple string Json)) string (Option Json))) +(defun (lookup fields key) (json-object-ref (JsonFields fields) key)) + +(: (-> (IArray (Tuple string Json)) string (Result string string))) +(defun (required-string fields key) + (match (lookup fields key) + ((Some (JsonStr s)) (Ok s)) + ((Some _) (Err (str key ": expected a string"))) + (None (Err (str key ": missing"))))) + +(: (-> string string (Result string string))) +(defun (url-field key text) + (match (parse-url text) + ((Ok u) (if (url-absolute? u) (Ok text) (Err (str key ": not an absolute URL: " text)))) + ((Err why) (Err (str key ": not a URL: " why))))) + +(: (-> (IArray Json) (Result string (Vec string)))) +(defun (read-tags items) + (def n (iarray-length items)) + (let go ((i 0) (out [])) + (if (= i n) + (Ok (sorted-unique out)) + (match (iarray-ref items i) + ((JsonStr "") (Err (str "tags[" (int->string i) "]: a tag cannot be empty"))) + ((JsonStr t) (go (+ i 1) (vec-add out t))) + (_ (Err (str "tags[" (int->string i) "]: expected a string"))))))) + +(: (-> (IArray (Tuple string Json)) Uuid (Result string Bookmark))) +(defun (read-bookmark fields id) + (def (Ok url-text) (required-string fields "url") + :propagate) + (def (Ok url) (url-field "url" url-text) + :propagate) + (def (Ok added-text) (required-string fields "added") + :propagate) + (def (Some added) (iso8601->instant added-text) + :leave-with (Err (str "added: not an ISO 8601 date and time with an offset: " added-text))) + (def (Ok tags) + (match (lookup fields "tags") + (None (Ok [])) + ((Some (JsonArr items)) (read-tags items)) + ((Some _) (Err "tags: expected an array of strings"))) + :propagate) + (def (Ok archive) + (match (lookup fields "archive") + (None (Ok None)) + ((Some JsonNull) (Ok None)) + ((Some (JsonStr a)) + (match (url-field "archive" a) ((Ok a) (Ok (Some a))) ((Err why) (Err why)))) + ((Some _) (Err "archive: expected a string or null"))) + :propagate) + (def (Ok title) + (match (lookup fields "title") + (None (Ok None)) + ((Some JsonNull) (Ok None)) + ((Some (JsonStr t)) (Ok (clean-title t))) + ((Some _) (Err "title: expected a string or null"))) + :propagate) + (Ok (Bookmark (id id) (url url) (title title) (added added) (tags tags) (archive archive)))) + +(: (-> (IArray (Tuple string Json)) (Result string Entry))) +(defun (read-entry fields) + (def (Ok id-text) (required-string fields "id") + :propagate) + (def (Some id) (string->uuid id-text) + :leave-with (Err (str "id: not a uuid: " id-text))) + (def (Ok stamp-text) (required-string fields "stamp") + :propagate) + (def (Some stamp) (string->stamp stamp-text) + :leave-with (Err (str "stamp: not a stamp: " stamp-text))) + (def (Ok deleted) + (match (lookup fields "deleted") + (None (Ok #f)) + ((Some (JsonBool b)) (Ok b)) + ((Some _) (Err "deleted: expected true or false"))) + :propagate) + (if deleted + (Ok (deleted-entry stamp id)) + (match (read-bookmark fields id) + ((Ok b) + (Ok (Entry (stamp stamp) (state (Live b)) + (extra (vec-filter (fun (f) (not (vec-contains? known-fields (fst f)))) + (iarray->vec fields)))))) + ((Err why) (Err why))))) + +;; The entry that the JSON `j` holds, or why it does not hold one. An object +;; read as a map, not as fields, is read too, but the order of its extra +;; fields is then the map's. +(: (-> Json (Result string Entry))) +(defun (json->entry j) + (match j + ((JsonFields fields) (read-entry fields)) + ((JsonObj m) (read-entry (vec->iarray (map->vec m)))) + (_ (Err "expected an object")))) + +(: (-> Entry Json)) +(defun (entry->json e) + (def head [(Tuple "id" (JsonStr (uuid->string (entry-id e)))) + (Tuple "stamp" (JsonStr (stamp->string (.stamp e))))]) + (match (.state e) + ((Deleted _) (JsonFields (vec->iarray (vec-add head (Tuple "deleted" (JsonBool #t)))))) + ((Live b) + (def titled (match (.title b) + ((Some t) + (vec-add (vec-add head (Tuple "url" (JsonStr (.url b)))) + (Tuple "title" (JsonStr t)))) + (None (vec-add head (Tuple "url" (JsonStr (.url b))))))) + (def fields (vec-append titled + [(Tuple "added" (JsonStr (written (.added b)))) + (Tuple "tags" (JsonArr (vec->iarray (vec-map JsonStr (.tags b)))))])) + (def with-archive (match (.archive b) + ((Some a) (vec-add fields (Tuple "archive" (JsonStr a)))) + (None fields))) + (JsonFields (vec->iarray (vec-append with-archive (.extra e))))))) + +;; --------------------------------------------------------------------------- +;; The document of a device +;; --------------------------------------------------------------------------- +;; +;; {"format": 1, "device": "<uuid>", "seen": {"<uuid>": 41, ...}, +;; "records": [<entry>, ...]} +;; +;; - `records` is every entry the device knows, its own and those it merged: +;; the whole state, not only its own changes. +;; - `seen` is the highest revision of each other device's file that this +;; device has merged. +;; - Fields other than these four are not kept. + +(: int) +(def document-format 1) + +(type (: DeviceDoc (Record (: device Uuid) + (: seen (Map string long)) + (: entries (Vec Entry))))) + +;; Compact JSON. The records are in the order of their ids, so the same +;; entries always give the same text. +(: (-> DeviceDoc string)) +(defun (device-doc->string doc) + (def records + (vec-sort-by (fun (a b) (compare (uuid->string (entry-id a)) (uuid->string (entry-id b)))) + (.entries doc))) + (json->string + (JsonFields + (vec->iarray + [(Tuple "format" (JsonInt (cast long document-format))) + (Tuple "device" (JsonStr (uuid->string (.device doc)))) + (Tuple "seen" (JsonObj (map-map-values JsonInt (.seen doc)))) + (Tuple "records" (JsonArr (vec->iarray (vec-map entry->json records))))])))) + +(: (-> (IArray (Tuple string Json)) (Result string (Map string long)))) +(defun (read-seen fields) + (def n (iarray-length fields)) + (let go ((i 0) (out (map-empty))) + (if (= i n) + (Ok out) + (match (iarray-ref fields i) + ((Tuple k (JsonInt r)) + (cond + ((match (string->uuid k) ((Some _) #f) (None #t)) (Err (str "seen: not a uuid: " k))) + ((< r 0L) (Err (str "seen." k ": a revision cannot be negative"))) + (else (go (+ i 1) (map-set out k r))))) + ((Tuple k _) (Err (str "seen." k ": expected an integer"))))))) + +(: (-> (IArray Json) (Result string (Vec Entry)))) +(defun (read-records items) + (def n (iarray-length items)) + (let go ((i 0) (out [])) + (if (= i n) + (Ok out) + (match (json->entry (iarray-ref items i)) + ((Ok e) (go (+ i 1) (vec-add out e))) + ((Err why) (Err (str "records[" (int->string i) "]: " why))))))) + +;; The document that `text` holds, or why it does not hold one: not JSON, a +;; format newer than `document-format`, or a field that is not right. +(: (-> string (Result string DeviceDoc))) +(defun (parse-device-doc text) + (def (Ok j) (parse-json text #:objects 'fields) + :propagate) + (def (JsonFields fields) j + :leave-with (Err "expected an object")) + (def (Ok format) + (match (lookup fields "format") + ((Some (JsonInt f)) (Ok f)) + ((Some _) (Err "format: expected an integer")) + (None (Err "format: missing"))) + :propagate) + (cond + ((> format (cast long document-format)) + (Err (str "format " (long->string format) " is newer than this version reads (" + (int->string document-format) ")"))) + ((< format 1L) (Err (str "format " (long->string format) " is not a format"))) + (else + (def (Ok device-text) (required-string fields "device") + :propagate) + (def (Some device) (string->uuid device-text) + :leave-with (Err (str "device: not a uuid: " device-text))) + (def (Ok seen) + (match (lookup fields "seen") + (None (Ok (map-empty))) + ((Some (JsonFields s)) (read-seen s)) + ((Some _) (Err "seen: expected an object"))) + :propagate) + (def (Ok entries) + (match (lookup fields "records") + ((Some (JsonArr items)) (read-records items)) + ((Some _) (Err "records: expected an array")) + (None (Err "records: missing"))) + :propagate) + (Ok (DeviceDoc (device device) (seen seen) (entries entries)))))) diff --git a/src/draft.bjo b/src/draft.bjo new file mode 100644 index 0000000..7e10460 --- /dev/null +++ b/src/draft.bjo @@ -0,0 +1,203 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/draft.bjo — the module (bjomarks draft): the dialog of a +;; bookmark, as it is typed. The apps show it; this module has what it +;; does. The search of the list is in (bjomarks search). +;; +;; The dialog: +;; - A `Draft` is a bookmark being made (`editing` is `None`) or changed. +;; - `with-address` is the draft after its address was typed. In the dialog +;; of a new bookmark, an address that a bookmark has loads that bookmark, +;; so that no address is there twice. +;; - `apply-draft` puts the draft in the vault, or returns why it cannot. +;; - A fetch of the title or of the archive link has a number. Its result +;; goes in the draft only when the draft still waits for that number: +;; typing in the field drops the fetch. + +(export + Typed Draft empty-draft draft-of address-here + bookmark-with-url with-address apply-draft split-tags fetch-address + start-title-fetch start-archive-fetch with-title-fetched with-archive-fetched) + +(import (std prelude)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +;; --------------------------------------------------------------------------- +;; The dialog +;; --------------------------------------------------------------------------- + +;; What was typed in a new bookmark's dialog before its address loaded +;; another bookmark. +(type (: Typed (Record (: title string) + (: tags string) + (: archive string)))) + +;; A bookmark being made (`editing` is `None`) or changed, as it is typed. +;; - An empty `title` or `archive` is none. +;; - `fetching` is the number of the fetch of the title that runs for this +;; draft, if one runs. `archiving` is the same for the archive link. +;; - `typed` is `Some` when the dialog was opened for a new bookmark, and its +;; address is one that a bookmark has: then the draft edits that bookmark, +;; and `typed` keeps what was typed before, for when the address changes +;; again. +(type (: Draft (Record (: editing (Option Bookmark)) + (: url string) + (: title string) + (: tags string) + (: archive string) + (: problem string) + (: fetching (Option int)) + (: archiving (Option int)) + (: typed (Option Typed))))) + +;; The draft of a new bookmark. +(: Draft) +(def empty-draft + (Draft (editing None) (url "") (title "") (tags "") (archive "") (problem "") (fetching None) (archiving None) + (typed None))) + +;; The draft that edits `b`. +(: (-> Bookmark Draft)) +(defun (draft-of b) + (Draft (editing (Some b)) (url (.url b)) (title (option-ref-or (.title b) "")) + (tags (string-join (.tags b) " ")) (archive (option-ref-or (.archive b) "")) (problem "") + (fetching None) (archiving None) (typed None))) + +;; What the problem line says while a new bookmark's dialog edits the +;; bookmark that has its address. +(: string) +(def address-here "This address is here already: this is its bookmark.") + +;; The bookmark with the address `url`, exactly, if there is one. +(: (-> Vault string (Option Bookmark))) +(defun (bookmark-with-url v url) + (def found (vec-filter (fun (b) (= (.url b) url)) (vault-bookmarks v))) + (if (vec-empty? found) None (Some (vec-ref found 0)))) + +;; The draft of the bookmark `b`, whose address `s` was typed in a new +;; bookmark's dialog. `before` is what the other fields had. +(: (-> Bookmark string Typed Draft)) +(defun (loaded b s before) + (def d (draft-of b)) + (record-set d (url s) (typed (Some before)) (problem address-here))) + +;; The draft after its address was typed in. The fetches that run are +;; dropped. A dialog opened for a new bookmark checks the address: +;; - An address that a bookmark has, as it is, but for the spaces at its +;; ends: the draft edits that bookmark, and keeps what was typed in the +;; other fields. +;; - Then another address: the draft is of a new bookmark again, with what +;; was typed in the other fields before. +;; A dialog opened to edit a bookmark does not check. +(: (-> Vault Draft string Draft)) +(defun (with-address v d s) + (def d2 (record-set d (url s) (problem "") (fetching None) (archiving None))) + (def new? (or (none? (.editing d)) (some? (.typed d)))) + (def before (match (.typed d) + ((Some t) t) + (None (Typed (title (.title d)) (tags (.tags d)) (archive (.archive d)))))) + (match (Tuple new? (bookmark-with-url v (string-trim s)) (.editing d)) + ((Tuple #f _ _) d2) + ;; The bookmark it edits already: the edits to it are kept. + ((Tuple #t (Some b) (Some e)) + (if (= (.id b) (.id e)) + (record-set d2 (problem address-here)) + (loaded b s before))) + ((Tuple #t (Some b) None) (loaded b s before)) + ((Tuple #t None _) + (match (.typed d) + ((Some t) (record-set d2 (editing None) (title (.title t)) (tags (.tags t)) (archive (.archive t)) + (typed None))) + (None d2))))) + +;; Tags as typed: separated by spaces or commas. +(: (-> string (Vec string))) +(defun (split-tags text) + (vec-filter (fun (t) (not (string-empty? t))) (string-split (string-replace text "," " ") " "))) + +(: (-> string (Option string))) +(defun (optional text) + (def t (string-trim text)) + (if (string-empty? t) None (Some t))) + +;; The vault with the bookmark of the draft, and the bookmark. `Err` with +;; the reason when the address or the archive link is not an absolute URL. +;; - An edit keeps the fields of newer versions: see `vault-put`. +(: (-> Vault Draft (Result string (Tuple Vault Bookmark)))) +(defun (apply-draft v d) + (def tags (split-tags (.tags d))) + (def archive (optional (.archive d))) + (def title (optional (.title d))) + (def url (string-trim (.url d))) + (match (.editing d) + (None (vault-add v url #:title title #:tags tags #:archive archive)) + ((Some old) + (cond + ((not (absolute-url? url)) (Err (str "Not an absolute URL: " (.url d)))) + (:def edited (bookmark-with-title (bookmark-with-tags (record-set old (url url)) tags) title)) + (:def (Ok b) (bookmark-with-archive edited archive) + :propagate) + (else (Ok (Tuple (vault-put v b) b))))))) + +;; The address of the draft to fetch from: trimmed, with "https://" before +;; it when it does not start with "http". `None` when it is empty. +(: (-> Draft (Option string))) +(defun (fetch-address d) + (def url (string-trim (.url d))) + (cond + ((string-empty? url) None) + ((string-starts-with? url "http") (Some url)) + (else (Some (str "https://" url))))) + +;; --------------------------------------------------------------------------- +;; Fetching the title and the archive link +;; --------------------------------------------------------------------------- + +;; Starts the fetch number `n` of the title: the draft that waits for it, +;; and the address to fetch. The address in the draft gets its "https://". +;; - `None` when a fetch of the title runs already. +;; - `Err` of the draft with a problem when there is no address. +(: (-> Draft int (Option (Result Draft (Tuple Draft string))))) +(defun (start-title-fetch d n) + (match (Tuple (.fetching d) (fetch-address d)) + ((Tuple (Some _) _) None) + ((Tuple None None) (Some (Err (record-set d (problem "Type the address first."))))) + ((Tuple None (Some url)) (Some (Ok (Tuple (record-set d (fetching (Some n)) (url url) (problem "")) url)))))) + +;; The same as `start-title-fetch`, for the archive link. +(: (-> Draft int (Option (Result Draft (Tuple Draft string))))) +(defun (start-archive-fetch d n) + (match (Tuple (.archiving d) (fetch-address d)) + ((Tuple (Some _) _) None) + ((Tuple None None) (Some (Err (record-set d (problem "Type the address first."))))) + ((Tuple None (Some url)) (Some (Ok (Tuple (record-set d (archiving (Some n)) (url url) (problem "")) url)))))) + +(: (-> Exception string)) +(defun (message-of e) (.-Message e)) + +;; The draft after the fetch number `n` of the title ended with `r`. The +;; title goes in the field when the draft still waits for that fetch. Else +;; the draft is as it was. +(: (-> Draft int (Result Exception (Result string string)) Draft)) +(defun (with-title-fetched d n r) + (if (= (.fetching d) (Some n)) + (let ((done (record-set d (fetching None)))) + (match r + ((Ok (Ok title)) (record-set done (title title))) + ((Ok (Err why)) (record-set done (problem (str "No title: " why ".")))) + ((Err e) (record-set done (problem (str "No title: " (message-of e))))))) + d)) + +;; The same as `with-title-fetched`, for the archive link. +(: (-> Draft int (Result Exception (Result string string)) Draft)) +(defun (with-archive-fetched d n r) + (if (= (.archiving d) (Some n)) + (let ((done (record-set d (archiving None)))) + (match r + ((Ok (Ok link)) (record-set done (archive link))) + ((Ok (Err why)) (record-set done (problem (str "No archive: " why ".")))) + ((Err e) (record-set done (problem (str "No archive: " (message-of e))))))) + d)) diff --git a/src/duplicates.bjo b/src/duplicates.bjo new file mode 100644 index 0000000..444e687 --- /dev/null +++ b/src/duplicates.bjo @@ -0,0 +1,132 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/duplicates.bjo — the module (bjomarks duplicates): one +;; bookmark for each page. +;; +;; Two devices that add the same page before they sync make two bookmarks of +;; it, with ids of their own. After a sync, `vault-join-duplicates` makes +;; them one: +;; +;; - Bookmarks are of the same page when their addresses are the same text. +;; https://example.org/a and https://example.org/a/ are two pages. +;; - The one kept is the one added first; a tie goes to the lower id. The +;; others are deleted. +;; - It gets the tags of all of them, the earliest time added, and the first +;; archive link that one has, in the same order. +;; - When they have one title, or none, that title is kept. When their +;; titles differ, the user chooses: they all stay, with the joined tags, +;; time and archive link, and the page is reported as a `Duplicate`. +;; `vault-choose-title` then makes them one, with the title chosen. +;; +;; Each device that joins a page makes the same bookmark from the same +;; bookmarks, so two devices that join it before they sync agree. + +(export + Duplicate duplicate-url duplicate-titles duplicate-ids + vault-join-duplicates vault-choose-title) + +(import (std prelude)) +(import (std datetime)) +(import (std uuid)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +;; A page that bookmarks with different titles hold: its address, the titles +;; in the order of the bookmarks, each once, and the ids of the bookmarks. +(type (: Duplicate (Record (: url string) + (: titles (Vec string)) + (: ids (Vec Uuid))))) + +(: (-> Duplicate string)) +(defun (duplicate-url d) (.url d)) + +(: (-> Duplicate (Vec string))) +(defun (duplicate-titles d) (.titles d)) + +(: (-> Duplicate (Vec Uuid))) +(defun (duplicate-ids d) (.ids d)) + +;; The bookmarks of each address that more than one bookmark has, each group +;; in the order of `first-added?`, the groups in the order of their address. +(: (-> Vault (Vec (Vec Bookmark)))) +(defun (groups v) + (def by-url (vec-fold (fun (b m) + (map-set m (.url b) (vec-add (option-ref-or (map-try-ref m (.url b)) []) b))) + (map-empty) (vault-bookmarks v))) + (map-fold (fun (url bs acc) (if (> (vec-length bs) 1) (vec-add acc (vec-sort-by order bs)) acc)) + [] by-url)) + +;; The bookmark added first comes first; of two added at once, the one with +;; the lower id. +(: (-> Bookmark Bookmark int)) +(defun (order a b) + (compare (Tuple (instant->unix-milliseconds (.added a)) (uuid->string (.id a))) + (Tuple (instant->unix-milliseconds (.added b)) (uuid->string (.id b))))) + +;; The titles of `bs`, each once, in their order. +(: (-> (Vec Bookmark) (Vec string))) +(defun (titles bs) + (vec-fold (fun (b acc) + (match (.title b) + ((Some t) (if (vec-contains? acc t) acc (vec-add acc t))) + (None acc))) + [] bs)) + +;; `b` with the tags of all of `bs`, the time of the first, and the first +;; archive link. `bs` is in the order of `order`. +(: (-> Bookmark (Vec Bookmark) Bookmark)) +(defun (joined b bs) + (def tags (clean-tags (vec-fold (fun (x acc) (vec-append acc (.tags x))) [] bs))) + (def archive (vec-fold (fun (x acc) (match acc ((Some a) (Some a)) (None (.archive x)))) None bs)) + (record-set b (tags tags) (added (.added (vec-ref bs 0))) (archive archive))) + +(: (-> Bookmark Bookmark bool)) +(defun (same? a b) + (and (= (.title a) (.title b)) + (= (.tags a) (.tags b)) + (= (instant->unix-microseconds (.added a)) (instant->unix-microseconds (.added b))) + (= (.archive a) (.archive b)))) + +;; The vault with `b`, unless it has it as it is. +(: (-> Vault Bookmark Bookmark Vault)) +(defun (put-changed v was b) + (if (same? was b) v (vault-put v b))) + +;; The bookmarks of one page as one, with `title`. +(: (-> Vault (Vec Bookmark) (Option string) Vault)) +(defun (join-group v bs title) + (def keep (vec-ref bs 0)) + (def j (joined keep bs)) + (def v2 (put-changed v keep (record-set j (title title)))) + (vec-fold (fun (b acc) (if (eq? b keep) acc (vault-delete acc (.id b)))) + v2 bs)) + +;; The vault with the bookmarks of each page as one, but for the pages whose +;; bookmarks have different titles: their bookmarks get the joined tags, +;; time and archive link, and the pages are returned, for the user to +;; choose a title. The vault is the same vault when there is nothing to +;; join. +(: (-> Vault (Tuple Vault (Vec Duplicate)))) +(defun (vault-join-duplicates v) + (vec-fold + (fun (bs acc) + (def (Tuple v asked) acc) + (def ts (titles bs)) + (if (<= (vec-length ts) 1) + (Tuple (join-group v bs (if (vec-empty? ts) None (Some (vec-ref ts 0)))) asked) + (Tuple (vec-fold (fun (b w) (put-changed w b (joined b bs))) v bs) + (vec-add asked (Duplicate (url (.url (vec-ref bs 0))) (titles ts) + (ids (vec-map (fun (b) (.id b)) bs))))))) + (Tuple v []) (groups v))) + +;; The vault with the bookmarks of the page `url` as one, with the title +;; `title`. The vault is the same when it has fewer than two bookmarks of +;; the page. +(: (-> Vault string (Option string) Vault)) +(defun (vault-choose-title v url title) + (def found (vec-filter (fun (bs) (= (.url (vec-ref bs 0)) url)) (groups v))) + (if (vec-empty? found) + v + (join-group v (vec-ref found 0) (match title ((Some t) (clean-title t)) (None None))))) diff --git a/src/import.bjo b/src/import.bjo new file mode 100644 index 0000000..a2f279d --- /dev/null +++ b/src/import.bjo @@ -0,0 +1,231 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/import.bjo — the module (bjomarks import): bookmarks from +;; Firefox, put in a vault. +;; +;; - `read-firefox-backup` reads the JSON backup that Firefox writes, named +;; bookmarks-YYYY-MM-DD.json: in Firefox's Library window, "Import and +;; Backup", then "Backup…". Not the HTML export. +;; - Only http and https addresses are read. The others, as Firefox's own +;; `place:` queries, `javascript:` bookmarklets and `about:` pages, are +;; counted and left out. +;; - An http or https address that is not a URL by RFC 3986 is left out +;; too, and named with the reason: a bookmark must be one. Browsers take +;; some of these, as a second "#" in the fragment. +;; - Each folder of the user's that holds a bookmark, at any depth, is a tag +;; of it. Firefox's top folders (the menu, the toolbar, "Other bookmarks", +;; "Mobile bookmarks") are not. Firefox's tags are tags too. +;; - A tag's name is lower-cased, and each run of white space and commas in +;; it is one "-": the dialog of bjomarks-gui splits tags at both. +;; - An address bookmarked more than once is one bookmark: with the tags of +;; all its copies, the earliest date, and the first title that is not +;; empty. +;; - `vault-import` adds the bookmarks whose address the vault does not +;; have. It changes no bookmark that is there. + +(export Imported FirefoxBackup read-firefox-backup tag-name ImportReport vault-import import-summary) + +(import (std prelude)) +(import (std datetime)) +(import (std url)) +(import (text json)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +(import/extern + ;; The input, a pattern and its replacement. + (clr-regex-replace (: System.Text.RegularExpressions.Regex.Replace (-> string string string string)))) + +;; A bookmark to import. +(type (: Imported (Record (: url string) + (: title (Option string)) + (: tags (Vec string)) + (: added Instant)))) + +;; What a backup holds: +;; - its bookmarks, one for each address, in the order that the backup +;; first has them; +;; - how many were left out because their address is not http or https; +;; - the http and https addresses that are not URLs, each with the reason; +;; - how many bookmarks were more copies of an address. +(type (: FirefoxBackup (Record (: bookmarks (Vec Imported)) + (: not-web int) + (: invalid (Vec (Tuple string string))) + (: copies int)))) + +;; `text` as a tag: lower case, each run of white space and commas one "-". +;; `None` when nothing is left. +(: (-> string (Option string))) +(defun (tag-name text) + (def spaced (string-trim (clr-regex-replace (string-downcase text) "[\\s,]+" " "))) + (if (string-empty? spaced) None (Some (string-replace spaced " " "-")))) + +(: (-> (Vec string) (Vec string))) +(defun (tag-names texts) + (vec-fold (fun (t acc) (match (tag-name t) ((Some n) (vec-add acc n)) (None acc))) [] texts)) + +;; True when `url` starts with http:// or https://, in any case. +(: (-> string bool)) +(defun (web-scheme? url) + (def lower (string-downcase url)) + (or (string-starts-with? lower "http://") (string-starts-with? lower "https://"))) + +;; Why `url` is not an absolute URL by RFC 3986, or `None` when it is one. +(: (-> string (Option string))) +(defun (url-problem url) + (match (parse-url url) + ((Ok u) (if (url-absolute? u) None (Some "it is not an absolute URL"))) + ((Err why) (Some why)))) + +(: (-> (IArray (Tuple string Json)) string (Option Json))) +(defun (field fields key) (json-object-ref (JsonFields fields) key)) + +(: (-> (IArray (Tuple string Json)) string (Option string))) +(defun (string-field fields key) + (match (field fields key) + ((Some (JsonStr s)) (Some s)) + (_ None))) + +;; --------------------------------------------------------------------------- +;; Reading a backup +;; --------------------------------------------------------------------------- + +;; What the walk has found so far: the addresses in the order first found, +;; the bookmark of each, and the rest of `FirefoxBackup`. +(type (: Walk (Record (: order (Vec string)) + (: found (Map string Imported)) + (: not-web int) + (: invalid (Vec (Tuple string string))) + (: copies int)))) + +(: Walk) +(def walk-start (Walk (order []) (found (map-empty)) (not-web 0) (invalid []) (copies 0))) + +;; Two copies of one address as one bookmark. +(: (-> Imported Imported Imported)) +(defun (joined first later) + (Imported (url (.url first)) + (title (match (.title first) ((Some t) (Some t)) (None (.title later)))) + (tags (clean-tags (vec-append (.tags first) (.tags later)))) + (added (if (< (instant->unix-microseconds (.added later)) (instant->unix-microseconds (.added first))) + (.added later) + (.added first))))) + +;; A bookmark of the backup, in the folders `folders`. +(: (-> (IArray (Tuple string Json)) (Vec string) Instant Walk Walk)) +(defun (place fields folders fallback w) + (def url (string-trim (option-ref-or (string-field fields "uri") ""))) + (def problem (if (web-scheme? url) (url-problem url) None)) + (cond + ((not (web-scheme? url)) (record-set w (not-web (+ (.not-web w) 1)))) + ((some? problem) (record-set w (invalid (vec-add (.invalid w) (Tuple url (option-ref problem)))))) + (else + (def own (match (string-field fields "tags") ((Some t) (tag-names (string-split t ","))) (None []))) + (def item (Imported (url url) + (title (match (string-field fields "title") ((Some t) (clean-title t)) (None None))) + (tags (clean-tags (vec-append folders own))) + (added (match (field fields "dateAdded") + ((Some (JsonInt us)) (option-ref-or (unix-microseconds->instant us) fallback)) + (_ fallback))))) + (match (map-try-ref (.found w) url) + ((Some old) (record-set w (found (map-set (.found w) url (joined old item))) (copies (+ (.copies w) 1)))) + (None (record-set w (order (vec-add (.order w) url)) (found (map-set (.found w) url item)))))))) + +;; A node of the backup, and all under it. `folders` are the tags of the +;; folders that hold it. A folder with a "root" field is one of Firefox's. +(: (-> Json (Vec string) Instant Walk Walk)) +(defun (walk node folders fallback w) + (match node + ((JsonFields fields) + (match (string-field fields "type") + ((Some "text/x-moz-place-container") + (def inner (match (Tuple (field fields "root") (string-field fields "title")) + ((Tuple (Some _) _) folders) + ((Tuple None (Some t)) (match (tag-name t) ((Some n) (vec-add folders n)) (None folders))) + (_ folders))) + (match (field fields "children") + ((Some (JsonArr kids)) + (let go ((i 0) (w w)) + (if (= i (iarray-length kids)) + w + (go (+ i 1) (walk (iarray-ref kids i) inner fallback w))))) + (_ w))) + ((Some "text/x-moz-place") (place fields folders fallback w)) + ;; Separators, and kinds that this version does not know. + (_ w))) + (_ w))) + +;; The bookmarks of a Firefox JSON backup, or why `text` is not one. A +;; bookmark with no date gets `#:now`. +(: (-> string (#:now Instant) (Result string FirefoxBackup))) +(defun (read-firefox-backup text #:now (now)) + (if (string-starts-with? (string-trim text) "<") + (Err (str "this is Firefox's HTML export, and bjomarks reads the JSON backup: in Firefox's " + "Library window, choose Import and Backup, then Backup…")) + (match (parse-json text #:objects 'fields) + ((Err why) (Err (str "not JSON: " why))) + ((Ok (JsonFields fields)) + (match (string-field fields "type") + ((Some "text/x-moz-place-container") + (def w (walk (JsonFields fields) [] now walk-start)) + (Ok (FirefoxBackup (bookmarks (vec-map (fun (u) (map-ref (.found w) u)) (.order w))) + (not-web (.not-web w)) + (invalid (.invalid w)) + (copies (.copies w))))) + (_ (Err "not a Firefox bookmark backup: it has no top folder")))) + ((Ok _) (Err "not a Firefox bookmark backup: it is not an object"))))) + +;; --------------------------------------------------------------------------- +;; Into a vault +;; --------------------------------------------------------------------------- + +;; How an import went: how many bookmarks were added, how many the vault +;; had already (by address), and why the others, if any, were refused. +(type (: ImportReport (Record (: added int) + (: already int) + (: refused (Vec string))))) + +;; The vault with each bookmark of `items` whose address it does not have +;; yet. A bookmark that the vault has is not changed. +(: (-> Vault (Vec Imported) (Tuple Vault ImportReport))) +(defun (vault-import v items) + (def present (vec-fold (fun (b s) (map-set s (.url b) #t)) (map-empty) (vault-bookmarks v))) + (let go ((i 0) (v v) (present present) (added 0) (already 0) (refused [])) + (if (= i (vec-length items)) + (Tuple v (ImportReport (added added) (already already) (refused refused))) + (let ((item (vec-ref items i))) + (if (some? (map-try-ref present (.url item))) + (go (+ i 1) v present added (+ already 1) refused) + (match (vault-add v (.url item) #:title (.title item) #:tags (.tags item) #:added (.added item)) + ((Ok (Tuple v2 _)) (go (+ i 1) v2 (map-set present (.url item) #t) (+ added 1) already refused)) + ((Err why) (go (+ i 1) v present added already (vec-add refused why))))))))) + +;; "1 bookmark", "2 bookmarks". +(: (-> int string string string)) +(defun (counted n one many) (str (int->string n) " " (if (= n 1) one many))) + +;; What an import from the file `name` did, for the user: the bookmarks +;; added, and those that were here already, joined, or left out. +(: (-> string FirefoxBackup ImportReport string)) +(defun (import-summary name backup report) + (def parts + [(str "Imported " (counted (.added report) "bookmark" "bookmarks") " from " name ".") + (if (> (.already report) 0) + (str (counted (.already report) "was" "were") " here already.") + "") + (if (> (.copies backup) 0) + (str (counted (.copies backup) "second copy was" "more copies were") " joined to the first.") + "") + (if (> (.not-web backup) 0) + (str (counted (.not-web backup) "is not a web address" "are not web addresses") ", and left out.") + "") + (match (vec-length (.invalid backup)) + (0 "") + (1 (str "Left out, as not a URL: " (fst (vec-ref (.invalid backup) 0)) ".")) + (n (str (int->string n) " are not URLs, and left out; the first: " (fst (vec-ref (.invalid backup) 0)) "."))) + (match (vec-length (.refused report)) + (0 "") + (n (str (counted n "was" "were") " refused: " (vec-ref (.refused report) 0))))]) + (string-join (vec-filter (fun (s) (not (string-empty? s))) parts) " ")) diff --git a/src/keys.bjo b/src/keys.bjo new file mode 100644 index 0000000..930e19b --- /dev/null +++ b/src/keys.bjo @@ -0,0 +1,345 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/keys.bjo — the module (bjomarks keys): `keys.bin`, the file +;; that holds the key of a vault, encrypted with keys made from passwords. +;; +;; - A vault has one data key (DEK): 32 random bytes that encrypt every +;; device's file. +;; - `keys.bin` holds the DEK wrapped (encrypted) in one or more slots. A +;; password slot wraps it with a key (KEK) that Argon2id makes from the +;; password and the slot's salt and cost. +;; - A new password comes with a new DEK, with a new key id: an old copy of +;; `keys.bin` and the old password then open only what was written before +;; the change. The earlier DEKs stay in `keys.bin`, each wrapped with the +;; current DEK in a slot of its own, so that the files written with them +;; still open. +;; - The file is not secret. An attacker who has it must run Argon2id at the +;; slot's cost for each password they try. +;; +;; The layout, version 1. Integers are big-endian. +;; +;; offset size field +;; 0 4 "BMKV" +;; 4 2 version: 1 +;; 6 16 vault id +;; 22 1 number of slots, from 1 +;; 23 the slots, one after the other +;; +;; A password slot: +;; 0 1 kind: 1 = password +;; 1 4 key id: the DEK that the slot wraps +;; 5 1 kdf: 1 = Argon2id +;; 6 4 iterations +;; 10 4 memory, in KiB +;; 14 16 salt +;; 30 1 cipher: 1 = AEGIS-256, 2 = XChaCha20-Poly1305 +;; 31 n nonce, as long as the cipher's +;; 31+n 32+t the DEK, encrypted, and the tag +;; +;; A slot of an earlier key, the same length: +;; 0 1 kind: 2 = an earlier key +;; 1 4 key id: the earlier DEK that the slot holds +;; 5 1 kdf: 0 = none +;; 6 4 the key id of the DEK that wraps it: the current one +;; 10 20 zeros +;; 30 1 cipher +;; 31 n nonce +;; 31+n 32+t the earlier DEK, encrypted with the current DEK, and the tag +;; +;; The associated data of a slot's encryption is bytes 0 to 21 of the file +;; and bytes 0 to 30 of the slot. A change to the vault id, the cost or the +;; salt makes the slot fail to open. +;; +;; The password slots come first, and all wrap the same DEK: the current +;; one. The earlier keys follow, the latest first. A version that knows only +;; password slots skips the others: it opens the vault, but not the files +;; written with an earlier key. + +(export + KeyCost default-key-cost + Unlocked KeysError KeyIds + keys-file-name make-keys wrap-keys unlock-keys keys-vault-id keys-key-ids new-keys) + +(import (std prelude)) +(import (std uuid)) +(import (bjosodium core)) +(import (bjomarks binary)) + +(: string) +(def keys-file-name "keys.bin") + +;; The cost of Argon2id for a password slot. +(type (: KeyCost (Record (: iterations int) + (: memory-kib int)))) + +;; 3 iterations over 64 MiB: about 75 ms on a desktop CPU of 2020. Measure +;; on the slowest device, and choose more if it allows. +(: KeyCost) +(def default-key-cost (KeyCost (iterations 3) (memory-kib 65536))) + +;; What a slot that opened gives: the current DEK, and the earlier ones, +;; each with its key id, the latest first. +(type (: Unlocked (Record (: vault-id Uuid) + (: key-id int) + (: dek (Array byte)) + (: earlier (Vec (Tuple int (Array byte))))))) + +;; The key ids of a keys file, which it shows without a password: the +;; current one, and the earlier ones, the latest first. +(type (: KeyIds (Record (: current int) + (: earlier-ids (Vec int))))) + +(type (: KeysError (Union + ;; No password slot opened with the password. + WrongPassword + ;; The bytes are not a keys file that this version reads. + (: BadKeys string)))) + +(: (Array byte)) +(def magic (string->bytes "BMKV")) + +(: int) +(def keys-version 1) + +(: int) +(def header-length 23) + +;; The part of a slot before its nonce. +(: int) +(def slot-head-length 31) + +(: int) +(def dek-length 32) + +;; Bounds on a cost read from a file. A file can come from an attacker, and a +;; cost far above these would stop a device for minutes or use all its +;; memory. +(: int) +(def max-iterations 100) + +(: int) +(def max-memory-kib 1048576) + +;; Each slot that is tried costs a run of Argon2id. +(: int) +(def max-password-slots 4) + +;; The earlier keys that a new keys file keeps: the oldest go first. A file +;; has at most 255 slots. +(: int) +(def max-earlier-keys 200) + +(: (-> Cipher int)) +(defun (slot-length cipher) #fl(+ slot-head-length (cipher-nonce-length cipher) dek-length (cipher-tag-length cipher))) + +;; The DEK, wrapped for `password` in a new slot, as the whole of a keys +;; file with that one password slot, and a slot for each of the `#:earlier` +;; keys, wrapped with the DEK. +(: (-> Uuid int (Array byte) string (#:cost KeyCost) (#:cipher Cipher) + (#:earlier (Vec (Tuple int (Array byte)))) + (Array byte))) +(defun (wrap-keys vault-id key-id dek password #:cost default-key-cost #:cipher (preferred-cipher) + #:earlier []) + (def kept (vec-take earlier max-earlier-keys)) + (def nonce-length (cipher-nonce-length cipher)) + (def file (: (make-array (+ header-length (* (+ 1 (vec-length kept)) (slot-length cipher)))) (Array byte))) + (put-bytes! file 0 magic) + (put-u16! file 4 keys-version) + (put-bytes! file 6 (uuid->bytes vault-id)) + (put-u8! file 22 (+ 1 (vec-length kept))) + (def at header-length) + (def salt (make-argon2id-salt)) + (def nonce (make-aead-nonce cipher)) + (put-u8! file at 1) + (put-u32! file (+ at 1) key-id) + (put-u8! file (+ at 5) 1) + (put-u32! file (+ at 6) (.iterations cost)) + (put-u32! file (+ at 10) (.memory-kib cost)) + (put-bytes! file (+ at 14) salt) + (put-u8! file (+ at 30) (cipher->code cipher)) + (put-bytes! file (+ at slot-head-length) nonce) + (def aad (bytes-concat (get-bytes file 0 22) (get-bytes file at slot-head-length))) + (def kek (argon2id-derive-key password salt #:iterations (.iterations cost) #:memory-kib (.memory-kib cost))) + (def wrapped (try (aead-encrypt cipher kek nonce dek #:aad aad) #:finally (wipe! kek))) + (put-bytes! file (+ at slot-head-length nonce-length) wrapped) + (loop (:for (Tuple i old) (enumerate kept)) + (:do (def (Tuple old-id old-dek) old) + (def there (+ header-length (* (+ i 1) (slot-length cipher)))) + (def old-nonce (make-aead-nonce cipher)) + (put-u8! file there 2) + (put-u32! file (+ there 1) old-id) + (put-u8! file (+ there 5) 0) + (put-u32! file (+ there 6) key-id) + (put-u8! file (+ there 30) (cipher->code cipher)) + (put-bytes! file (+ there slot-head-length) old-nonce) + (def old-aad (bytes-concat (get-bytes file 0 22) (get-bytes file there slot-head-length))) + (put-bytes! file (+ there slot-head-length nonce-length) + (aead-encrypt cipher dek old-nonce old-dek #:aad old-aad)))) + file) + +;; A new vault: a new vault id and a new DEK, with key id 1, and its keys +;; file with one password slot. +(: (-> string (#:cost KeyCost) (#:cipher Cipher) (Tuple (Array byte) Unlocked))) +(defun (make-keys password #:cost default-key-cost #:cipher (preferred-cipher)) + (def vault-id (uuid-v4)) + (def dek (make-aead-key XChaCha20Poly1305)) + (Tuple (wrap-keys vault-id 1 dek password #:cost cost #:cipher cipher) + (Unlocked (vault-id vault-id) (key-id 1) (dek dek) (earlier [])))) + +;; A key id that is none of `known`: random, so that two devices that make +;; a new key at once do not give theirs the same id. +(: (-> (Vec int) int)) +(defun (new-key-id known) + (def id (get-u32 (make-aead-key XChaCha20Poly1305) 0)) + (if (or (<= id 1) (vec-contains? known id)) (new-key-id known) id)) + +;; A new DEK for the vault of `u`, for a new password: its keys file, and +;; what it unlocks. The DEK of `u` and its earlier ones become the earlier +;; keys. +(: (-> Unlocked string (#:cost KeyCost) (#:cipher Cipher) (Tuple (Array byte) Unlocked))) +(defun (new-keys u password #:cost default-key-cost #:cipher (preferred-cipher)) + (def earlier (vec-append [(Tuple (.key-id u) (.dek u))] (.earlier u))) + (def key-id (new-key-id (vec-map fst earlier))) + (def dek (make-aead-key XChaCha20Poly1305)) + (def kept (vec-take earlier max-earlier-keys)) + (Tuple (wrap-keys (.vault-id u) key-id dek password #:cost cost #:cipher cipher #:earlier kept) + (Unlocked (vault-id (.vault-id u)) (key-id key-id) (dek dek) (earlier kept)))) + +;; The vault id of a keys file, or why the bytes are not one. Needs no +;; password. +(: (-> (Array byte) (Result KeysError Uuid))) +(defun (keys-vault-id file) + (cond + ((< (array-length file) header-length) (Err (BadKeys "too short for a keys file"))) + ((not (bytes-at? file 0 magic)) (Err (BadKeys "not a keys file"))) + ((not (= (get-u16 file 4) keys-version)) + (Err (BadKeys (str "keys file version " (int->string (get-u16 file 4)) " is not version " + (int->string keys-version))))) + (else (match (bytes->uuid (get-bytes file 6 16)) + ((Some id) (Ok id)) + (None (Err (BadKeys "no vault id"))))))) + +;; A slot as read, before it is opened. +(type (: Slot (Record (: kind int) + (: slot-key-id int) + (: kdf int) + (: cost KeyCost) + (: salt (Array byte)) + (: cipher Cipher) + (: aad (Array byte)) + (: nonce (Array byte)) + (: wrapped (Array byte))))) + +;; The slot at `at`, and where the next one starts, or why it is not a slot. +(: (-> (Array byte) int (Result KeysError (Tuple Slot int)))) +(defun (read-slot file at) + (def n (array-length file)) + (cond + ((> (+ at slot-head-length) n) (Err (BadKeys "a slot is cut short"))) + (:def code (get-u8 file (+ at 30))) + (:def (Some cipher) (code->cipher code) :leave-with (Err (BadKeys (str "unknown cipher " (int->string code))))) + (:def length (slot-length cipher)) + ((> (+ at length) n) (Err (BadKeys "a slot is cut short"))) + (else + (def nonce-length (cipher-nonce-length cipher)) + (Ok (Tuple (Slot (kind (get-u8 file at)) + (slot-key-id (get-u32 file (+ at 1))) + (kdf (get-u8 file (+ at 5))) + (cost (KeyCost (iterations (get-u32 file (+ at 6))) (memory-kib (get-u32 file (+ at 10))))) + (salt (get-bytes file (+ at 14) 16)) + (cipher cipher) + (aad (bytes-concat (get-bytes file 0 22) (get-bytes file at slot-head-length))) + (nonce (get-bytes file (+ at slot-head-length) nonce-length)) + (wrapped (get-bytes file (+ at slot-head-length nonce-length) + (+ dek-length (cipher-tag-length cipher))))) + (+ at length)))))) + +(: (-> (Array byte) int (Result KeysError (Vec Slot)))) +(defun (read-slots file count) + (let go ((i 0) (at header-length) (out [])) + (cond + ((= i count) + (if (= at (array-length file)) (Ok out) (Err (BadKeys "bytes after the last slot")))) + (:def (Ok (Tuple slot next)) (read-slot file at) :propagate) + (else (go (+ i 1) next (vec-add out slot)))))) + +(: (-> Slot (Result KeysError KeyCost))) +(defun (checked-cost slot) + (def cost (.cost slot)) + (cond + ((or (< (.iterations cost) 1) (> (.iterations cost) max-iterations)) + (Err (BadKeys (str "a slot asks for " (int->string (.iterations cost)) " iterations")))) + ((or (< (.memory-kib cost) 8) (> (.memory-kib cost) max-memory-kib)) + (Err (BadKeys (str "a slot asks for " (int->string (.memory-kib cost)) " KiB")))) + (else (Ok cost)))) + +;; The DEK of a password slot, or `None` when the password does not open it. +(: (-> Slot string KeyCost (Option (Array byte)))) +(defun (open-slot slot password cost) + (def kek (argon2id-derive-key password (.salt slot) #:iterations (.iterations cost) + #:memory-kib (.memory-kib cost))) + (try (aead-decrypt (.cipher slot) kek (.nonce slot) (.wrapped slot) #:aad (.aad slot)) + #:finally (wipe! kek))) + +;; The vault id, the key id and the DEK, from the first password slot that +;; `password` opens. +;; - `WrongPassword` when no password slot opens. +;; - `BadKeys` when the bytes are not a keys file of this version, when no +;; slot is a password slot, or when a cost is out of bounds. +(: (-> (Array byte) string (Result KeysError Unlocked))) +(defun (unlock-keys file password) + (def (Ok vault-id) (keys-vault-id file) :propagate) + (def count (get-u8 file 22)) + (def (Ok slots) (read-slots file count) :propagate) + (def passwords (vec-filter (fun (s) (and (= (.kind s) 1) (= (.kdf s) 1))) slots)) + ;; The earlier keys that the DEK `key-id` wraps, or why one does not open. + (: (-> int (Array byte) (Result KeysError (Vec (Tuple int (Array byte)))))) + (defun (earlier-of key-id dek) + (let go ((i 0) (out [])) + (if (= i (vec-length slots)) + (Ok out) + (let ((s (vec-ref slots i))) + (if (and (= (.kind s) 2) (= (get-u32 (.aad s) 28) key-id)) + (match (aead-decrypt (.cipher s) dek (.nonce s) (.wrapped s) #:aad (.aad s)) + ((Some old) #:when (= (array-length old) dek-length) + (go (+ i 1) (vec-add out (Tuple (.slot-key-id s) old)))) + (_ (Err (BadKeys (str "the earlier key " (int->string (.slot-key-id s)) " does not open"))))) + (go (+ i 1) out)))))) + (cond + ((vec-empty? passwords) (Err (BadKeys "no password slot"))) + ((> (vec-length passwords) max-password-slots) + (Err (BadKeys (str "more than " (int->string max-password-slots) " password slots")))) + (else + (let go ((i 0)) + (if (= i (vec-length passwords)) + (Err WrongPassword) + (let ((slot (vec-ref passwords i))) + (match (checked-cost slot) + ((Err why) (Err why)) + ((Ok cost) + (match (open-slot slot password cost) + ((Some dek) + (if (= (array-length dek) dek-length) + (match (earlier-of (.slot-key-id slot) dek) + ((Ok earlier) + (Ok (Unlocked (vault-id vault-id) (key-id (.slot-key-id slot)) (dek dek) (earlier earlier)))) + ((Err why) (Err why))) + (Err (BadKeys "the key in a slot has the wrong length")))) + (None (go (+ i 1)))))))))))) + +;; The key ids of a keys file: those of its password slots, which must be +;; the same, and those of its earlier keys. Needs no password. +(: (-> (Array byte) (Result KeysError KeyIds))) +(defun (keys-key-ids file) + (def (Ok _vault) (keys-vault-id file) :propagate) + (def (Ok slots) (read-slots file (get-u8 file 22)) :propagate) + (def passwords (vec-map (fun (s) (.slot-key-id s)) (vec-filter (fun (s) (= (.kind s) 1)) slots))) + (def earlier (vec-map (fun (s) (.slot-key-id s)) (vec-filter (fun (s) (= (.kind s) 2)) slots))) + (cond + ((vec-empty? passwords) (Err (BadKeys "no password slot"))) + ((not (vec-empty? (vec-filter (fun (id) (not (= id (vec-ref passwords 0)))) passwords))) + (Err (BadKeys "the password slots wrap different keys"))) + (else (Ok (KeyIds (current (vec-ref passwords 0)) (earlier-ids earlier)))))) + diff --git a/src/search.bjo b/src/search.bjo new file mode 100644 index 0000000..6161084 --- /dev/null +++ b/src/search.bjo @@ -0,0 +1,435 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/search.bjo — the module (bjomarks search): the search of the +;; list of bookmarks. +;; +;; A search is terms, separated by spaces. A bookmark is shown when it +;; matches each of them. +;; +;; - A word, such as `rust`, is in the title, the address or a tag. It may be +;; a whole word there, the start of one, inside one, or have a typo: one in +;; a word of 4 to 7 letters, two in a longer one. A swap of two letters +;; side by side is one typo. +;; - `t:rust`, or `tag:rust`: the bookmark has the tag "rust", the whole tag. +;; - `d:github` is in the domain of the address, and `d:github.com` is the +;; domain or one under it, such as gist.github.com. "www." before the +;; domain is not part of it. +;; - `a:2012-06` is the day the bookmark was added: a year, a month or a day. +;; `a:2011:2012-06` is from the first day of the first to the last day of +;; the second. `a:2011:` has no end and `a::2012` no start. The days are +;; in the time zone of the clock, as the list shows them. +;; - `"two words"` is that text, exactly, in the title, the address or a tag. +;; `t:"c#"` and `d:"x"` may be quoted too. +;; - `-` before a term: the bookmark must not match it. `-word` is exact, as +;; a quoted text is. +;; +;; The case of letters never matters, and accents are not looked at: "cafe" +;; finds "café". But å, ä, ö, æ and ø are letters of their own. Only words +;; are forgiven typos; the other terms are exact. +;; +;; With words, the bookmarks come in the order of how well they match: a +;; whole word first, then the start of a word, then a word that has it +;; inside, then a typo. Of each, the title first, then the tags, then the +;; address. Otherwise, and between bookmarks that match as well, the newest +;; first. +;; +;; A date that is not one, such as `a:2012-13`, matches nothing, and +;; `query-problem` says why. + +(export + Query Term parse-query query-empty? query-problem matches? search-bookmarks + fold-text typos) + +(import (std prelude)) +(import (std datetime)) +(import (bjomarks bookmark)) +(import (bjomarks store)) + +;; --------------------------------------------------------------------------- +;; Text +;; --------------------------------------------------------------------------- + +;; The letters with accents that a search does not tell from the letter +;; without. Not å, ä, ö, æ or ø: in Swedish, Norwegian and Danish they are +;; letters of their own. +(: (Vec (Tuple string string))) +(def accented + [(Tuple "àáâãāăą" "a") (Tuple "çćč" "c") (Tuple "ďđ" "d") (Tuple "èéêëēėęě" "e") + (Tuple "ğ" "g") (Tuple "ìíîïīį" "i") (Tuple "ł" "l") (Tuple "ñńň" "n") + (Tuple "òóôõōő" "o") (Tuple "řŕ" "r") (Tuple "śšş" "s") (Tuple "ťţ" "t") + (Tuple "ùúûüūůű" "u") (Tuple "ýÿ" "y") (Tuple "źżž" "z")]) + +(: (-> char string)) +(defun (fold-char c) + (def s (char->string c)) + (def found (vec-filter (fun (p) (string-contains? (fst p) s)) accented)) + (if (vec-empty? found) s (snd (vec-ref found 0)))) + +;; `s` as a search compares it: in lower case, with the accents of +;; `accented` taken away. +(: (-> string string)) +(defun (fold-text s) + (def low (string-downcase s)) + (if (vec-empty? (vec-filter (fun (c) (> (char->int c) 127)) (string->vec low))) + low + (string-join (vec-map fold-char (string->vec low)) ""))) + +(: (-> char bool)) +(defun (word-char? c) (or (char-alphabetic? c) (char-numeric? c))) + +;; The words of `s`: its runs of letters and digits. +(: (-> string (Vec string))) +(defun (words-of s) + (def (Tuple done current) + (vec-fold (fun (c acc) + (def (Tuple ws w) acc) + (if (word-char? c) + (Tuple ws (str w (char->string c))) + (Tuple (if (string-empty? w) ws (vec-add ws w)) ""))) + (Tuple [] "") (string->vec s))) + (if (string-empty? current) done (vec-add done current))) + +;; How many typos make `a` of `b`: a letter added, taken away, changed, or +;; two side by side swapped. Counts no further than `most` + 1. +(: (-> string string int int)) +(defun (typos a b most) + (def x (string->vec a)) + (def y (string->vec b)) + (def n (vec-length x)) + (def m (vec-length y)) + (if (> (abs (- n m)) most) + (+ most 1) + (let () + (def width (+ m 1)) + (def d (make-array (* (+ n 1) width) #:fill 0)) + (defun (at i j) (array-ref d (+ (* i width) j))) + (defun (put! i j v) (array-set! d (+ (* i width) j) v)) + (for-each (fun (i) (put! i 0 i)) (range 0 (+ n 1))) + (for-each (fun (j) (put! 0 j j)) (range 0 (+ m 1))) + (for-each + (fun (i) + (for-each + (fun (j) + (def cost (if (char=? (vec-ref x (- i 1)) (vec-ref y (- j 1))) 0 1)) + (def best (min (min (+ (at (- i 1) j) 1) (+ (at i (- j 1)) 1)) (+ (at (- i 1) (- j 1)) cost))) + (put! i j (if (and (> i 1) (> j 1) + (char=? (vec-ref x (- i 1)) (vec-ref y (- j 2))) + (char=? (vec-ref x (- i 2)) (vec-ref y (- j 1)))) + (min best (+ (at (- i 2) (- j 2)) 1)) + best))) + (range 1 (+ m 1)))) + (range 1 (+ n 1))) + (min (at n m) (+ most 1))))) + +;; How many typos a word of `n` letters may have. +(: (-> int int)) +(defun (typos-allowed n) + (cond ((< n 4) 0) ((< n 8) 1) (else 2))) + +;; --------------------------------------------------------------------------- +;; The query +;; --------------------------------------------------------------------------- + +;; - `Text` is a quoted text, or a word after `-`: exactly that. +;; - `Tag` and `Domain` are folded with `fold-text`. +;; - `Added` is the first and the last day, each when there is one. +;; - `NoDate` is a date that is not one: it matches nothing. +(type (: Term (Union (: Text string) + (: Tag string) + (: Domain string) + (: Added (Option Date) (Option Date)) + (: NoDate string)))) + +;; A search: the words, the terms that a bookmark must match, and those that +;; it must not. +(type (: Query (Record (: words (Vec string)) + (: must (Vec Term)) + (: must-not (Vec Term))))) + +;; The pieces of `text`, split at spaces outside quotes. A quote is kept in +;; its piece. +(: (-> string (Vec string))) +(defun (pieces text) + (def (Tuple done current _) + (vec-fold (fun (c acc) + (def (Tuple ps p quoted) acc) + (cond + ((char=? c #\") (Tuple ps (str p "\"") (not quoted))) + ((and (not quoted) (char-whitespace? c)) + (Tuple (if (string-empty? p) ps (vec-add ps p)) "" #f)) + (else (Tuple ps (str p (char->string c)) quoted)))) + (Tuple [] "" #f) (string->vec text))) + (if (string-empty? current) done (vec-add done current))) + +;; `s` without its quotes, and whether it had any. +(: (-> string (Tuple string bool))) +(defun (unquoted s) + (if (string-contains? s "\"") + (Tuple (string-replace s "\"" "") #t) + (Tuple s #f))) + +(: (-> string bool)) +(defun (digits? s) + (and (not (string-empty? s)) (vec-empty? (vec-filter (fun (c) (not (char-numeric? c))) (string->vec s))))) + +;; The first and the last day of a year, a month or a day. +(: (-> string (Option (Tuple Date Date)))) +(defun (day-span s) + (def parts (string-split s "-")) + (def lengths (vec-map string-length parts)) + (cond + ((not (vec-empty? (vec-filter (fun (p) (not (digits? p))) parts))) None) + ((= lengths [4]) + (def y (string->int (vec-ref parts 0))) + (match (Tuple (date y 1 1) (date y 12 31)) + ((Tuple (Some a) (Some b)) (Some (Tuple a b))) + (_ None))) + ((= lengths [4 2]) + (match (date (string->int (vec-ref parts 0)) (string->int (vec-ref parts 1)) 1) + ((Some a) (Some (Tuple a (-days (+months a 1) 1)))) + (None None))) + ((= lengths [4 2 2]) + (match (date (string->int (vec-ref parts 0)) (string->int (vec-ref parts 1)) (string->int (vec-ref parts 2))) + ((Some a) (Some (Tuple a a))) + (None None))) + (else None))) + +;; The term of `a:` and what is after it, or `None` when nothing is. +(: (-> string (Option Term))) +(defun (added-term s) + (def ends (string-split s ":")) + (defun (end text first?) + (if (string-empty? text) + (Some None) + (match (day-span text) + ((Some (Tuple a b)) (Some (Some (if first? a b)))) + (None None)))) + (match (vec-length ends) + (1 (if (string-empty? s) + None + (match (day-span s) + ((Some (Tuple a b)) (Some (Added (Some a) (Some b)))) + (None (Some (NoDate s)))))) + (2 (match (Tuple (end (vec-ref ends 0) #t) (end (vec-ref ends 1) #f)) + ((Tuple (Some None) (Some None)) None) + ((Tuple (Some a) (Some b)) (Some (Added a b))) + (_ (Some (NoDate s))))) + (_ (Some (NoDate s))))) + +(: (-> string string (Option string))) +(defun (after prefix s) + (if (string-starts-with? s prefix) (Some (string-drop s (string-count prefix))) None)) + +;; The term of a piece, without its `-`; `None` when it asks for nothing, +;; such as `t:`. A word is `Ok`, the other terms `Err`. +(: (-> string (Option (Result string Term)))) +(defun (piece-term p) + (def tagged (match (after "t:" p) ((Some v) (Some v)) (None (after "tag:" p)))) + (def domain (after "d:" p)) + (def added (after "a:" p)) + (cond + ((some? tagged) + (def (Tuple v _) (unquoted (option-ref-or tagged ""))) + (if (string-empty? v) None (Some (Ok (Tag (fold-text v)))))) + ((some? domain) + (def (Tuple v _) (unquoted (option-ref-or domain ""))) + (def d (fold-text v)) + (if (string-empty? d) None (Some (Ok (Domain (option-ref-or (after "www." d) d)))))) + ((some? added) + (match (added-term (option-ref-or added "")) + ((Some t) (Some (Ok t))) + (None None))) + (else + (def (Tuple v quoted) (unquoted p)) + (def f (fold-text v)) + (cond + ((string-empty? (string-trim f)) None) + (quoted (Some (Ok (Text f)))) + (else (Some (Err f))))))) + +;; The search in `text`. +(: (-> string Query)) +(defun (parse-query text) + (vec-fold + (fun (p q) + (def negated (and (string-starts-with? p "-") (> (string-count p) 1))) + (def body (if negated (string-drop p 1) p)) + (match (if (= p "-") None (piece-term body)) + (None q) + ((Some (Ok t)) (if negated + (record-set q (must-not (vec-add (.must-not q) t))) + (record-set q (must (vec-add (.must q) t))))) + ((Some (Err w)) + (if negated + (record-set q (must-not (vec-add (.must-not q) (Text w)))) + ;; A word of signs only, such as "&", is looked for as text. + (let ((ws (words-of w))) + (if (vec-empty? ws) + (record-set q (must (vec-add (.must q) (Text w)))) + (record-set q (words (vec-append (.words q) ws))))))))) + (Query (words []) (must []) (must-not [])) + (pieces text))) + +;; True when the search asks for nothing: then every bookmark is shown. +(: (-> Query bool)) +(defun (query-empty? q) + (and (vec-empty? (.words q)) (vec-empty? (.must q)) (vec-empty? (.must-not q)))) + +;; What is wrong with the search, or "". +(: (-> Query string)) +(defun (query-problem q) + (def bad (vec-fold (fun (t acc) (match t ((NoDate s) (vec-add acc s)) (_ acc))) + [] (vec-append (.must q) (.must-not q)))) + (if (vec-empty? bad) "" (str "Not a date: " (string-join bad ", ")))) + +;; --------------------------------------------------------------------------- +;; Matching +;; --------------------------------------------------------------------------- + +;; A bookmark as the search looks at it: the words of its title, its tags +;; and its address, folded; its text; its domain; and the day it was added. +(type (: Seen (Record (: bookmark Bookmark) + (: title-words (Vec string)) + (: tags (Vec string)) + (: tag-words (Vec string)) + (: url-words (Vec string)) + (: text string) + (: domain string) + (: day Date)))) + +;; The domain of an address, folded, without "www.". +(: (-> string string)) +(defun (domain-of url) + (def rest (match (string-split-once url "://") ((Some (Tuple _ r)) r) (None url))) + (def host (vec-fold (fun (sep h) (match (string-split-once h sep) ((Some (Tuple a _)) a) (None h))) + rest ["/" "?" "#"])) + (def no-user (match (string-split-once host "@") ((Some (Tuple _ h)) h) (None host))) + (def no-port (match (string-split-once no-user ":") ((Some (Tuple h _)) h) (None no-user))) + (def d (fold-text no-port)) + (option-ref-or (after "www." d) d)) + +(: (-> Bookmark TimeZone Seen)) +(defun (seen b zone) + (def title (fold-text (option-ref-or (.title b) ""))) + (def url (fold-text (.url b))) + (def tags (vec-map fold-text (.tags b))) + (def url-words (vec-filter (fun (w) (not (or (= w "https") (= w "http") (= w "www")))) (words-of url))) + (Seen (bookmark b) (title-words (words-of title)) (tags tags) + (tag-words (vec-fold (fun (t acc) (vec-append acc (words-of t))) [] tags)) + (url-words url-words) + (text (string-join (vec-append [title url] tags) "\n")) + (domain (domain-of (.url b))) + (day (->date (instant->moment (.added b) zone))))) + +;; How well the word `w` matches the word `t`: 100 for the whole word, 80 +;; for its start, 60 for a part of it, 40 less 10 for each typo, 0 for not. +(: (-> string string int)) +(defun (word-score w t) + (cond + ((= w t) 100) + ((string-starts-with? t w) 80) + ((string-contains? t w) 60) + (else + (def most (typos-allowed (string-count w))) + (if (= most 0) + 0 + (let ((n (min (typos w t most) (typos w (string-take t (string-count w)) most)))) + (if (<= n most) (- 40 (* 10 n)) 0)))))) + +;; The best score of `w` in `ws`, with `bonus` when it is above 0. +(: (-> string (Vec string) int int)) +(defun (best-in w ws bonus) + (def best (vec-fold (fun (t acc) (max acc (word-score w t))) 0 ws)) + (if (> best 0) (+ best bonus) 0)) + +;; How well the word `w` matches the bookmark, 0 when not: a match in the +;; title is worth more than one in the tags, and that more than one in the +;; address. +(: (-> string Seen int)) +(defun (score-word w s) + (max (best-in w (.title-words s) 20) + (max (best-in w (.tag-words s) 10) (best-in w (.url-words s) 0)))) + +(: (-> Term Seen bool)) +(defun (term-matches? t s) + (match t + ((Text x) (string-contains? (.text s) x)) + ((Tag x) (vec-contains? (.tags s) x)) + ((Domain x) + (if (string-contains? x ".") + (or (= (.domain s) x) (string-ends-with? (.domain s) (str "." x))) + (string-contains? (.domain s) x))) + ((Added from to) + (and (match from ((Some a) (>= (compare (.day s) a) 0)) (None #t)) + (match to ((Some b) (<= (compare (.day s) b) 0)) (None #t)))) + ((NoDate _) #f))) + +;; The score of the bookmark for the search: `None` when it does not match. +(: (-> Query Seen (Option int))) +(defun (score q s) + (cond + ((not (vec-empty? (vec-filter (fun (t) (not (term-matches? t s))) (.must q)))) None) + ((not (vec-empty? (vec-filter (fun (t) (term-matches? t s)) (.must-not q)))) None) + (else + (vec-fold (fun (w acc) + (match acc + ((Some total) (let ((n (score-word w s))) (if (= n 0) None (Some (+ total n))))) + (None None))) + (Some 0) (.words q))))) + +;; True when the bookmark matches the search. +(: (-> Query Bookmark bool)) +(defun (matches? q b) (some? (score q (seen b (clock-timezone))))) + +;; The bookmarks of the last vault searched, as the search looks at them: +;; made once for each vault, not for each letter typed. +(: (Box (Option (Tuple Vault (Vec Seen))))) +(def last-seen (make-box None)) + +(: (-> Vault (Vec Seen))) +(defun (seen-of v) + (match (box-ref last-seen) + ((Some (Tuple was ss)) #:when (eq? was v) ss) + (_ + (def zone (clock-timezone)) + (def ss (vec-map (fun (b) (seen b zone)) (vault-bookmarks v))) + (box-set! last-seen (Some (Tuple v ss))) + ss))) + +;; The last search, and what it found. +(: (Box (Option (Tuple Vault string (Vec Bookmark))))) +(def last-found (make-box None)) + +(: (-> Vault string (Vec Bookmark))) +(defun (found-in v text) + (def q (parse-query text)) + (if (query-empty? q) + (vault-bookmarks v) + (let () + ;; Each found with its score and its place, the newest first. + (def scored (vec-fold (fun (s acc) + (match (score q s) + ((Some n) (vec-add acc (Tuple n (vec-length acc) (.bookmark s)))) + (None acc))) + [] (seen-of v))) + (def ordered (if (vec-empty? (.words q)) + scored + (vec-sort-by (fun (a b) + (def (Tuple na ia _) a) + (def (Tuple nb ib _) b) + (if (= na nb) (compare ia ib) (compare nb na))) + scored))) + (vec-map (fun (x) (def (Tuple _ _ b) x) b) ordered)))) + +;; The bookmarks of the vault that the search `text` shows: see the top of +;; this module for the order. +(: (-> Vault string (Vec Bookmark))) +(defun (search-bookmarks v text) + (match (box-ref last-found) + ((Some (Tuple was t found)) #:when (and (eq? was v) (= t text)) found) + (_ + (def found (found-in v text)) + (box-set! last-found (Some (Tuple v text found))) + found))) diff --git a/src/store.bjo b/src/store.bjo new file mode 100644 index 0000000..43a5781 --- /dev/null +++ b/src/store.bjo @@ -0,0 +1,987 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/store.bjo — the module (bjomarks store): a vault of +;; bookmarks, kept in encrypted files that any file syncer or WebDAV share +;; can carry. +;; +;; The shared storage holds: +;; +;; keys.bin the vault's key, wrapped for each password +;; devices/<device uuid>.bin one file for each device +;; +;; - Each device writes only its own file, so a syncer never has two writers +;; for one file. +;; - A device's file holds every entry the device knows, so any one file is a +;; whole copy of the vault. +;; - A device reads the files of the others and merges their entries into +;; its own (see (bjomarks bookmark)). It then writes its own file again +;; when that changed anything. +;; +;; This device's own folder (not shared) holds `device.json` (the vault and +;; device ids), `state.bin` (the same bytes as its file in the storage) and +;; `keys.bin` (a copy, so that the vault opens without the storage). +;; +;; The layout of a device file, version 1. Integers are big-endian. +;; +;; offset size field +;; 0 4 "BMK1" +;; 4 2 version: 1 +;; 6 16 vault id +;; 22 16 device id +;; 38 8 revision: 1 for the first file, then 1 more each time +;; 46 4 key id: the DEK that encrypts the file +;; 50 1 cipher: 1 = AEGIS-256, 2 = XChaCha20-Poly1305 +;; 51 n nonce, as long as the cipher's +;; 51+n the contents, encrypted, and the tag +;; +;; The associated data is the header: bytes 0 to 50+n. The contents are: +;; +;; 0 1 compression: 0 = none, 1 = Brotli +;; 1 4 length of the stored document +;; 5 4 length of the document +;; 9 the stored document, then bytes of 0 +;; +;; The document is the JSON of (bjomarks bookmark)'s `DeviceDoc`, in UTF-8. +;; The contents are padded with zeros to a multiple of 16 KiB, so that the +;; size of a file shows only roughly how many bookmarks it holds. +;; +;; Errors: +;; - Opening, creating and joining return a `StoreError`. +;; - A peer's file that cannot be read does not stop a sync. It is skipped +;; and named in the report's problems. +;; - What the storage and the file system raise is raised. + +(export + ;; Storage + Storage StorageFunctions folder-storage function-storage + storage-label storage-read storage-write storage-list + devices-dir device-file-name + ;; Device files + FileHead encode-device-file decode-device-file + ;; Vaults + Vault StoreError SyncReport + create-vault join-vault open-vault vault-close device-folder + vault-id vault-device vault-revision vault-dirty? vault-entries + vault-bookmarks vault-find vault-add vault-put vault-delete vault-restore + vault-sync vault-save vault-merge vault-change-password) + +(import (std prelude)) +(import (std datetime)) +(import (std uuid)) +(import (text json)) +(import (bjosodium core)) +(import (bjomarks binary)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) + +(import/extern + (clr-brotli-max (: System.IO.Compression.BrotliEncoder.GetMaxCompressedLength (-> int int))) + ;; The source, the destination, the bytes written, the quality (0 to 11) + ;; and the window (10 to 24). + (clr-brotli-compress (: System.IO.Compression.BrotliEncoder.TryCompress + (-> (RoSpan byte) (Span byte) (out int) int int (Tuple bool int)))) + (clr-brotli-decompress (: System.IO.Compression.BrotliDecoder.TryDecompress + (-> (RoSpan byte) (Span byte) (out int) (Tuple bool int)))) + (clr-sha256 (: System.Security.Cryptography.SHA256.HashData (-> (Array byte) (Array byte)))) + (clr-hex (: System.Convert.ToHexStringLower (-> (Array byte) string)))) + +;; --------------------------------------------------------------------------- +;; Storage +;; --------------------------------------------------------------------------- + +;; The functions of a `FunctionStorage`. Each takes a name as the others do: +;; relative, with `/` between its parts. +;; - `read`: the bytes of the file, or `None` when there is no such file. +;; - `write`: writes the file in place of what it held, and makes the +;; folders on the way. +;; - `list`: the names of the files in a folder, without the folder. A +;; missing folder has none. +;; Each raises what the storage raises. +(type (: StorageFunctions (Record (: label string) + (: read (-> string (Option (Array byte)))) + (: write (-> string (Array byte) void)) + (: list (-> string (Vec string)))))) + +;; Where the shared files are. +;; +;; - `FolderStorage`: a folder on this machine, that a file syncer shares, a +;; mounted network drive, or a removable disk. Called in a bjoroutine, its +;; operations read and write without blocking the thread, as the file +;; functions do. +;; - `FunctionStorage`: three functions that read, write and list files by +;; name. For a folder that has no path, such as a folder of Android's +;; Storage Access Framework. A function in a record field cannot be of +;; either colour, so in a bjoroutine these block the thread: call the +;; vault's functions in `blocking`. +;; +;; WebDAV is a case to add. +(type (: Storage (Union (: FolderStorage string) + (: FunctionStorage StorageFunctions)))) + +(: (-> string Storage)) +(defun (folder-storage root) (FolderStorage root)) + +;; A storage of three functions, named `label` in messages: see +;; `StorageFunctions`. +(: (-> string (-> string (Option (Array byte))) (-> string (Array byte) void) (-> string (Vec string)) + Storage)) +(defun (function-storage label read write list) + (FunctionStorage (StorageFunctions (label label) (read read) (write write) (list list)))) + +(: string) +(def devices-dir "devices") + +;; What to call the storage in a message. +(: (-> Storage string)) +(defun (storage-label s) + (match s + ((FolderStorage root) root) + ((FunctionStorage fs) (.label fs)))) + +;; A name is relative, with `/` between its parts: `keys.bin`, +;; `devices/<uuid>.bin`. `None` when there is no such file. +(: (-> Storage string (Option (Array byte)))) +(defun (storage-read s name) + (match s + ((FolderStorage root) (read-if-there (path-of root name))) + ((FunctionStorage fs) ((.read fs) name)))) + +;; Writes the file, in place of what it held. +;; - A `FolderStorage` replaces the file in one step, so that a reader never +;; sees half of it. +;; - A `FunctionStorage` writes as its function does. A device that reads +;; half of a device file cannot decrypt it: it skips the file, names it in +;; the sync's problems, and reads it at the next sync. +(: (-> Storage string (Array byte) void)) +(defun (storage-write s name bytes) + (match s + ((FolderStorage root) + (def parts (string-split name "/")) + (def dir (path-of root (string-join (vec-take parts (- (vec-length parts) 1)) "/"))) + (write-replacing dir (path-of root name) bytes)) + ((FunctionStorage fs) ((.write fs) name bytes)))) + +;; The names of the files in a directory, without the directory: +;; `[<uuid>.bin ...]`. A missing directory has none. Names that start with +;; `.` are left out: they are temporary files. +(: (-> Storage string (Vec string))) +(defun (storage-list s dir) + (def names + (match s + ((FolderStorage root) + (def path (path-of root dir)) + (if (directory-exists? path) + (vec-map (fun (p) (match (path-filename p) ((Some n) n) (None ""))) (directory-files path)) + [])) + ((FunctionStorage fs) ((.list fs) dir)))) + (vec-filter (fun (n) (not (or (string-empty? n) (string-starts-with? n ".")))) names)) + +(: (-> Uuid string)) +(defun (device-file-name device) (str (uuid->string device) ".bin")) + +(: (-> string string string)) +(defun (path-of root name) + (vec-fold (fun (part acc) (path-combine acc part)) root (string-split name "/"))) + +(: (-> string (Option (Array byte)))) +(defun (read-if-there path) + (if (file-exists? path) (Some (file-read-bytes path)) None)) + +;; Writes a temporary file beside `path`, then moves it over `path`. +(: (-> string string (Array byte) void)) +(defun (write-replacing dir path bytes) + (directory-create dir) + (def name (match (path-filename path) ((Some n) n) (None "file"))) + (def temp (path-combine dir (str "." name "." (uuid->string (uuid-v4)) ".tmp"))) + (file-write-bytes temp bytes) + (file-move temp path #:mode MoveReplace)) + +;; --------------------------------------------------------------------------- +;; Device files +;; --------------------------------------------------------------------------- + +(: (Array byte)) +(def device-magic (string->bytes "BMK1")) + +(: int) +(def device-format 1) + +;; The header before the nonce. +(: int) +(def head-length 51) + +(: int) +(def padding-step 16384) + +;; Bounds on what a file can make this device allocate. +(: int) +(def max-document-bytes 268435456) + +;; What the header of a device file says. +(type (: FileHead (Record (: head-vault Uuid) + (: head-device Uuid) + (: head-revision long) + (: head-key-id int) + (: head-cipher Cipher)))) + +;; The contents: the document, compressed, behind its lengths, padded. +(: (-> (Array byte) (Array byte))) +(defun (pack json) + (def n (array-length json)) + (def room (: (make-array (clr-brotli-max n)) (Array byte))) + (def (Tuple compressed written) (clr-brotli-compress (array->ro-span json) (array->span room) 5 22)) + (def stored (if compressed (get-bytes room 0 written) json)) + (def used (+ 9 (array-length stored))) + (def total (* (/ (+ used (- padding-step 1)) padding-step) padding-step)) + (def contents (: (make-array total) (Array byte))) + (put-u8! contents 0 (if compressed 1 0)) + (put-u32! contents 1 (array-length stored)) + (put-u32! contents 5 n) + (put-bytes! contents 9 stored) + contents) + +;; The document from the contents, or why not. +(: (-> (Array byte) (Result string (Array byte)))) +(defun (unpack contents) + (def n (array-length contents)) + (if (< n 9) + (Err "the contents are cut short") + (let ((compression (get-u8 contents 0)) + (stored (get-u32 contents 1)) + (original (get-u32 contents 5))) + (cond + ((or (< stored 0) (> stored (- n 9))) (Err "the contents are cut short")) + ((or (< original 0) (> original max-document-bytes)) (Err "the document is too large")) + ((= compression 0) + (if (= stored original) + (Ok (get-bytes contents 9 stored)) + (Err "the lengths of the document do not agree"))) + ((= compression 1) + (def out (: (make-array original) (Array byte))) + (def (Tuple done written) + (clr-brotli-decompress (array->ro-span contents #:from 9 #:to (+ 9 stored)) (array->span out))) + (if (and done (= written original)) + (Ok out) + (Err "the document does not decompress"))) + (else (Err (str "unknown compression " (int->string compression)))))))) + +;; A device file with a new random nonce. +(: (-> FileHead (Array byte) DeviceDoc (Array byte))) +(defun (encode-device-file head dek doc) + (def cipher (.head-cipher head)) + (def nonce (make-aead-nonce cipher)) + (def header (: (make-array (+ head-length (array-length nonce))) (Array byte))) + (put-bytes! header 0 device-magic) + (put-u16! header 4 device-format) + (put-bytes! header 6 (uuid->bytes (.head-vault head))) + (put-bytes! header 22 (uuid->bytes (.head-device head))) + (put-u64! header 38 (.head-revision head)) + (put-u32! header 46 (.head-key-id head)) + (put-u8! header 50 (cipher->code cipher)) + (put-bytes! header head-length nonce) + (def contents (pack (string->bytes (device-doc->string doc)))) + (def sealed (aead-encrypt cipher dek nonce contents #:aad header)) + (wipe! contents) + (bytes-concat header sealed)) + +;; The DEK of the key id `id`, of those `known`. +(: (-> (Vec (Tuple int (Array byte))) int (Option (Array byte)))) +(defun (key-of known id) + (let go ((i 0)) + (cond ((= i (vec-length known)) None) + ((= (fst (vec-ref known i)) id) (Some (snd (vec-ref known i)))) + (else (go (+ i 1)))))) + +;; The header and the document of a device file, or why it cannot be read. +;; - The file must be of the vault `vault-id`, and encrypted with one of the +;; DEKs `known`, each with its key id. +;; - The document must name the device that the header names. +(: (-> (Array byte) Uuid (Vec (Tuple int (Array byte))) (Result string (Tuple FileHead DeviceDoc)))) +(defun (decode-device-file file vault-id known) + (def n (array-length file)) + (def version (if (>= n 6) (get-u16 file 4) 0)) + (cond + ((< n head-length) (Err "too short for a device file")) + ((not (bytes-at? file 0 device-magic)) (Err "not a device file")) + ((> version device-format) + (Err (str "device file version " (int->string version) " is newer than this version reads (" + (int->string device-format) ")"))) + ((< version 1) (Err (str "device file version " (int->string version) " is not a version"))) + (:def (Some vault) (bytes->uuid (get-bytes file 6 16)) :leave-with (Err "no vault id")) + ((not (= vault vault-id)) (Err (str "it belongs to another vault, " (uuid->string vault)))) + (:def (Some device) (bytes->uuid (get-bytes file 22 16)) :leave-with (Err "no device id")) + (:def revision (get-u64 file 38)) + ((< revision 0L) (Err "the revision is out of range")) + (:def file-key (get-u32 file 46)) + (:def (Some dek) (key-of known file-key) + :leave-with (Err (str "it is encrypted with key " (int->string file-key) ", which this device does not have"))) + (:def code (get-u8 file 50)) + (:def (Some cipher) (code->cipher code) :leave-with (Err (str "unknown cipher " (int->string code)))) + (:def nonce-length (cipher-nonce-length cipher)) + ((< n (+ head-length nonce-length (cipher-tag-length cipher))) (Err "too short for a device file")) + (:def header (get-bytes file 0 (+ head-length nonce-length))) + (:def nonce (get-bytes file head-length nonce-length)) + (:def sealed (get-bytes file (+ head-length nonce-length) (- n (+ head-length nonce-length)))) + (:def (Some contents) (aead-decrypt cipher dek nonce sealed #:aad header) + :leave-with (Err "it does not decrypt: it was changed, or it was encrypted with another key")) + (:def (Ok json) (unpack contents) :propagate) + (:def (Ok doc) (parse-device-doc (bytes->string json)) :propagate) + ((not (= (.device doc) device)) + (Err (str "the header names the device " (uuid->string device) ", and the document names " + (uuid->string (.device doc))))) + (else (Ok (Tuple (FileHead (head-vault vault) (head-device device) (head-revision revision) + (head-key-id file-key) (head-cipher cipher)) + doc))))) + +;; --------------------------------------------------------------------------- +;; This device's folder +;; --------------------------------------------------------------------------- + +(: (-> string string)) +(defun (device-json-path local) (path-combine local "device.json")) + +(: (-> string string)) +(defun (state-path local) (path-combine local "state.bin")) + +(: (-> string string)) +(defun (local-keys-path local) (path-combine local keys-file-name)) + +(: (-> Uuid Uuid string)) +(defun (device-json vault device) + (json->string + (JsonFields (vec->iarray [(Tuple "format" (JsonInt 1L)) + (Tuple "vault" (JsonStr (uuid->string vault))) + (Tuple "device" (JsonStr (uuid->string device)))])) + #:indent 2)) + +(: (-> (Option Json) (Option Uuid))) +(defun (uuid-field j) + (match j + ((Some (JsonStr s)) (string->uuid s)) + (_ None))) + +;; The vault id and the device id of `device.json`. +(: (-> string (Result string (Tuple Uuid Uuid)))) +(defun (parse-device-json text) + (def (Ok j) (parse-json text) :propagate) + (match (Tuple (json-object-ref j "format") (uuid-field (json-object-ref j "vault")) + (uuid-field (json-object-ref j "device"))) + ((Tuple (Some (JsonInt 1L)) (Some vault) (Some device)) (Ok (Tuple vault device))) + ((Tuple (Some (JsonInt f)) _ _) + (if (= f 1L) (Err "a vault or device id is missing") (Err (str "format " (long->string f) " is not 1")))) + (_ (Err "not the device.json of a vault")))) + +(: (-> string Uuid Uuid void)) +(defun (write-device-json local vault device) + (directory-create local) + (write-replacing local (device-json-path local) (string->bytes (device-json vault device)))) + +;; --------------------------------------------------------------------------- +;; Vaults +;; --------------------------------------------------------------------------- + +(type (: StoreError (Union + ;; No password slot of keys.bin opened with the password. + WrongPassword + ;; There is no vault where one is needed: the text says where. + (: NoVault string) + ;; There is a vault where a new one would go. + (: VaultExists string) + ;; Two parts of a vault that do not belong together. + (: OtherVault string) + ;; A file that cannot be read: its name, and why. + (: BadFile string)))) + +;; What a sync did. +;; - `files-merged`: the device files that were read and merged. +;; - `entries-changed`: the entries that the merge took from them. +;; - `wrote`: whether this device's file was written. +;; - `problems`: the files that were skipped, and other things to tell the +;; user, one text each. +(type (: SyncReport (Record (: files-merged int) + (: entries-changed int) + (: wrote bool) + (: problems (Vec string))))) + +;; An open vault. `#:opaque`, so that it is written as #<Vault> and its key +;; is not printed. A change returns a new vault; `vault-save` writes it. +;; - `key-id` and `dek` are the key that this device writes with: the +;; current one of keys.bin, or, while it does not have that, one that the +;; others have. `known` is every key it has, those too. +(type (: Vault #:opaque (Record (: storage Storage) + (: local string) + (: id Uuid) + (: device Uuid) + (: key-id int) + (: dek (Array byte)) + (: known (Vec (Tuple int (Array byte)))) + (: cipher Cipher) + (: entries (Map string Entry)) + (: seen (Map string long)) + (: revision long) + (: clock Clock) + (: dirty bool)))) + +(: (-> Vault Uuid)) +(defun (vault-id v) (.id v)) + +(: (-> Vault Uuid)) +(defun (vault-device v) (.device v)) + +;; The revision of the last file this device wrote. +(: (-> Vault long)) +(defun (vault-revision v) (.revision v)) + +;; True when the vault has changes that `vault-save` has not written. +(: (-> Vault bool)) +(defun (vault-dirty? v) (.dirty v)) + +;; Every entry, the deleted ones too. +(: (-> Vault (Map string Entry))) +(defun (vault-entries v) (.entries v)) + +(: (-> KeysError StoreError)) +(defun (keys-error e) + (match e + (WrongPassword WrongPassword) + ((BadKeys why) (BadFile (str keys-file-name ": " why))))) + +;; The keys that `u` gives: the current one first, then the earlier ones. +(: (-> Unlocked (Vec (Tuple int (Array byte))))) +(defun (keys-of u) (vec-append [(Tuple (.key-id u) (.dek u))] (.earlier u))) + +(: (-> Storage Unlocked string Uuid Vault)) +(defun (empty-vault storage unlocked local device) + (Vault (storage storage) (local local) (id (.vault-id unlocked)) (device device) + (key-id (.key-id unlocked)) (dek (.dek unlocked)) (known (keys-of unlocked)) (cipher (preferred-cipher)) + (entries (map-empty)) (seen (map-empty)) (revision 0L) (clock clock-zero) (dirty #t))) + +;; Writes this device's file if the vault has changes, with the next +;; revision, to the storage and to `state.bin`. `state.bin` is written +;; first, so that the changes are kept when the storage cannot be written. +(: (-> Vault Vault)) +(defun (vault-save v) + (if (not (.dirty v)) + v + (let ((revision (+ (.revision v) 1L))) + (def head (FileHead (head-vault (.id v)) (head-device (.device v)) (head-revision revision) + (head-key-id (.key-id v)) (head-cipher (.cipher v)))) + (def doc (DeviceDoc (device (.device v)) (seen (.seen v)) + (entries (map-fold (fun (k e acc) (vec-add acc e)) [] (.entries v))))) + (def file (encode-device-file head (.dek v) doc)) + (write-replacing (.local v) (state-path (.local v)) file) + (storage-write (.storage v) (str devices-dir "/" (device-file-name (.device v))) file) + (record-set v (revision revision) (dirty #f))))) + +;; A new vault in `storage`, with this device as its first device. +;; - `VaultExists` when the storage already has a keys.bin, or when `local` +;; already has a device.json. +;; - `#:cost` is the cost of Argon2id for the password. +(: (-> Storage string string (#:cost KeyCost) (Result StoreError Vault))) +(defun (create-vault storage local password #:cost default-key-cost) + (cond + ((match (storage-read storage keys-file-name) ((Some _) #t) (None #f)) + (Err (VaultExists (str (storage-label storage) " already has a " keys-file-name)))) + ((file-exists? (device-json-path local)) + (Err (VaultExists (str (device-json-path local) " already belongs to a vault")))) + (else + (def (Tuple keys unlocked) (make-keys password #:cost cost)) + (def device (uuid-v4)) + (storage-write storage keys-file-name keys) + (directory-create local) + (write-replacing local (local-keys-path local) keys) + (write-device-json local (.vault-id unlocked) device) + (Ok (vault-save (empty-vault storage unlocked local device)))))) + +;; This device as a new device of the vault in `storage`. The vault is +;; synced and saved. +;; - `VaultExists` when `local` already has a device.json. +;; - `NoVault` when the storage has no keys.bin. +(: (-> Storage string string (Result StoreError (Tuple Vault SyncReport)))) +(defun (join-vault storage local password) + (cond + ((file-exists? (device-json-path local)) + (Err (VaultExists (str (device-json-path local) " already belongs to a vault")))) + (:def (Some keys) (storage-read storage keys-file-name) + :leave-with (Err (NoVault (str (storage-label storage) " has no " keys-file-name)))) + (:def (Ok unlocked) (match (unlock-keys keys password) ((Ok u) (Ok u)) ((Err e) (Err (keys-error e)))) + :propagate) + (else + (def device (uuid-v4)) + (directory-create local) + (write-replacing local (local-keys-path local) keys) + (write-device-json local (.vault-id unlocked) device) + (Ok (vault-sync (empty-vault storage unlocked local device)))))) + +;; The entries of a file of this device, merged into `v`, with its revision +;; when that is higher. +(: (-> Vault FileHead DeviceDoc Vault)) +(defun (adopt-own v head doc) + (def (Tuple entries changed) (merge-entries/count (.entries v) (.entries doc))) + (record-set v + (entries entries) + (seen (merge-seen (.seen v) (.seen doc))) + (revision (if (> (.head-revision head) (.revision v)) (.head-revision head) (.revision v))) + (clock (entries-clock entries)) + (dirty (or (.dirty v) (> changed 0))))) + +;; The highest revision of each device. +(: (-> (Map string long) (Map string long) (Map string long))) +(defun (merge-seen a b) + (map-fold (fun (k r acc) (if (> r (map-ref-or acc k -1L)) (map-set acc k r) acc)) a b)) + +;; The keys that open the vault, from the storage's keys.bin, `shared`, and +;; this device's copy, `own`. +;; - The storage's opens it, when the password opens that. This device's +;; copy, when it is another file and the password opens it too, adds its +;; keys: those of a password change that lost to another one made at the +;; same time. +;; - This device's copy opens it when the storage's does not, and the +;; storage's does not hold the key of this device's copy: the storage's +;; was replaced, or another device changed the password at the same time. +;; When it holds it, the password was changed on another device, and the +;; old one no longer opens the vault. +(: (-> Storage (Option (Array byte)) (Option (Array byte)) string (Result StoreError Unlocked))) +(defun (unlock-for storage shared own password) + (: (-> (Array byte) (Result StoreError Unlocked))) + (defun (unlock keys) (match (unlock-keys keys password) ((Ok u) (Ok u)) ((Err e) (Err (keys-error e))))) + (def other-own (match (Tuple shared own) + ((Tuple (Some sk) (Some ok)) (if (bytes=? sk ok) None (Some ok))) + ((Tuple None (Some ok)) (Some ok)) + (_ None))) + (match shared + (None (match own ((Some ok) (unlock ok)) (None (Err (NoVault (str keys-file-name " is missing")))))) + ((Some sk) + (match (Tuple (keys-vault-id sk) (unlock sk)) + ((Tuple (Ok shared-vault) (Ok u)) + (match other-own + ((Some ok) + (if (= (keys-vault-id ok) (Ok shared-vault)) + (match (unlock-keys ok password) + ((Ok o) (Ok (with-keys u (keys-of o)))) + ((Err _) (Ok u))) + (Ok u))) + (None (Ok u)))) + ((Tuple (Err e) _) (match other-own ((Some ok) (unlock ok)) (None (Err (keys-error e))))) + ((Tuple _ (Err e)) + (match other-own + ((Some ok) + (if (holds-key? sk ok) + (Err e) + (match (unlock ok) ((Ok o) (Ok o)) ((Err _) (Err e))))) + (None (Err e)))))))) + +;; `u` with the keys of `more` that it does not have, as earlier keys. +(: (-> Unlocked (Vec (Tuple int (Array byte))) Unlocked)) +(defun (with-keys u more) + (def ids (vec-map fst (keys-of u))) + (record-set u (earlier (vec-append (.earlier u) (vec-filter (fun (k) (not (vec-contains? ids (fst k)))) more))))) + +;; The ids of the keys of a keys file, the current one first. None when it +;; cannot be read. +(: (-> (Array byte) (Option (Vec int)))) +(defun (ids-of keys) + (match (keys-key-ids keys) + ((Ok ids) (Some (vec-append [(.current ids)] (.earlier-ids ids)))) + ((Err _) None))) + +;; Whether the keys file `keys` holds the current key of the keys file `own`. +(: (-> (Array byte) (Array byte) bool)) +(defun (holds-key? keys own) + (match (Tuple (ids-of keys) (ids-of own)) + ((Tuple (Some all) (Some mine)) (vec-contains? all (vec-ref mine 0))) + (_ #f))) + +;; The vault of this device: `local`'s device.json, the keys of the storage +;; or of `local`'s copy (see `unlock-for`), and the entries of +;; state.bin and of this device's file in the storage. Call `vault-sync` to +;; merge the other devices. +;; - `NoVault` when `local` has no device.json. +;; - `OtherVault` when the storage's keys.bin is of another vault. +;; - `BadFile` when a file of this device cannot be read and no other copy +;; can be. +(: (-> Storage string string (Result StoreError Vault))) +(defun (open-vault storage local password) + (def json-path (device-json-path local)) + (cond + ((not (file-exists? json-path)) + (Err (NoVault (str json-path " is missing: create a vault, or join one")))) + (:def (Ok (Tuple vault device)) + (match (parse-device-json (file-read-text json-path)) + ((Ok ids) (Ok ids)) + ((Err why) (Err (BadFile (str json-path ": " why))))) + :propagate) + (:def shared (storage-read storage keys-file-name)) + (:def own (read-if-there (local-keys-path local))) + ((and (none? shared) (none? own)) + (Err (NoVault (str "neither " (storage-label storage) " nor " local " has a " keys-file-name)))) + (:def (Ok unlocked) (unlock-for storage shared own password) :propagate) + ((not (= (.vault-id unlocked) vault)) + (Err (OtherVault (str "the " keys-file-name " of " (storage-label storage) " is of the vault " + (uuid->string (.vault-id unlocked)) ", and this device is of " (uuid->string vault))))) + (else + (def fresh (empty-vault storage unlocked local device)) + (def own-name (str devices-dir "/" (device-file-name device))) + (def copies [(read-own fresh (state-path local) (read-if-there (state-path local))) + (read-own fresh (str (storage-label storage) "/" own-name) (storage-read storage own-name))]) + (load-copies fresh copies)))) + +;; A copy of this device's file, read. `None` when there is no copy. +(: (-> Vault string (Option (Array byte)) (Option (Result string (Tuple FileHead DeviceDoc))))) +(defun (read-own v name bytes) + (match bytes + (None None) + ((Some b) + (match (decode-device-file b (.id v) (.known v)) + ((Ok (Tuple head doc)) + (if (= (.head-device head) (.device v)) + (Some (Ok (Tuple head doc))) + (Some (Err (str name ": it is the file of the device " (uuid->string (.head-device head))))))) + ((Err why) (Some (Err (str name ": " why)))))))) + +;; The vault from the copies of this device's file: the one with the highest +;; revision, and the entries of the others merged into it. +;; - With no copy, the vault is empty, and is written at the next save. +;; - The vault has changes to write when a copy is missing or cannot be +;; read, when the copies differ, or when one is written with another key +;; than the one the vault writes with. +;; - `BadFile` when there are copies and none can be read. +(: (-> Vault (Vec (Option (Result string (Tuple FileHead DeviceDoc)))) (Result StoreError Vault))) +(defun (load-copies fresh copies) + (def present (vec-fold (fun (c acc) (match c ((Some r) (vec-add acc r)) (None acc))) [] copies)) + (def good (vec-fold (fun (r acc) (match r ((Ok hd) (vec-add acc hd)) ((Err _) acc))) [] present)) + (def problems (vec-fold (fun (r acc) (match r ((Err why) (vec-add acc why)) ((Ok _) acc))) [] present)) + (cond + ((and (vec-empty? good) (not (vec-empty? problems))) (Err (BadFile (string-join problems "; ")))) + ((vec-empty? good) (Ok fresh)) + (else + (def newest-first (vec-sort-by (fun (a b) (compare (.head-revision (fst b)) (.head-revision (fst a)))) good)) + (def (Tuple head doc) (vec-ref newest-first 0)) + (def entries (entries->map (.entries doc))) + (def start (record-set fresh + (entries entries) (seen (.seen doc)) (revision (.head-revision head)) + (clock (entries-clock entries)) + ;; A copy written with another key than the one this device + ;; writes with is written again, with that one. + (dirty (or (< (vec-length good) (vec-length copies)) + (not (vec-empty? (vec-filter (fun (hd) (not (= (.head-key-id (fst hd)) (.key-id fresh)))) + good))))))) + (Ok (vec-fold (fun (hd v) + (def (Tuple h d) hd) + (def (Tuple merged changed) (merge-entries/count (.entries v) (.entries d))) + (record-set v + (entries merged) + (seen (merge-seen (.seen v) (.seen d))) + (clock (entries-clock merged)) + (dirty (or (.dirty v) (> changed 0) (not (= (.head-revision h) (.revision v))))))) + start (vec-drop newest-first 1)))))) + +;; `current`, with what `done` did: `done` is the result of a save or a sync +;; that ran in the background on an earlier copy of `current`, while +;; `current` changed. +;; - The entries and the seen revisions are merged, and the revision is the +;; higher of the two. Merging is safe in any order: see (bjomarks bookmark). +;; - The result has changes to write when `current` has entries that `done` +;; does not: those made while it ran. +(: (-> Vault Vault Vault)) +(defun (vault-merge current done) + (def later (map-fold (fun (k e acc) (vec-add acc e)) [] (.entries current))) + (def (Tuple entries changed) (merge-entries/count (.entries done) later)) + (record-set done + (entries entries) + (seen (merge-seen (.seen done) (.seen current))) + (revision (if (> (.revision current) (.revision done)) (.revision current) (.revision done))) + (clock (entries-clock entries)) + (dirty (> changed 0)))) + +;; Sets the DEKs to zeros. Do not use the vault after this. +(: (-> Vault void)) +(defun (vault-close v) + (loop (:for k (.known v)) (:do (wipe! (snd k))))) + +;; --------------------------------------------------------------------------- +;; Changes +;; --------------------------------------------------------------------------- + +;; A new stamp of this device, and the vault with its clock moved on. +(: (-> Vault (Tuple Vault Stamp))) +(defun (new-stamp v) + (def (Tuple clock s) (clock-next (.clock v) (instant->unix-milliseconds (now)) (.device v))) + (Tuple (record-set v (clock clock)) s)) + +;; `e` merged into the vault. It wins, as its stamp is new. +(: (-> Vault Entry Vault)) +(defun (with-entry v e) + (record-set v (entries (merge-entry (.entries v) e)) (dirty #t))) + +;; The bookmarks that are not deleted, the newest first. +(: (-> Vault (Vec Bookmark))) +(defun (vault-bookmarks v) (live-bookmarks (.entries v))) + +(: (-> Vault Uuid (Option Bookmark))) +(defun (vault-find v id) + (match (map-try-ref (.entries v) (uuid->string id)) + ((Some e) (match (.state e) ((Live b) (Some b)) ((Deleted _) None))) + (None None))) + +;; A new bookmark. `Err` when `url` or the archive link is not an absolute +;; URL. +(: (-> Vault string (#:title (Option string)) (#:tags (Vec string)) (#:archive (Option string)) + (#:added Instant) + (Result string (Tuple Vault Bookmark)))) +(defun (vault-add v url #:title None #:tags [] #:archive None #:added (now)) + (def (Ok b) (make-bookmark url #:title title #:tags tags #:archive archive #:added added) :propagate) + (def (Tuple v2 s) (new-stamp v)) + (Ok (Tuple (with-entry v2 (live-entry s b)) b))) + +;; The vault with `b` as the bookmark of its id: a change of its address, +;; tags or archive link. The fields that this version does not know, which +;; a newer version wrote, are kept. The tags are cleaned with `clean-tags`. +(: (-> Vault Bookmark Vault)) +(defun (vault-put v b) + (def (Tuple v2 s) (new-stamp v)) + (def extra (match (map-try-ref (.entries v) (uuid->string (.id b))) + ((Some old) (.extra old)) + (None []))) + (with-entry v2 (Entry (stamp s) (state (Live (bookmark-with-tags b (.tags b)))) (extra extra)))) + +;; The vault without the bookmark `id`. Its entry becomes a tombstone, so +;; that the delete reaches the other devices. A bookmark that the vault does +;; not have is not changed. +(: (-> Vault Uuid Vault)) +(defun (vault-delete v id) + (match (vault-find v id) + ((Some _) + (def (Tuple v2 s) (new-stamp v)) + (with-entry v2 (deleted-entry s id))) + (None v))) + +;; The vault with the bookmark of `e` as `e` has it, with its extra fields, +;; at a new stamp: an undone delete. `e` is the entry as it was before the +;; delete, from `vault-entries`. A tombstone changes nothing. +(: (-> Vault Entry Vault)) +(defun (vault-restore v e) + (match (.state e) + ((Live _) + (def (Tuple v2 s) (new-stamp v)) + (with-entry v2 (record-set e (stamp s)))) + ((Deleted _) v))) + +;; A new password, with a new key: writes a new keys.bin, with one slot for +;; `password` and the vault's keys as earlier keys, to the storage and to +;; this device's copy, then this device's file with the new key. An old +;; copy of keys.bin and the old password then open only what was written +;; before. The other devices read on, and need the new password the next +;; time they open the vault. +;; - `Err` when the storage's keys.bin has a key that this device does not +;; have: another device changed the password, and this device must open +;; with the new one first, so that no key is left out. +(: (-> Vault string (#:cost KeyCost) (Result string Vault))) +(defun (vault-change-password v password #:cost default-key-cost) + (def shared (storage-read (.storage v) keys-file-name)) + (def mine (vec-map fst (.known v))) + (def missing (match shared + ((Some keys) (match (ids-of keys) + ((Some all) (vec-filter (fun (k) (not (vec-contains? mine k))) all)) + (None []))) + (None []))) + (if (not (vec-empty? missing)) + (Err "The password was changed on another device. Open the bookmarks with the new password first.") + (let ((u (Unlocked (vault-id (.id v)) (key-id (.key-id v)) (dek (.dek v)) + (earlier (vec-filter (fun (k) (not (= (fst k) (.key-id v)))) (.known v)))))) + (def (Tuple keys made) (new-keys u password #:cost cost)) + (storage-write (.storage v) keys-file-name keys) + (write-replacing (.local v) (local-keys-path (.local v)) keys) + (Ok (vault-save (record-set v (key-id (.key-id made)) (dek (.dek made)) (known (keys-of made)) + (dirty #t))))))) + +;; --------------------------------------------------------------------------- +;; Sync +;; --------------------------------------------------------------------------- + +;; The device that a file name names, as `<uuid>.bin`. +(: (-> string (Option Uuid))) +(defun (device-of-name name) + (if (string-ends-with? name ".bin") + (match (string->uuid (string-drop-right name 4)) + ((Some u) (if (= (device-file-name u) name) (Some u) None)) + (None None)) + None)) + +;; What reading one file did: the vault after it, the entries it changed, +;; and a problem to report, if any. `merged` is false for a file that was +;; skipped. +(type (: FileResult (Record (: after Vault) + (: merged bool) + (: changed int) + (: problem (Option string))))) + +(: (-> Vault string FileResult)) +(defun (sync-file v name) + (def path (str devices-dir "/" name)) + (def skipped (fun (why) (FileResult (after v) (merged #f) (changed 0) (problem (Some (str path ": " why)))))) + (cond + (:def (Some named) (device-of-name name) :leave-with (skipped "the name is not <device uuid>.bin")) + (:def (Some bytes) (storage-read (.storage v) path) :leave-with (skipped "it was gone when it was read")) + (:def decoded (decode-device-file bytes (.id v) (.known v))) + (:def (Ok (Tuple head doc)) decoded :leave-with (match decoded ((Err why) (skipped why)) ((Ok _) (skipped "")))) + ((not (= (.head-device head) named)) + (skipped (str "it holds the file of the device " (uuid->string (.head-device head))))) + ((= named (.device v)) + ;; This device's own file: merged too, as it can have entries that + ;; state.bin lost. An older copy is written again. + (def adopted (adopt-own v head doc)) + (def older (< (.head-revision head) (.revision v))) + (FileResult (after (if older (record-set adopted (dirty #t)) adopted)) (merged #t) (changed 0) (problem None))) + (else + (def key (uuid->string named)) + (def before (map-ref-or (.seen v) key -1L)) + (def revision (.head-revision head)) + (def (Tuple entries changed) (merge-entries/count (.entries v) (.entries doc))) + (FileResult (after (record-set v + (entries entries) + (seen (if (> revision before) (map-set (.seen v) key revision) (.seen v))) + (clock (if (> changed 0) (entries-clock entries) (.clock v))) + (dirty (or (.dirty v) (> changed 0))))) + (merged #t) + (changed changed) + (problem (if (< revision before) + (Some (str path ": revision " (long->string revision) " is older than revision " + (long->string before) ", which this device merged before. " + "An older copy replaced it.")) + None)))))) + +;; The vault writing with the key `id`, which it has, from the next save. +(: (-> Vault int Vault)) +(defun (writing-with v id) + (match (key-of (.known v) id) + ((Some dek) (if (= id (.key-id v)) v (record-set v (key-id id) (dek dek) (dirty #t)))) + (None v))) + +;; The keys.bin of the storage, checked against this vault, before a save: +;; the vault, with the key it writes with from now on, and a problem to tell +;; the user, if any. +;; - A missing one is written again from this device's copy. +;; - When this device has its current key, it writes with that. +;; - When it does not, and the storage's keys.bin holds this device's key as +;; an earlier one, another device changed the password: this device writes +;; on with its key, which the others can read, until it opens with the new +;; password. +;; - When it does not hold that either, another device changed the password +;; at the same time as this one, or keys.bin was replaced: this device +;; writes with a key that keys.bin holds, when it has one, so that the +;; others can read its file. keys.bin is left as it is. +(: (-> Vault (Tuple Vault (Option string)))) +(defun (check-keys v) + (def label (storage-label (.storage v))) + (match (storage-read (.storage v) keys-file-name) + (None + (match (read-if-there (local-keys-path (.local v))) + ((Some keys) + (storage-write (.storage v) keys-file-name keys) + (Tuple v (Some (str keys-file-name " was missing from " label ", and was written again")))) + (None (Tuple v (Some (str keys-file-name " is missing from " label " and from " (.local v))))))) + ((Some keys) + (match (keys-vault-id keys) + ((Err e) (Tuple v (Some (match (keys-error e) ((BadFile why) why) (_ "keys.bin cannot be read"))))) + ((Ok id) #:when (not (= id (.id v))) + (Tuple v (Some (str keys-file-name " of " label " is of another vault, " (uuid->string id))))) + ((Ok _) + (match (ids-of keys) + (None (Tuple v (Some (str keys-file-name " of " label " cannot be read")))) + ((Some all) + (def current (vec-ref all 0)) + (def mine (vec-map fst (.known v))) + (cond + ((vec-contains? mine current) (Tuple (writing-with v current) None)) + ((vec-contains? all (.key-id v)) + (Tuple v (Some (str "The password was changed on another device. Open the bookmarks again " + "with the new password: until then, this device does not read what " + "the others write.")))) + (else + (def shared-keys (vec-filter (fun (k) (vec-contains? mine k)) all)) + (if (vec-empty? shared-keys) + (Tuple v (Some (str keys-file-name " of " label " holds none of this device's keys. " + "It was left as it is."))) + (Tuple (writing-with v (vec-ref shared-keys 0)) + (Some (str "Another device changed the password at the same time as this one. " + "Open the bookmarks again with the password of the other device."))))))))))))) + +;; After a save: this device's copy of keys.bin becomes the storage's, when +;; this device has its current key and wrote its file with a key that it +;; holds. A keys.bin that this device has no key of never replaces its copy: +;; it opens again with its password. +(: (-> Vault void)) +(defun (keep-keys! v) + (def path (local-keys-path (.local v))) + (match (storage-read (.storage v) keys-file-name) + ((Some keys) + (match (Tuple (keys-vault-id keys) (ids-of keys)) + ((Tuple (Ok id) (Some all)) + (when (and (= id (.id v)) (not (.dirty v)) + (vec-contains? (vec-map fst (.known v)) (vec-ref all 0)) + (vec-contains? all (.key-id v)) + (not (match (read-if-there path) ((Some old) (bytes=? old keys)) (None #f)))) + (write-replacing (.local v) path keys))) + (_ unit))) + (None unit))) + +;; Reads the files of the storage, merges them, and saves the vault when +;; that changed it, or when it had changes before. +(: (-> Vault (Tuple Vault SyncReport))) +(defun (vault-sync v) + (def names (vec-filter (fun (n) (string-ends-with? n ".bin")) (storage-list (.storage v) devices-dir))) + ;; A loop and not a fold with a function, so that the reads do not block + ;; the thread in a bjoroutine. + (def (Tuple after merged changed problems) + (let go ((i 0) (cur v) (m 0) (c 0) (ps [])) + (if (= i (vec-length names)) + (Tuple cur m c ps) + (let ((r (sync-file cur (vec-ref names i)))) + (go (+ i 1) (.after r) (if (.merged r) (+ m 1) m) (+ c (.changed r)) + (match (.problem r) ((Some p) (vec-add ps p)) (None ps))))))) + (def (Tuple checked keys-problem) (check-keys after)) + ;; A storage that lost this device's file gets it again. + (def own-missing (not (vec-contains? names (device-file-name (.device v))))) + (def wrote (or (.dirty checked) own-missing)) + (def saved (vault-save (record-set checked (dirty wrote)))) + (keep-keys! saved) + (Tuple saved + (SyncReport (files-merged merged) (entries-changed changed) (wrote wrote) + (problems (match keys-problem ((Some p) (vec-add problems p)) (None problems)))))) + +;; --------------------------------------------------------------------------- +;; This device's folders +;; --------------------------------------------------------------------------- + +;; This device's own folder for the shared folder `shared`, in `root`: each +;; shared folder has one of its own, `root/vaults/<hash of shared>`, so that +;; two shared folders are two vaults. `shared` names the shared folder: its +;; path, or what the system calls it. `storage` is that folder. +;; +;; Before, `root` itself was the folder of the one vault. Its files are +;; moved to the folder of the first shared folder whose keys.bin is of the +;; vault of root's device.json. A shared folder of another vault, or with +;; none, gets a folder of its own, and root's files stay where they are. +(: (-> string string Storage string)) +(defun (device-folder root shared storage) + (def hash (clr-hex (clr-sha256 (string->bytes shared)))) + (def folder (path-combine (path-combine root "vaults") (string-take hash 32))) + (def old-json (device-json-path root)) + (when (and (not (file-exists? (device-json-path folder))) (file-exists? old-json)) + (def old-vault (match (parse-device-json (file-read-text old-json)) + ((Ok (Tuple vault _)) (Some vault)) + ((Err _) None))) + (def shared-vault (match (storage-read storage keys-file-name) + ((Some keys) (match (keys-vault-id keys) ((Ok id) (Some id)) ((Err _) None))) + (None None))) + (when (and (some? old-vault) (= old-vault shared-vault)) + (directory-create folder) + (loop (:for name (list "state.bin" keys-file-name "device.json")) + (:do (def from (path-combine root name)) + (when (file-exists? from) + (file-move from (path-combine folder name) #:mode MoveReplace)))))) + folder) + diff --git a/src/title.bjo b/src/title.bjo new file mode 100644 index 0000000..e504ada --- /dev/null +++ b/src/title.bjo @@ -0,0 +1,232 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/title.bjo — the module (bjomarks title): the title of a web +;; page, fetched from its address. +;; +;; - `fetch-title` asks the server for the page, reads the start of it, and +;; returns the text of its `<title>` element, cleaned as +;; (bjomarks bookmark)'s `clean-title` cleans it. +;; - Only http and https addresses are fetched. Redirects are followed. +;; - At most `max-page-bytes` are read: the title is in the head of a page. +;; Reading stops at the end of the title. +;; - The whole fetch has a deadline: a server that does not answer, or +;; answers slowly, gives an `Err` and not a wait. +;; - The bytes of the title are decoded by the charset that the server +;; names, or else the one that the page names in a `<meta>` element, or +;; else UTF-8. Character references, as `&` and `—`, are decoded. +;; - A status that is not 2xx, or a page that is not HTML, is an `Err`. +;; +;; `page-title` is the part that reads the bytes, for a page got another +;; way. + +(export fetch-title page-title max-page-bytes) + +(import (std http)) +(import (std ports)) +(import (text encodings)) +(import (bjomarks bookmark)) + +(import/class + (Exception (: System.Exception))) + +(import/extern + (clr-html-decode (: System.Net.WebUtility.HtmlDecode (-> string string)))) + +;; 512 KiB. +(: int) +(def max-page-bytes 524288) + +;; Sent as the User-Agent. Some servers answer a client that names no +;; browser with an error page. +(: string) +(def agent "Mozilla/5.0 (compatible; bjomarks/0.1; +title)") + +;; --------------------------------------------------------------------------- +;; Reading the bytes +;; --------------------------------------------------------------------------- + +;; The byte in lower case, for the ASCII letters. +(: (-> int int)) +(defun (lower b) (if (and (>= b 65) (<= b 90)) (+ b 32) b)) + +;; True when `bytes` holds `pattern` at `i`, in any case. `pattern` is ASCII +;; in lower case. +(: (-> (Array byte) int (Array byte) bool)) +(defun (holds-at? bytes i pattern) + (def m (array-length pattern)) + (let go ((j 0)) + (cond + ((= j m) #t) + ((= (lower (cast int (array-ref bytes (+ i j)))) (cast int (array-ref pattern j))) (go (+ j 1))) + (else #f)))) + +;; The first place from `start`, before `end`, where `bytes` holds +;; `pattern`, in any case. -1 when there is none. +(: (-> (Array byte) int int string int)) +(defun (find-ci bytes start end pattern-text) + (def pattern (string->bytes pattern-text)) + (def m (array-length pattern)) + (let go ((i (max start 0))) + (cond + ((> (+ i m) end) -1) + ((holds-at? bytes i pattern) i) + (else (go (+ i 1)))))) + +;; The name after `charset=` at `at`: letters, digits and `-_.:`, maybe in +;; quotes. +(: (-> (Array byte) int int string)) +(defun (charset-name bytes at end) + (def start (if (and (< at end) (let ((b (cast int (array-ref bytes at)))) (or (= b 34) (= b 39)))) + (+ at 1) + at)) + (defun (name-byte? b) + (or (and (>= b 97) (<= b 122)) (and (>= b 65) (<= b 90)) (and (>= b 48) (<= b 57)) + (= b 45) (= b 95) (= b 46) (= b 58))) + (let go ((i start)) + (if (and (< i end) (name-byte? (cast int (array-ref bytes i)))) + (go (+ i 1)) + (bytes->string (ro-span->array (array->ro-span bytes #:from start #:to i)))))) + +;; The charset that a `Content-Type` value names, if it names one. +(: (-> string (Option string))) +(defun (header-charset content-type) + (def bytes (string->bytes content-type)) + (def at (find-ci bytes 0 (array-length bytes) "charset=")) + (if (< at 0) + None + (let ((name (charset-name bytes (+ at 8) (array-length bytes)))) + (if (string-empty? name) None (Some name))))) + +;; The charset that the page names in a `<meta>` element, in its first 4 KiB: +;; `<meta charset="...">` or `<meta http-equiv=... content="...; charset=...">`. +(: (-> (Array byte) int (Option string))) +(defun (meta-charset bytes n) + (def end (min n 4096)) + (def at (find-ci bytes 0 end "charset=")) + (if (< at 0) + None + (let ((name (charset-name bytes (+ at 8) end))) + (if (string-empty? name) None (Some name))))) + +;; The text of bytes `from` to `to`, in the encoding named, or UTF-8. Bytes +;; that are not of the encoding are read as Windows-1252, which takes any. +(: (-> (Array byte) int int (Option string) string)) +(defun (decode bytes from to charset) + (def slice (ro-span->array (array->ro-span bytes #:from from #:to to))) + (def encoding (match charset + ((Some name) (match (encoding-named name) ((Some e) e) (None utf-8))) + (None utf-8))) + (match (try (bytes->string slice #:encoding encoding) #:catch (System.Exception)) + ((Ok text) text) + ((Err _) (bytes->string slice #:encoding windows-1252)))) + +;; The title of the page in the first `n` bytes of `bytes`, as +;; `clean-title` makes it. `None` when there is no whole `<title>` element, +;; or it is empty. `content-type` is the server's `Content-Type`, if it sent +;; one: its charset comes first. +(: (-> (Array byte) int (Option string) (Option string))) +(defun (page-title bytes n content-type) + (def start (title-start bytes n)) + (def close (if (>= start 0) (find-ci bytes start n "</title") -1)) + (if (< close 0) + None + (let ((charset (match (match content-type ((Some t) (header-charset t)) (None None)) + ((Some c) (Some c)) + (None (meta-charset bytes n))))) + (clean-title (clr-html-decode (decode bytes start close charset)))))) + +;; Where the text of the first `<title>` element starts: the index after +;; the `>` of its tag. -1 when there is none. `<title lang="en">` is a +;; title tag; `<titlebar>` is not. +(: (-> (Array byte) int int)) +(defun (title-start bytes n) + (let go ((from 0)) + (def open (find-ci bytes from n "<title")) + (cond + ((or (< open 0) (>= (+ open 6) n)) -1) + ((let ((b (cast int (array-ref bytes (+ open 6))))) + (or (= b 62) (= b 32) (= b 9) (= b 10) (= b 13) (= b 12) (= b 47))) + (let ((gt (find-ci bytes (+ open 6) n ">"))) + (if (< gt 0) -1 (+ gt 1)))) + (else (go (+ open 6)))))) + +;; --------------------------------------------------------------------------- +;; Fetching +;; --------------------------------------------------------------------------- + +;; True for the types of an HTML page. A server that sends no type is given +;; the benefit of the doubt. +(: (-> (Option string) bool)) +(defun (html-type? content-type) + (match content-type + ((Some t) + (def lower (string-downcase t)) + (or (string-starts-with? lower "text/html") + (string-starts-with? lower "application/xhtml+xml"))) + (None #t))) + +;; The start of the body, at most `max-page-bytes`, and how much of the +;; buffer it fills. Reading stops at EOF, or when the title has ended. +(: (-bjo-> InputPort (Tuple (Array byte) int))) +(defbjo (read-head port) + (def buffer (: (make-array max-page-bytes) (Array byte))) + (let go ((n 0)) + (if (>= n max-page-bytes) + (Tuple buffer n) + (match (read-some port) + (None (Tuple buffer n)) + ((Some chunk) + (def take (min (array-length chunk) (- max-page-bytes n))) + (.CopyTo (array->ro-span chunk #:to take) (array->span buffer #:from n #:to (+ n take))) + (def total (+ n take)) + ;; A title's end can straddle two chunks. + (if (>= (find-ci buffer (- n 8) total "</title") 0) + (Tuple buffer total) + (go total))))))) + +(: (-> Exception string)) +(defun (message-of e) (.-Message e)) + +;; Fetches the page and reads its title. +(: (-bjo-> string (Result string string))) +(defbjo (read-title url) + (with-response (got (fetch (http-get url #:headers [("User-Agent" . agent) + ("Accept" . "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1")]))) + (match got + ((Err e) (Err (message-of e))) + ((Ok r) + (def content-type (response-header r "Content-Type")) + (cond + ((not (response-ok? r)) (Err (str "the server answered " (int->string (response-status r))))) + ((not (html-type? content-type)) + (Err (str "it is not a web page, but " (match content-type ((Some t) t) (None ""))))) + (else + (def (Tuple bytes n) (read-head (response-bytes-port r))) + (match (page-title bytes n content-type) + ((Some title) (Ok title)) + (None (Err "the page has no title"))))))))) + +;; The title of the page at `url`, or why there is none. The whole fetch +;; has `#:within` seconds to finish; then it is cancelled. +;; - `Err` for an address that is not http or https, for a request that +;; fails, for a status that is not 2xx, for a page that is not HTML, and +;; for a page with no title in its first `max-page-bytes`. +(: (-bjo-> string (#:within int) (Result string string))) +(defbjo (fetch-title url #:within 10) + (if (not (http-address? url)) + (Err (str "only http and https addresses are fetched: " url)) + (match (sync (choose (wrap (spawn-evt (read-title url)) Some) + (wrap (timeout (seconds (cast long within))) (fun (_) None)))) + ((Some (Ok result)) result) + ((Some (Err e)) (Err (message-of e))) + (None (Err (str "no answer in " + (int->string within) + (if (= within 1) " second" " seconds"))))))) + +(: (-> string bool)) +(defun (http-address? url) + (def lower (string-downcase (string-trim url))) + (and (absolute-url? url) + (or (string-starts-with? lower "http://") (string-starts-with? lower "https://")))) diff --git a/src/wayback.bjo b/src/wayback.bjo new file mode 100644 index 0000000..79a6b75 --- /dev/null +++ b/src/wayback.bjo @@ -0,0 +1,110 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/src/wayback.bjo — the module (bjomarks wayback): the latest copy +;; of a web page in the Wayback Machine of the Internet Archive. +;; +;; - `fetch-archive` asks the Wayback Machine's availability API +;; (`wayback-api`) for the page, and returns the address of the latest +;; snapshot of it. +;; - The API is asked with no timestamp, so its "closest" snapshot is the +;; latest one. +;; - The address of the snapshot is made https: the API gives http. +;; - Only http and https addresses are asked for. +;; - The whole fetch has a deadline: an API that does not answer, or answers +;; slowly, gives an `Err` and not a wait. +;; +;; `snapshot-in` is the part that reads the answer, for an answer got +;; another way. + +(export fetch-archive snapshot-in wayback-api) + +(import (std prelude)) +(import (std http)) +(import (text json)) +(import (bjomarks bookmark)) + +(import/class + (Exception (: System.Exception))) + +;; The availability API: `?url=<address>` returns JSON with the snapshot +;; closest to now, if there is one. +(: string) +(def wayback-api "https://archive.org/wayback/available") + +;; Sent as the User-Agent. +(: string) +(def agent "Mozilla/5.0 (compatible; bjomarks/0.1; +archive)") + +;; The address with https in place of http. +(: (-> string string)) +(defun (as-https address) + (if (string-starts-with? (string-downcase address) "http://") + (str "https://" (string-drop address 7)) + address)) + +;; The address of the snapshot in an answer of the API. `None` when the +;; Wayback Machine has no snapshot of the page. `Err` when the text is not +;; JSON. +;; - A snapshot is `archived_snapshots.closest`, with `available` true and +;; a `url`. Its address is made https. +(: (-> string (Result string (Option string)))) +(defun (snapshot-in text) + (match (parse-json text #:objects 'fields) + ((Err why) (Err (str "the answer is not JSON: " why))) + ((Ok answer) + (def closest (match (json-object-ref answer "archived_snapshots") + ((Some snapshots) (json-object-ref snapshots "closest")) + (None None))) + (Ok (match closest + ((Some c) + (match (Tuple (json-object-ref c "available") (json-object-ref c "url")) + ((Tuple (Some (JsonBool #t)) (Some (JsonStr address))) (Some (as-https address))) + (_ None))) + (None None)))))) + +(: (-> Exception string)) +(defun (message-of e) (.-Message e)) + +;; Asks `api` about `url`, and reads the answer. +(: (-bjo-> string string (Result string string))) +(defbjo (ask api url) + (with-response (got (fetch (http-get api #:query [("url" . url)] + #:headers [("User-Agent" . agent) ("Accept" . "application/json")]))) + (match got + ((Err e) (Err (message-of e))) + ((Ok r) + (cond + ((not (response-ok? r)) + (Err (str "the Wayback Machine answered " (int->string (response-status r))))) + (else + (match (snapshot-in (response-text r)) + ((Err why) (Err why)) + ((Ok (Some address)) (Ok address)) + ((Ok None) (Err "the Wayback Machine has no copy of this page"))))))))) + +;; The address of the latest snapshot of the page at `url` in the Wayback +;; Machine, or why there is none. +;; - `#:within`: the seconds the whole fetch has to finish; then it is +;; cancelled. The API is often slow, so the default is 20. +;; - `#:api`: the address of the API, `wayback-api` by default. +;; - `Err` for an address that is not http or https, for a request that +;; fails, for a status that is not 2xx, for an answer that is not JSON, and +;; for a page with no snapshot. +(: (-bjo-> string (#:within int) (#:api string) (Result string string))) +(defbjo (fetch-archive url #:within 20 #:api wayback-api) + (def address (string-trim url)) + (if (not (http-address? address)) + (Err (str "only http and https addresses are looked up: " url)) + (match (sync (choose (wrap (spawn-evt (ask api address)) Some) + (wrap (timeout (seconds (cast long within))) (fun (_) None)))) + ((Some (Ok result)) result) + ((Some (Err e)) (Err (message-of e))) + (None (Err (str "no answer in " (int->string within) (if (= within 1) " second" " seconds"))))))) + +(: (-> string bool)) +(defun (http-address? url) + (def lower (string-downcase url)) + (and (absolute-url? url) + (or (string-starts-with? lower "http://") (string-starts-with? lower "https://")))) diff --git a/tests/bookmark.bjo b/tests/bookmark.bjo new file mode 100644 index 0000000..dde0eaf --- /dev/null +++ b/tests/bookmark.bjo @@ -0,0 +1,412 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/bookmark.bjo — (bjomarks bookmark): stamps, the JSON of +;; entries and documents, and the properties of the merge. +;; +;; bjo run tests/bookmark.bjo + +(import (std prelude)) +(import (std test)) +(import (std test gen)) +(import (std test prop)) +(import (std datetime)) +(import (std uuid)) +(import (text json)) +(import (bjomarks bookmark)) + +(: (-> string Uuid)) +(defun (uuid text) + (match (string->uuid text) + ((Some u) u) + (None (panic! (str "not a uuid: " text))))) + +(: (-> string Instant)) +(defun (at text) + (match (iso8601->instant text) + ((Some i) i) + (None (panic! (str "not an instant: " text))))) + +(def id-a (uuid "0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f")) +(def id-b (uuid "1c8b3e1f-7b4d-4e8f-a021-2b3c4d5e6f70")) +(def id-c (uuid "2d7c4f20-8c5e-4f90-b132-3c4d5e6f7081")) +(def phone (uuid "3f9c0d2a-1111-4222-8333-444455556666")) +(def laptop (uuid "77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff")) + +(: (-> long int Uuid Stamp)) +(defun (stamp-at ms counter device) (Stamp (ms ms) (counter counter) (device device))) + +(def example-bookmark + (Bookmark (id id-a) (url "https://example.org/") (title (Some "Example Domain")) + (added (at "2026-11-11T09:12:00Z")) + (tags ["async" "rust"]) + (archive (Some "https://web.archive.org/web/20261111091200/https://example.org/")))) + +(def example-entry (live-entry (stamp-at 1762852320000L 2 phone) example-bookmark)) + +(: (-> string (Result string Entry))) +(defun (parse-entry text) + (match (parse-json text #:objects 'fields) + ((Ok j) (json->entry j)) + ((Err why) (Err why)))) + +(: (-> (Result string Entry) string)) +(defun (error-of r) + (match r + ((Ok _) "Ok") + ((Err why) why))) + +;; 1762852320000 is 0x019a722fb300. +(def stamp-a-text "019a722fb300-0002-3f9c0d2a-1111-4222-8333-444455556666") + +;; ---- Stamps ------------------------------------------------------------------- + +(deftest "a stamp's text has fixed widths" + (check (= (stamp->string (stamp-at 1762852320000L 2 phone)) stamp-a-text)) + (check (= (stamp->string (stamp-at 0L 0 laptop)) "000000000000-0000-77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff"))) + +(deftest "a stamp's text reads back" + (check (= (string->stamp stamp-a-text) (Some (stamp-at 1762852320000L 2 phone)))) + (check (= (string->stamp "019A722FB300-0002-3f9c0d2a-1111-4222-8333-444455556666") None)) + (check (= (string->stamp "019a722fb300-0002-3F9C0D2A-1111-4222-8333-444455556666") None)) + (check (= (string->stamp "019a722fb300_0002-3f9c0d2a-1111-4222-8333-444455556666") None)) + (check (= (string->stamp "19a722fb300-0002-3f9c0d2a-1111-4222-8333-444455556666") None)) + (check (= (string->stamp "") None))) + +(def gen-stamp + (gen-let ((ms (gen-long-range 0L 281474976710655L)) + (counter (gen-int-range 0 65535)) + (device (gen-element (list phone laptop)))) + (stamp-at ms counter device))) + +(deftest "the order of stamp texts is the order of stamps" + (for-all ((a gen-stamp) (b gen-stamp)) + (check (= (string->stamp (stamp->string a)) (Some a))) + (def by-text (compare (stamp->string a) (stamp->string b))) + (def by-stamp (stamp-compare a b)) + (check (= (compare by-text 0) (compare by-stamp 0))))) + +(deftest "the clock uses the wall clock when it is ahead" + (def (Tuple c s) (clock-next clock-zero 1000L phone)) + (check (= s (stamp-at 1000L 0 phone))) + (check (= (.last-ms c) 1000L))) + +(deftest "the clock counts while the wall clock is behind" + (def seen (clock-observe clock-zero (stamp-at 5000L 7 laptop))) + (def (Tuple c s) (clock-next seen 1000L phone)) + (check (= s (stamp-at 5000L 8 phone))) + (def (Tuple _c2 s2) (clock-next c 1000L phone)) + (check (= s2 (stamp-at 5000L 9 phone))) + (check (> (stamp-compare s2 s) 0))) + +(deftest "the clock moves a millisecond on when the counter is full" + (def full (clock-observe clock-zero (stamp-at 5000L 65535 laptop))) + (def (Tuple _c s) (clock-next full 5000L phone)) + (check (= s (stamp-at 5001L 0 phone)))) + +(deftest "a new stamp is later than all that the clock saw" + (for-all ((seen gen-stamp) (wall (gen-long-range 0L 281474976710655L))) + (def (Tuple _c s) (clock-next (clock-observe clock-zero seen) wall phone)) + (check (> (compare (Tuple (.ms s) (.counter s)) (Tuple (.ms seen) (.counter seen))) 0)))) + +;; ---- Bookmarks ---------------------------------------------------------------- + +(deftest "make-bookmark checks and cleans" + (def (Ok b) (make-bookmark " https://example.org/a " #:tags ["b" " a" "" "b"] + #:added (at "2026-11-11T09:12:00Z")) + :leave-with (check-fail "make-bookmark refused a good address")) + (check (= (.url b) "https://example.org/a")) + (check (= (.tags b) ["a" "b"])) + (check (= (.archive b) None)) + (check (= (.added b) (at "2026-11-11T09:12:00Z"))) + (check-match (make-bookmark "example.org") (Err _)) + (check-match (make-bookmark "http://exa mple.org") (Err _)) + (check-match (make-bookmark "https://example.org" #:archive (Some "web.archive.org/x")) (Err _)) + (check-match (make-bookmark "https://example.org" + #:archive (Some "https://web.archive.org/web/2026/https://example.org")) + (Ok _)) + (check (not (= (.id b) (match (make-bookmark "https://example.org/a") ((Ok b2) (.id b2)) ((Err _) (.id b))))))) + +(deftest "changing tags and the archive link" + (check (= (.tags (bookmark-with-tags example-bookmark ["z" "a" "z"])) ["a" "z"])) + (check-match (bookmark-with-archive example-bookmark (Some "nonsense")) (Err _)) + (check (= (match (bookmark-with-archive example-bookmark None) ((Ok b) (.archive b)) ((Err _) (Some "x"))) + None))) + +;; `n` copies of `c`. +(: (-> char int string)) +(defun (repeat c n) (string-pad-left "" n #:with c)) + +(deftest "a title is one line, trimmed, and not empty" + #:cases ((text wanted) + ("Example Domain" (Some "Example Domain")) + (" Example \n\t Domain \r\n" (Some "Example Domain")) + ;; A no-break space. + ((list->string (list #\R #\x00A0 #\s)) (Some "R s")) + ("" None) + (" \n\t " None)) + (check (= (clean-title text) wanted))) + +(deftest "a long title is cut at 300 characters" + (check (= (clean-title (repeat #\a 400)) (Some (repeat #\a 300)))) + ;; Characters, not UTF-16 units: each of these is two units. + (def (Some cut) (clean-title (repeat #\x1F600 301)) :leave-with (check-fail "no title")) + (check (= (string-count cut) 300)) + (check (= cut (repeat #\x1F600 300))) + ;; The space at the cut is trimmed. + (check (= (clean-title (str (repeat #\a 299) " b")) (Some (repeat #\a 299))))) + +(deftest "make-bookmark and bookmark-with-title clean the title" + (def (Ok b) (make-bookmark "https://example.org/" #:title (Some " Example\nDomain ")) + :leave-with (check-fail "make-bookmark refused a good address")) + (check (= (.title b) (Some "Example Domain"))) + (def (Ok untitled) (make-bookmark "https://example.org/") :leave-with (check-fail "refused")) + (check (= (.title untitled) None)) + (def (Ok blank) (make-bookmark "https://example.org/" #:title (Some " ")) :leave-with (check-fail "refused")) + (check (= (.title blank) None)) + (check (= (.title (bookmark-with-title example-bookmark (Some "\tNew title"))) (Some "New title"))) + (check (= (.title (bookmark-with-title example-bookmark (Some ""))) None)) + (check (= (.title (bookmark-with-title example-bookmark None)) None))) + +;; ---- JSON of an entry ------------------------------------------------------------ + +(def example-json + (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\"," + "\"stamp\":\"" stamp-a-text "\"," + "\"url\":\"https://example.org/\"," + "\"title\":\"Example Domain\"," + "\"added\":\"2026-11-11T09:12:00Z\"," + "\"tags\":[\"async\",\"rust\"]," + "\"archive\":\"https://web.archive.org/web/20261111091200/https://example.org/\"}")) + +(deftest "an entry as JSON" + (check (= (json->string (entry->json example-entry)) example-json))) + +(deftest "an entry read from JSON" + (check (= (parse-entry example-json) (Ok example-entry)))) + +(deftest "a deleted entry" + (def gone (deleted-entry (stamp-at 1762852320000L 2 phone) id-a)) + (def text (json->string (entry->json gone))) + (check (= text (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text + "\",\"deleted\":true}"))) + (check (= (parse-entry text) (Ok gone))) + ;; The fields of a deleted bookmark are not read. + (check (= (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text + "\",\"deleted\":true,\"url\":3}")) + (Ok gone)))) + +(deftest "tags and the archive link can be left out" + (def r (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text + "\",\"url\":\"https://example.org/\",\"added\":\"2026-11-11T10:12:00+01:00\"," + "\"archive\":null,\"deleted\":false}"))) + (def (Ok e) r :leave-with (check-fail (error-of r))) + (def (Live b) (.state e) :leave-with (check-fail "not live")) + (check (= (.tags b) [])) + (check (= (.archive b) None)) + (check (= (.added b) (at "2026-11-11T09:12:00Z")))) + +(deftest "tags are read as a set" + (def r (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text + "\",\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\"," + "\"tags\":[\"rust\",\"async\",\"rust\"]}"))) + (def (Ok e) r :leave-with (check-fail (error-of r))) + (def (Live b) (.state e) :leave-with (check-fail "not live")) + (check (= (.tags b) ["async" "rust"]))) + +(deftest "fields from a newer version are kept, in order, after the known ones" + (def text (str "{\"rating\":4,\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\"," + "\"stamp\":\"" stamp-a-text "\",\"url\":\"https://example.org/\"," + "\"added\":\"2026-11-11T09:12:00Z\",\"x-visits\":[1,2],\"note\":{\"text\":\"hi\"}}")) + (def r (parse-entry text)) + (def (Ok e) r :leave-with (check-fail (error-of r))) + (check (= (vec-map fst (.extra e)) ["rating" "x-visits" "note"])) + (check (= (json->string (entry->json e)) + (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text "\"," + "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[]," + "\"rating\":4,\"x-visits\":[1,2],\"note\":{\"text\":\"hi\"}}")))) + +(deftest "a title can be left out, or null, and is read cleaned" + (: (-> string (Option string))) + (defun (title-of field) + (match (parse-entry (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text + "\",\"url\":\"https://example.org/\"," field "\"added\":\"2026-11-11T09:12:00Z\"}")) + ((Ok e) (match (.state e) ((Live b) (.title b)) ((Deleted _) (Some "deleted")))) + ((Err why) (Some (str "Err: " why))))) + (check (= (title-of "") None)) + (check (= (title-of "\"title\":null,") None)) + (check (= (title-of "\"title\":\" \",") None)) + (check (= (title-of "\"title\":\" Example\\n Domain \",") (Some "Example Domain")))) + +(deftest "a bookmark with no title writes no title field" + (def untitled (live-entry (stamp-at 1762852320000L 2 phone) (bookmark-with-title example-bookmark None))) + (def text (json->string (entry->json untitled))) + (check (not (string-contains? text "title"))) + (check (= (parse-entry text) (Ok untitled)))) + +(: (-> string string)) +(defun (with-field field) + (str "{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"" stamp-a-text "\"," field "}")) + +(deftest "what an entry must not be" + #:cases ((text wanted) + ("[1]" "expected an object") + ("{\"stamp\":\"x\"}" "id: missing") + ("{\"id\":7}" "id: expected a string") + ("{\"id\":\"nope\"}" "id: not a uuid: nope") + ("{\"id\":\"0b9a2f0e-6a3c-4d7e-9f10-1a2b3c4d5e6f\",\"stamp\":\"soon\"}" "stamp: not a stamp: soon") + ((with-field "\"added\":\"2026-11-11T09:12:00Z\"") "url: missing") + ((with-field "\"url\":\"example.org\",\"added\":\"2026-11-11T09:12:00Z\"") + "url: not an absolute URL: example.org") + ((with-field "\"url\":\"https://example.org/\"") "added: missing") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11\"") + "added: not an ISO 8601 date and time with an offset: 2026-11-11") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":\"rust\"") + "tags: expected an array of strings") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[\"a\",2]") + "tags[1]: expected a string") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"tags\":[\"\"]") + "tags[0]: a tag cannot be empty") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"archive\":1") + "archive: expected a string or null") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"archive\":\"x\"") + "archive: not an absolute URL: x") + ((with-field "\"url\":\"https://example.org/\",\"added\":\"2026-11-11T09:12:00Z\",\"title\":[\"a\"]") + "title: expected a string or null") + ((with-field "\"deleted\":\"yes\"") "deleted: expected true or false")) + (check (= (error-of (parse-entry text)) wanted))) + +;; ---- The document of a device ------------------------------------------------------- + +(def example-doc + (DeviceDoc (device phone) + (seen (map-set (map-empty) (uuid->string laptop) 41L)) + (entries [example-entry + (deleted-entry (stamp-at 1762852321000L 0 laptop) id-b)]))) + +(deftest "a document reads back" + (check (= (parse-device-doc (device-doc->string example-doc)) (Ok example-doc)))) + +(deftest "a document's records are in the order of their ids" + (def reversed (record-set example-doc (entries (vec-reverse (.entries example-doc))))) + (check (= (device-doc->string reversed) (device-doc->string example-doc)))) + +(deftest "a document as text" + (check (= (device-doc->string (DeviceDoc (device phone) (seen (map-empty)) (entries []))) + "{\"format\":1,\"device\":\"3f9c0d2a-1111-4222-8333-444455556666\",\"seen\":{},\"records\":[]}"))) + +(: (-> (Result string DeviceDoc) string)) +(defun (doc-error r) + (match r + ((Ok _) "Ok") + ((Err why) why))) + +(def doc-head "{\"format\":1,\"device\":\"3f9c0d2a-1111-4222-8333-444455556666\",") + +(deftest "what a document must not be" + #:cases ((text wanted) + ;; The message that the docs of parse-json give for this text. + ("[1, 2,]" "line 1, column 7: ']' does not begin a value") + ("[]" "expected an object") + ("{\"device\":\"x\"}" "format: missing") + ("{\"format\":2,\"records\":[]}" "format 2 is newer than this version reads (1)") + ("{\"format\":0}" "format 0 is not a format") + ("{\"format\":1,\"records\":[]}" "device: missing") + ((str doc-head "\"seen\":{}}") "records: missing") + ((str doc-head "\"records\":{}}") "records: expected an array") + ((str doc-head "\"seen\":[],\"records\":[]}") "seen: expected an object") + ((str doc-head "\"seen\":{\"x\":1},\"records\":[]}") "seen: not a uuid: x") + ((str doc-head "\"seen\":{\"77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff\":-1},\"records\":[]}") + "seen.77b2e40e-aaaa-4bbb-8ccc-ddddeeeeffff: a revision cannot be negative") + ((str doc-head "\"records\":[" example-json ",{\"id\":3}]}") "records[1]: id: expected a string")) + (check (= (doc-error (parse-device-doc text)) wanted))) + +(deftest "the fields a document does not know are left out" + (check (= (parse-device-doc (str doc-head "\"records\":[],\"later\":true}")) + (Ok (DeviceDoc (device phone) (seen (map-empty)) (entries [])))))) + +;; ---- Merging -------------------------------------------------------------------- + +(deftest "the later stamp wins" + (def older (live-entry (stamp-at 1000L 0 phone) example-bookmark)) + (def newer (live-entry (stamp-at 1000L 1 laptop) (bookmark-with-tags example-bookmark ["new"]))) + (check (= (map-try-ref (entries->map [older newer]) (uuid->string id-a)) (Some newer))) + (check (= (map-try-ref (entries->map [newer older]) (uuid->string id-a)) (Some newer)))) + +(deftest "a delete wins over an older change, and a newer change wins over a delete" + (def changed (live-entry (stamp-at 1000L 0 phone) example-bookmark)) + (def gone (deleted-entry (stamp-at 2000L 0 laptop) id-a)) + (def again (live-entry (stamp-at 3000L 0 phone) example-bookmark)) + (check (= (live-bookmarks (entries->map [changed gone])) [])) + (check (= (live-bookmarks (entries->map [gone changed])) [])) + (check (= (live-bookmarks (entries->map [gone again changed])) [example-bookmark]))) + +(deftest "the bookmarks, the newest first" + (def b1 (record-set example-bookmark (id id-b) (added (at "2026-01-01T00:00:00Z")))) + (def b2 (record-set example-bookmark (id id-c) (added (at "2026-06-01T00:00:00Z")))) + (def es [(live-entry (stamp-at 1L 0 phone) b1) (live-entry (stamp-at 2L 0 phone) example-bookmark) + (live-entry (stamp-at 3L 0 phone) b2)]) + (check (= (vec-map #(.id &) (live-bookmarks (entries->map es))) [id-a id-c id-b]))) + +(deftest "the clock of the entries is their latest stamp" + (def es (entries->map [(live-entry (stamp-at 5L 3 phone) example-bookmark) + (deleted-entry (stamp-at 9L 1 laptop) id-b)])) + (check (= (entries-clock es) (Clock (last-ms 9L) (last-counter 1))))) + +;; Few ids, devices and times, so that the generated entries collide often: +;; the same id, the same time, and now and then the same stamp. +(def gen-entry + (gen-let ((id (gen-element (list id-a id-b id-c))) + (ms (gen-long-range 0L 3L)) + (counter (gen-int-range 0 2)) + (device (gen-element (list phone laptop))) + (deleted gen-bool) + (tags (gen-element (list [] ["a"] ["a" "b"])))) + (def s (stamp-at ms counter device)) + (if deleted + (deleted-entry s id) + (live-entry s (record-set example-bookmark (id id) (tags tags)))))) + +(def gen-entries (gen-vec gen-entry)) + +(deftest "merging is commutative" + (for-all ((xs gen-entries) (ys gen-entries)) + (def a (entries->map xs)) + (def b (entries->map ys)) + (check (= (merge-maps a b) (merge-maps b a))))) + +(deftest "merging is associative" + (for-all ((xs gen-entries) (ys gen-entries) (zs gen-entries)) + (def a (entries->map xs)) + (def b (entries->map ys)) + (def c (entries->map zs)) + (check (= (merge-maps (merge-maps a b) c) (merge-maps a (merge-maps b c)))))) + +(deftest "merging twice changes nothing" + (for-all ((xs gen-entries) (ys gen-entries)) + (def a (merge-maps (entries->map xs) (entries->map ys))) + (check (= (merge-maps a a) a)) + (check (= (merge-maps a (entries->map ys)) a)))) + +(deftest "the order of the entries does not matter" + (for-all ((xs gen-entries)) + (check (= (entries->map xs) (entries->map (vec-reverse xs)))))) + +(deftest "each id keeps its latest stamp, so a delete is never undone by an older change" + (for-all ((xs gen-entries)) + (def merged (entries->map xs)) + (loop (:for e xs) + (:do (match (map-try-ref merged (uuid->string (entry-id e))) + ((Some kept) (check (>= (stamp-compare (.stamp kept) (.stamp e)) 0))) + (None (check-fail "an id was lost"))))))) + +(deftest "a merged document reads back as the same entries" + (for-all ((xs gen-entries)) + (def entries (map-fold (fun (k e acc) (vec-add acc e)) [] (entries->map xs))) + (def doc (DeviceDoc (device phone) (seen (map-empty)) (entries entries))) + (match (parse-device-doc (device-doc->string doc)) + ((Ok back) (check (= (entries->map (.entries back)) (entries->map entries)))) + ((Err why) (check-fail why))))) + +(run-tests) diff --git a/tests/draft.bjo b/tests/draft.bjo new file mode 100644 index 0000000..7250b01 --- /dev/null +++ b/tests/draft.bjo @@ -0,0 +1,103 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/draft.bjo — (bjomarks draft): the dialog of a bookmark, +;; and the search. +;; +;; bjo run tests/draft.bjo + +(import (std prelude)) +(import (std test)) +(import (std os)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) +(import (bjomarks store)) +(import (bjomarks draft)) + +(def cheap (KeyCost (iterations 1) (memory-kib 8))) + +;; A vault in a new folder, with the bookmarks of `urls`. Returns the vault +;; and the folder, which the test deletes. +(: (-> (Vec string) (Tuple Vault string))) +(defun (vault-with urls) + (def root (make-temp-directory #:prefix "bjomarks-draft-")) + (def v0 (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "one") "pw" #:cost cheap) + ((Ok v) v) + ((Err _) (panic! "no vault")))) + (Tuple (vec-fold (fun (url v) + (match (vault-add v url #:tags ["web"]) + ((Ok (Tuple v2 _)) v2) + ((Err why) (panic! why)))) + v0 urls) + root)) + +(: (-> Vault Draft Vault)) +(defun (applied v d) + (match (apply-draft v d) + ((Ok (Tuple v2 _)) v2) + ((Err why) (panic! why)))) + +(deftest "a new bookmark" + (def (Tuple v root) (vault-with [])) + (def d (record-set empty-draft (url " https://example.org/a ") (title "A") (tags "x, y"))) + (def v2 (applied v d)) + (def b (vec-ref (vault-bookmarks v2) 0)) + (check (= (.url b) "https://example.org/a")) + (check (= (.title b) (Some "A"))) + (check (= (.tags b) ["x" "y"])) + (check (= (.archive b) None)) + (check-match (apply-draft v (record-set empty-draft (url "not an address"))) (Err _)) + (directory-delete-tree root)) + +(deftest "typing an address that a bookmark has loads it, and another address brings back what was typed" + (def (Tuple v root) (vault-with ["https://example.org/a"])) + (def typed (record-set empty-draft (title "Mine") (tags "t"))) + (def d1 (with-address v typed "https://example.org/a")) + (check (some? (.editing d1))) + (check (= (.problem d1) address-here)) + (check (= (.tags d1) "web")) + (def d2 (with-address v d1 "https://example.org/b")) + (check (none? (.editing d2))) + (check (= (.title d2) "Mine")) + (check (= (.tags d2) "t")) + (check (= (.problem d2) "")) + ;; A dialog opened to edit a bookmark does not load another. + (def edit (draft-of (vec-ref (vault-bookmarks v) 0))) + (check (= (.editing (with-address v edit "https://example.org/a")) (.editing edit))) + (directory-delete-tree root)) + +(deftest "an edit keeps the id, and checks the archive link" + (def (Tuple v root) (vault-with ["https://example.org/a"])) + (def b (vec-ref (vault-bookmarks v) 0)) + (def edit (draft-of b)) + (def d (record-set edit (title "Ay") (archive "https://web.archive.org/web/1/https://example.org/a"))) + (def v2 (applied v d)) + (def b2 (vec-ref (vault-bookmarks v2) 0)) + (check (= (.id b2) (.id b))) + (check (= (.title b2) (Some "Ay"))) + (check (some? (.archive b2))) + (check-match (apply-draft v (record-set edit (archive "no link"))) (Err _)) + (directory-delete-tree root)) + +(deftest "fetches: started, and their results taken only when the draft waits for them" + (check (= (fetch-address (record-set empty-draft (url " example.org "))) (Some "https://example.org"))) + (check (= (fetch-address empty-draft) None)) + (check-match (start-title-fetch empty-draft 1) (Some (Err _))) + (def (Some (Ok (Tuple d url))) (start-title-fetch (record-set empty-draft (url "example.org")) 3) + :leave-with (check #f)) + (check (= url "https://example.org")) + (check (= (.fetching d) (Some 3))) + (check (none? (start-title-fetch d 4))) + (check (= (.title (with-title-fetched d 3 (Ok (Ok "Example")))) "Example")) + (check (= (.title (with-title-fetched d 2 (Ok (Ok "Old")))) "")) + (check (= (.problem (with-title-fetched d 3 (Ok (Err "timed out")))) "No title: timed out.")) + (def (Some (Ok (Tuple a _))) (start-archive-fetch d 5) + :leave-with (check #f)) + (check (= (.archive (with-archive-fetched a 5 (Ok (Ok "https://web.archive.org/x")))) "https://web.archive.org/x")) + (check (= (.archive (with-archive-fetched a 6 (Ok (Ok "https://web.archive.org/y")))) ""))) + +(deftest "tags as typed" + (check (= (split-tags "a, b,,c d") ["a" "b" "c" "d"]))) + +(run-tests) diff --git a/tests/duplicates.bjo b/tests/duplicates.bjo new file mode 100644 index 0000000..7266e45 --- /dev/null +++ b/tests/duplicates.bjo @@ -0,0 +1,135 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/duplicates.bjo — (bjomarks duplicates): two devices that +;; add one page before they sync, in folders of the temp directory. +;; +;; bjo run tests/duplicates.bjo + +(import (std prelude)) +(import (std test)) +(import (std os)) +(import (std datetime)) +(import (std uuid)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) +(import (bjomarks store)) +(import (bjomarks duplicates)) + +(def cheap (KeyCost (iterations 1) (memory-kib 8))) + +(: (-> string Instant)) +(defun (instant text) + (match (iso8601->instant text) + ((Some i) i) + (None (panic! (str "not an instant: " text))))) + +(: (-> (Result StoreError Vault) Vault)) +(defun (must r) + (match r + ((Ok v) v) + ((Err _) (panic! "no vault")))) + +;; Two devices of one vault, in a new folder. +(: (-> (Tuple string Vault Vault))) +(defun (two-devices) + (def root (make-temp-directory #:prefix "bjomarks-dup-")) + (def shared (path-combine root "shared")) + (def one (must (create-vault (folder-storage shared) (path-combine root "one") "pw" #:cost cheap))) + (def two (match (join-vault (folder-storage shared) (path-combine root "two") "pw") + ((Ok (Tuple v _)) v) + ((Err _) (panic! "no join")))) + (Tuple root one two)) + +(: (-> Vault string (Option string) (Vec string) string (Option string) Vault)) +(defun (add-page v url title tags when archive) + (match (vault-add v url #:title title #:tags tags #:added (instant when) #:archive archive) + ((Ok (Tuple v2 _)) v2) + ((Err why) (panic! why)))) + +(: (-> Vault Vault)) +(defun (synced v) (fst (vault-sync v))) + +;; Both devices see the bookmarks of both. +(: (-> Vault Vault (Tuple Vault Vault))) +(defun (exchange a b) + (def a2 (synced a)) + (def b2 (synced b)) + (Tuple (synced a2) b2)) + +(: (-> Vault string (Vec Bookmark))) +(defun (of-page v url) (vec-filter (fun (b) (= (.url b) url)) (vault-bookmarks v))) + +(deftest "one page from two devices, with one title, becomes one bookmark" + (def (Tuple root one0 two0) (two-devices)) + (def one1 (add-page one0 "https://example.org/a" (Some "A page") ["x" "web"] "2026-01-01T10:00:00Z" None)) + (def two1 (add-page two0 "https://example.org/a" None ["y" "web"] "2025-06-01T10:00:00Z" + (Some "https://web.archive.org/a"))) + (def two2 (add-page two1 "https://example.org/b" (Some "B") [] "2026-02-01T10:00:00Z" None)) + (def (Tuple one2 two3) (exchange one1 two2)) + (check (= (vec-length (of-page one2 "https://example.org/a")) 2)) + (def (Tuple one3 asked) (vault-join-duplicates one2)) + (check (vec-empty? asked)) + (def pages (of-page one3 "https://example.org/a")) + (check (= (vec-length pages) 1)) + (def b (vec-ref pages 0)) + (check (= (.title b) (Some "A page"))) + (check (= (.tags b) ["web" "x" "y"])) + (check (= (instant->unix-milliseconds (.added b)) (instant->unix-milliseconds (instant "2025-06-01T10:00:00Z")))) + (check (= (.archive b) (Some "https://web.archive.org/a"))) + (check (= (vec-length (vault-bookmarks one3)) 2)) + ;; Joining again changes nothing. + (def (Tuple one4 again) (vault-join-duplicates one3)) + (check (vec-empty? again)) + (check (not (vault-dirty? (vault-save one4)))) + (check (= (vault-revision (vault-save one4)) (vault-revision (vault-save one3)))) + ;; The other device joins it too, the same way, and they agree. + (def (Tuple two4 _) (vault-join-duplicates two3)) + (def (Tuple one5 two5) (exchange (vault-save one4) (vault-save two4))) + (def a1 (of-page one5 "https://example.org/a")) + (def a2 (of-page two5 "https://example.org/a")) + (check (= (vec-length a1) 1)) + (check (= (vec-length a2) 1)) + (check (= (.id (vec-ref a1 0)) (.id (vec-ref a2 0)))) + (check (= (.tags (vec-ref a1 0)) (.tags (vec-ref a2 0)))) + (directory-delete-tree root)) + +(deftest "different titles are asked, and the one chosen is kept" + (def (Tuple root one0 two0) (two-devices)) + (def one1 (add-page one0 "https://example.org/a" (Some "First") ["x"] "2026-01-01T10:00:00Z" None)) + (def two1 (add-page two0 "https://example.org/a" (Some "Second") ["y"] "2026-01-02T10:00:00Z" None)) + (def (Tuple one2 _) (exchange one1 two1)) + (def (Tuple one3 asked) (vault-join-duplicates one2)) + (check (= (vec-length asked) 1)) + (def d (vec-ref asked 0)) + (check (= (duplicate-url d) "https://example.org/a")) + (check (= (duplicate-titles d) ["First" "Second"])) + (check (= (vec-length (duplicate-ids d)) 2)) + ;; Both stay, with the tags of both. + (def pages (of-page one3 "https://example.org/a")) + (check (= (vec-length pages) 2)) + (check (= (vec-length (vec-filter (fun (b) (= (.tags b) ["x" "y"])) pages)) 2)) + ;; Asked again, until a title is chosen. + (def (Tuple one4 again) (vault-join-duplicates one3)) + (check (= (vec-length again) 1)) + (def one5 (vault-choose-title one4 "https://example.org/a" (Some "Second"))) + (def kept (of-page one5 "https://example.org/a")) + (check (= (vec-length kept) 1)) + (check (= (.title (vec-ref kept 0)) (Some "Second"))) + (check (= (.tags (vec-ref kept 0)) ["x" "y"])) + (def (Tuple _ none) (vault-join-duplicates one5)) + (check (vec-empty? none)) + (directory-delete-tree root)) + +(deftest "a page with one bookmark is left alone" + (def (Tuple root one0 _) (two-devices)) + (def one1 (vault-save (add-page one0 "https://example.org/a" (Some "A") [] "2026-01-01T10:00:00Z" None))) + (def one2 (add-page one1 "https://example.org/a/" (Some "A") [] "2026-01-01T10:00:00Z" None)) + (def (Tuple one3 asked) (vault-join-duplicates one2)) + (check (vec-empty? asked)) + (check (= (vec-length (vault-bookmarks one3)) 2)) + (check (= (vault-choose-title one3 "https://example.org/a" (Some "B")) one3)) + (directory-delete-tree root)) + +(run-tests) diff --git a/tests/import.bjo b/tests/import.bjo new file mode 100644 index 0000000..d848b7d --- /dev/null +++ b/tests/import.bjo @@ -0,0 +1,181 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/import.bjo — (bjomarks import): Firefox's JSON backup, and +;; an import into a vault. +;; +;; bjo run tests/import.bjo +;; +;; The backup here is made up, in the shape Firefox writes: the fields of +;; each node, the four top folders with a "root" field, and dates in +;; microseconds. + +(import (std prelude)) +(import (std test)) +(import (std datetime)) +(import (std os)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) +(import (bjomarks store)) +(import (bjomarks import)) + +(: (-> long Instant)) +(defun (at-seconds s) + (match (unix-microseconds->instant (* s 1000000L)) + ((Some i) i) + (None (panic! "no instant")))) + +;; The instant given to a bookmark with no date. +(def fallback (at-seconds 1800000000L)) + +(def backup + """ + {"guid":"root________","title":"","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":1,"typeCode":2,"type":"text/x-moz-place-container","root":"placesRoot","children":[ + {"guid":"menu________","title":"menu","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":2,"typeCode":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[ + {"guid":"folderA00001","title":" Rust Docs ","index":0,"dateAdded":1700000000000000,"lastModified":1700000000000000, + "id":7,"typeCode":2,"type":"text/x-moz-place-container","children":[ + {"guid":"bookmark0001","title":"The Book","index":0,"dateAdded":1700000100000000,"lastModified":1700000100000000, + "id":8,"typeCode":1,"type":"text/x-moz-place","uri":"https://doc.rust-lang.org/book/","tags":"Rust,Must Read"}, + {"guid":"folderB00001","title":"Async, Await","index":1,"dateAdded":1700000000000000,"lastModified":1700000000000000, + "id":9,"typeCode":2,"type":"text/x-moz-place-container","children":[ + {"guid":"bookmark0002","title":"Async book","index":0,"dateAdded":1700000200000000, + "lastModified":1700000200000000,"id":10,"typeCode":1,"type":"text/x-moz-place", + "uri":"https://rust-lang.github.io/async-book/"}]}]}, + {"guid":"separator001","title":"","index":1,"dateAdded":1700000000000000,"lastModified":1700000000000000, + "id":11,"typeCode":3,"type":"text/x-moz-place-separator"}, + {"guid":"bookmark0003","title":"Most Visited","index":2,"dateAdded":1700000000000000, + "lastModified":1700000000000000,"id":12,"typeCode":1,"type":"text/x-moz-place", + "uri":"place:sort=8&maxResults=10"}, + {"guid":"bookmark0004","title":"A bookmarklet","index":3,"dateAdded":1700000000000000, + "lastModified":1700000000000000,"id":13,"typeCode":1,"type":"text/x-moz-place", + "uri":"javascript:alert(1)","keyword":"js"}, + {"guid":"bookmark0005","title":"","index":4,"dateAdded":1700000300000000,"lastModified":1700000300000000, + "id":14,"typeCode":1,"type":"text/x-moz-place","uri":" HTTPS://Example.org/Upper "}]}, + {"guid":"toolbar_____","title":"toolbar","index":1,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":3,"typeCode":2,"type":"text/x-moz-place-container","root":"toolbarFolder","children":[ + {"guid":"bookmark0006","title":"The Rust book, again","index":0,"dateAdded":1600000000000000, + "lastModified":1600000000000000,"id":15,"typeCode":1,"type":"text/x-moz-place", + "uri":"https://doc.rust-lang.org/book/","tags":"reading"}]}, + {"guid":"unfiled_____","title":"unfiled","index":3,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":5,"typeCode":2,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[ + {"guid":"bookmark0007","title":"No date","index":0,"id":16,"typeCode":1,"type":"text/x-moz-place", + "uri":"http://example.com/"}, + {"guid":"bookmark0008","title":"Two hashes","index":1,"dateAdded":1700000400000000,"id":17,"typeCode":1, + "type":"text/x-moz-place","uri":"https://example.org/app#/page#part"}]}, + {"guid":"mobile______","title":"mobile","index":4,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":6,"typeCode":2,"type":"text/x-moz-place-container","root":"mobileFolder","children":[]}]} + """) + +(: (-> FirefoxBackup)) +(defun (read-backup) + (match (read-firefox-backup backup #:now fallback) + ((Ok b) b) + ((Err why) (panic! why)))) + +(: (-> string Imported)) +(defun (imported url) + (def found (vec-filter (fun (i) (= (.url i) url)) (.bookmarks (read-backup)))) + (if (vec-empty? found) (panic! (str "not imported: " url)) (vec-ref found 0))) + +(: (-> (Result string FirefoxBackup) string)) +(defun (error-of r) + (match r + ((Ok _) "Ok") + ((Err why) why))) + +;; ---- Tag names ----------------------------------------------------------------------- + +(deftest "a tag's name" + #:cases ((text wanted) + ("Rust" (Some "rust")) + (" Rust Docs " (Some "rust-docs")) + ("Async, Await" (Some "async-await")) + ("a\tb\nc" (Some "a-b-c")) + (",lead,and,trail," (Some "lead-and-trail")) + (" , " None) + ("" None)) + (check (= (tag-name text) wanted))) + +;; ---- Reading a backup ---------------------------------------------------------------- + +(deftest "the bookmarks of a backup, one for each address, in the order found" + (check (= (vec-map #(.url &) (.bookmarks (read-backup))) + ["https://doc.rust-lang.org/book/" "https://rust-lang.github.io/async-book/" + "HTTPS://Example.org/Upper" "http://example.com/"]))) + +(deftest "addresses that are not http or https are counted and left out" + (check (= (.not-web (read-backup)) 2))) + +(deftest "an http address that is not a URL is left out, and named with the reason" + (def invalid (.invalid (read-backup))) + (check (= (vec-map fst invalid) ["https://example.org/app#/page#part"])) + (check (vec-fold (fun (p ok) (and ok (string-contains? (snd p) "'#' is not allowed in the fragment"))) #t invalid))) + +(deftest "folders of the user's are tags, at any depth; Firefox's top folders are not" + (check (= (.tags (imported "https://rust-lang.github.io/async-book/")) ["async-await" "rust-docs"])) + (check (= (.tags (imported "http://example.com/")) []))) + +(deftest "Firefox's tags are tags, named as folders are" + (check (vec-contains? (.tags (imported "https://doc.rust-lang.org/book/")) "must-read"))) + +(deftest "an address bookmarked twice is one bookmark" + (def book (imported "https://doc.rust-lang.org/book/")) + (check (= (.copies (read-backup)) 1)) + (check (= (.tags book) ["must-read" "reading" "rust" "rust-docs"])) + (check (= (.title book) (Some "The Book"))) + (check (= (.added book) (at-seconds 1600000000L)))) + +(deftest "the date is Firefox's, in microseconds, and a bookmark with none gets now" + (check (= (.added (imported "https://rust-lang.github.io/async-book/")) (at-seconds 1700000200L))) + (check (= (.added (imported "http://example.com/")) fallback))) + +(deftest "an empty title is no title" + (check (= (.title (imported "HTTPS://Example.org/Upper")) None)) + (check (= (.title (imported "https://rust-lang.github.io/async-book/")) (Some "Async book")))) + +(deftest "what is not a backup" + #:cases ((text wanted) + ("<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<TITLE>Bookmarks" + (str "this is Firefox's HTML export, and bjomarks reads the JSON backup: in Firefox's " + "Library window, choose Import and Backup, then Backup…")) + ("[1, 2]" "not a Firefox bookmark backup: it is not an object") + ("{\"a\": 1}" "not a Firefox bookmark backup: it has no top folder")) + (check (= (error-of (read-firefox-backup text)) wanted))) + +(deftest "text that is not JSON" + (check (string-starts-with? (error-of (read-firefox-backup "{\"type\": ")) "not JSON: "))) + +;; ---- Into a vault -------------------------------------------------------------------- + +(deftest "an import adds the addresses that the vault does not have, and changes no other" + (def root (make-temp-directory #:prefix "bjomarks-import-")) + (def made (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "local") "pw" + #:cost (KeyCost (iterations 1) (memory-kib 8))) + ((Ok v) v) + ((Err _) (panic! "the vault was not made")))) + (def (Ok (Tuple v0 mine)) (vault-add made "https://doc.rust-lang.org/book/" #:tags ["mine"]) + :leave-with (check-fail "vault-add refused")) + (def (Tuple v1 report) (vault-import v0 (.bookmarks (read-backup)))) + (check (= (.added report) 3)) + (check (= (.already report) 1)) + (check (= (.refused report) [])) + (check (= (vec-length (vault-bookmarks v1)) 4)) + (check (= (match (vault-find v1 (.id mine)) ((Some b) (.tags b)) (None [])) ["mine"])) + (def async (vec-filter (fun (b) (= (.url b) "https://rust-lang.github.io/async-book/")) (vault-bookmarks v1))) + (check (= (vec-map #(.tags &) async) [["async-await" "rust-docs"]])) + (check (= (vec-map #(.title &) async) [(Some "Async book")])) + (check (= (vec-map #(.added &) async) [(at-seconds 1700000200L)])) + ;; The same backup again adds nothing. + (def (Tuple v2 again) (vault-import v1 (.bookmarks (read-backup)))) + (check (= (.added again) 0)) + (check (= (.already again) 4)) + (check (= (vec-length (vault-bookmarks v2)) 4)) + ;; And it is saved as any change is. + (check (vault-dirty? v2)) + (vault-close (fst (vault-sync v2))) + (directory-delete-tree root)) + +(run-tests) diff --git a/tests/keys.bjo b/tests/keys.bjo new file mode 100644 index 0000000..9d28e6b --- /dev/null +++ b/tests/keys.bjo @@ -0,0 +1,166 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/keys.bjo — (bjomarks keys): keys files that open, and the +;; changes to one that must make it fail. +;; +;; bjo run tests/keys.bjo +;; +;; The tests use a cost of 1 iteration over 8 KiB, so that they are quick. + +(import (std prelude)) +(import (std test)) +(import (std uuid)) +(import (bjosodium core)) +(import (bjomarks binary)) +(import (bjomarks keys)) + +(def cheap (KeyCost (iterations 1) (memory-kib 8))) + +(: (-> (Result KeysError Unlocked) string)) +(defun (outcome r) + (match r + ((Ok _) "Ok") + ((Err WrongPassword) "WrongPassword") + ((Err (BadKeys why)) why))) + +(: (-> (Array byte) (Array byte))) +(defun (copy-of a) (get-bytes a 0 (array-length a))) + +;; A copy of `a` with bit 0 of byte `at` changed. +(: (-> (Array byte) int (Array byte))) +(defun (flipped a at) + (def b (copy-of a)) + (put-u8! b at (bitwise-xor (get-u8 b at) 1)) + b) + +(: (-> (Array byte) int int (Array byte))) +(defun (with-u8 a at v) + (def b (copy-of a)) + (put-u8! b at v) + b) + +(: (-> (Array byte) int int (Array byte))) +(defun (with-u32 a at v) + (def b (copy-of a)) + (put-u32! b at v) + b) + +(deftest "a new vault opens with its password" + (def (Tuple file made) (make-keys "hunter2" #:cost cheap)) + (def (Ok opened) (unlock-keys file "hunter2") :leave-with (check-fail "it did not open")) + (check (= (.vault-id opened) (.vault-id made))) + (check (= (.key-id opened) 1)) + (check (bytes=? (.dek opened) (.dek made))) + (check (= (array-length (.dek made)) 32)) + (check (= (keys-vault-id file) (Ok (.vault-id made))))) + +(deftest "each cipher wraps the key" + #:cases ((cipher length) + (Aegis256 150) + (XChaCha20Poly1305 126)) + (def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher cipher)) + (check (= (array-length file) length)) + (check (= (get-u8 file 53) (cipher->code cipher))) + (check (= (outcome (unlock-keys file "hunter2")) "Ok")) + (check (= (outcome (unlock-keys file "hunter3")) "WrongPassword"))) + +(deftest "a wrong password" + (def (Tuple file _made) (make-keys "hunter2" #:cost cheap)) + (check (= (outcome (unlock-keys file "")) "WrongPassword")) + (check (= (outcome (unlock-keys file "Hunter2")) "WrongPassword"))) + +(deftest "two vaults have their own ids and keys" + (def (Tuple _f1 a) (make-keys "pw" #:cost cheap)) + (def (Tuple _f2 b) (make-keys "pw" #:cost cheap)) + (check (not (= (.vault-id a) (.vault-id b)))) + (check (not (bytes=? (.dek a) (.dek b))))) + +(deftest "a new password keeps the vault and its key" + (def (Tuple old made) (make-keys "old password" #:cost cheap)) + (def new (wrap-keys (.vault-id made) (.key-id made) (.dek made) "new password" #:cost cheap)) + (check (= (outcome (unlock-keys new "old password")) "WrongPassword")) + (def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open")) + (check (bytes=? (.dek opened) (.dek made))) + (check (= (.vault-id opened) (.vault-id made))) + (check (= (outcome (unlock-keys old "old password")) "Ok"))) + +;; The offsets of the fields of the one slot, which starts at 23. +(deftest "a change to a field that the slot's tag covers" + #:cases ((what at) + ("the vault id" 6) + ("the vault id's last byte" 21) + ("the key id" 27) + ("the memory" 36) + ("the salt" 37) + ("the nonce" 54) + ("the wrapped key" 90) + ("the tag" 149)) + (def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256)) + (check (= (outcome (unlock-keys (flipped file at) "hunter2")) "WrongPassword"))) + +(deftest "another cost in bounds does not open the slot" + (def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256)) + (check (= (outcome (unlock-keys (with-u32 file 29 2) "hunter2")) "WrongPassword"))) + +(deftest "what a keys file must not be" + (def (Tuple file _made) (make-keys "hunter2" #:cost cheap #:cipher Aegis256)) + (check (= (outcome (unlock-keys (make-array 0) "hunter2")) "too short for a keys file")) + (check (= (outcome (unlock-keys (flipped file 0) "hunter2")) "not a keys file")) + (check (= (outcome (unlock-keys (with-u8 file 5 2) "hunter2")) "keys file version 2 is not version 1")) + (check (= (outcome (unlock-keys (with-u8 file 22 2) "hunter2")) "a slot is cut short")) + (check (= (outcome (unlock-keys (with-u8 file 22 0) "hunter2")) "bytes after the last slot")) + (check (= (outcome (unlock-keys (get-bytes file 0 (- (array-length file) 1)) "hunter2")) "a slot is cut short")) + (check (= (outcome (unlock-keys (bytes-concat file (make-array 1)) "hunter2")) "bytes after the last slot")) + (check (= (outcome (unlock-keys (with-u8 file 53 9) "hunter2")) "unknown cipher 9")) + (check (= (outcome (unlock-keys (with-u8 file 23 2) "hunter2")) "no password slot")) + (check (= (outcome (unlock-keys (with-u8 file 28 2) "hunter2")) "no password slot")) + (check (= (outcome (unlock-keys (with-u32 file 29 1000) "hunter2")) "a slot asks for 1000 iterations")) + (check (= (outcome (unlock-keys (with-u32 file 29 0) "hunter2")) "a slot asks for 0 iterations")) + (check (= (outcome (unlock-keys (with-u32 file 33 4) "hunter2")) "a slot asks for 4 KiB")) + (check (= (outcome (unlock-keys (with-u32 file 33 -1) "hunter2")) "a slot asks for -1 KiB")) + ;; At most 1 GiB: a file of an attacker cannot make a phone use more. + (check (= (outcome (unlock-keys (with-u32 file 33 1048577) "hunter2")) "a slot asks for 1048577 KiB"))) + +(deftest "the vault id needs no password" + (def (Tuple file made) (make-keys "hunter2" #:cost cheap)) + (check (= (keys-vault-id file) (Ok (.vault-id made)))) + (check-match (keys-vault-id (flipped file 1)) (Err (BadKeys _)))) + +;; ---- A new key for a new password ------------------------------------------ + +(deftest "a new password comes with a new key, and keeps the earlier one" + (def (Tuple old made) (make-keys "old password" #:cost cheap)) + (def (Tuple new rotated) (new-keys made "new password" #:cost cheap)) + (check (= (.vault-id rotated) (.vault-id made))) + (check (not (= (.key-id rotated) (.key-id made)))) + (check (not (bytes=? (.dek rotated) (.dek made)))) + ;; The new file opens with the new password, and gives the earlier key. + (def (Ok opened) (unlock-keys new "new password") :leave-with (check-fail "it did not open")) + (check (= (.key-id opened) (.key-id rotated))) + (check (bytes=? (.dek opened) (.dek rotated))) + (check (= (vec-map fst (.earlier opened)) [1])) + (check (bytes=? (snd (vec-ref (.earlier opened) 0)) (.dek made))) + (check (= (outcome (unlock-keys new "old password")) "WrongPassword")) + ;; The old file and the old password give the old key only. + (def (Ok was) (unlock-keys old "old password") :leave-with (check-fail "the old file did not open")) + (check (= (.key-id was) 1)) + (check (vec-empty? (.earlier was))) + ;; The ids show without a password. + (check (= (keys-key-ids new) (Ok (KeyIds (current (.key-id rotated)) (earlier-ids [1]))))) + (check (= (keys-key-ids old) (Ok (KeyIds (current 1) (earlier-ids []))))) + ;; A second change keeps both, the latest first. + (def (Tuple third again) (new-keys opened "third" #:cost cheap)) + (def (Ok opened3) (unlock-keys third "third") :leave-with (check-fail "the third did not open")) + (check (= (vec-map fst (.earlier opened3)) [(.key-id rotated) 1])) + (check (= (.key-id opened3) (.key-id again)))) + +(deftest "an earlier key that was changed does not open" + (def (Tuple _old made) (make-keys "pw" #:cost cheap #:cipher Aegis256)) + (def (Tuple new _rotated) (new-keys made "pw2" #:cost cheap #:cipher Aegis256)) + ;; The second slot starts at 23 + 127; its wrapped key at 23 + 127 + 63. + (check (= (outcome (unlock-keys (flipped new (+ 150 70)) "pw2")) "the earlier key 1 does not open")) + (check (= (outcome (unlock-keys (with-u32 new 151 7) "pw2")) "the earlier key 7 does not open"))) + +(run-tests) diff --git a/tests/search.bjo b/tests/search.bjo new file mode 100644 index 0000000..bc7b475 --- /dev/null +++ b/tests/search.bjo @@ -0,0 +1,133 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/search.bjo — (bjomarks search), on a vault in the temp +;; directory. +;; +;; bjo run tests/search.bjo + +(import (std prelude)) +(import (std test)) +(import (std os)) +(import (std datetime)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) +(import (bjomarks store)) +(import (bjomarks search)) + +(def cheap (KeyCost (iterations 1) (memory-kib 8))) + +(: (-> string Instant)) +(defun (instant text) + (match (iso8601->instant text) + ((Some i) i) + (None (panic! (str "not an instant: " text))))) + +(: (-> Vault string string (Vec string) string Vault)) +(defun (add-page v url title tags when) + (match (vault-add v url #:title (if (string-empty? title) None (Some title)) #:tags tags + #:added (instant (str when "T12:00:00Z"))) + ((Ok (Tuple v2 _)) v2) + ((Err why) (panic! why)))) + +;; Bookmarks, the newest last. +(: (-> (Tuple string Vault))) +(defun (example) + (def root (make-temp-directory #:prefix "bjomarks-search-")) + (def v0 (match (create-vault (folder-storage (path-combine root "shared")) (path-combine root "here") "pw" + #:cost cheap) + ((Ok v) v) + ((Err _) (panic! "no vault")))) + (def v (vec-fold (fun (p v) (def (Tuple url title tags when) p) (add-page v url title tags when)) + v0 + [(Tuple "https://doc.rust-lang.org/book/" "The Rust Programming Language" ["rust" "docs"] "2011-03-04") + (Tuple "https://www.github.com/rust-lang/rust" "rust-lang/rust" ["code"] "2012-06-30") + (Tuple "https://gist.github.com/x/1" "A gist about async" ["rust" "async"] "2012-07-01") + (Tuple "https://example.se/kottbullar" "Köttbullar med gräddsås" ["mat"] "2013-01-15") + (Tuple "https://example.fr/cafe" "Le café" ["café" "c#"] "2014-02-28") + (Tuple "https://notgithub.io/" "" [] "2015-05-05")])) + (Tuple root v)) + +(: (-> Vault string (Vec string))) +(defun (found v text) (vec-map (fun (b) (.url b)) (search-bookmarks v text))) + +(def book "https://doc.rust-lang.org/book/") +(def repo "https://www.github.com/rust-lang/rust") +(def gist "https://gist.github.com/x/1") +(def kott "https://example.se/kottbullar") +(def cafe "https://example.fr/cafe") +(def notgh "https://notgithub.io/") + +(deftest "parsing" + (check (query-empty? (parse-query " t: tag: d: a: a:: - "))) + (def q (parse-query "Rust -t:Docs \"two words\" a:2011:2012-06 a:2012-13")) + (check (= (.words q) ["rust"])) + (check (= (vec-length (.must q)) 3)) + (check (= (vec-length (.must-not q)) 1)) + (check (= (query-problem q) "Not a date: 2012-13")) + (check (= (query-problem (parse-query "a:2012-02-30")) "Not a date: 2012-02-30")) + (check (= (query-problem (parse-query "a:2012:2013-1")) "Not a date: 2012:2013-1")) + (check (= (query-problem (parse-query "a:2012-02-29 a::2013 a:2011:")) "")) + (check (= (fold-text "Café ÉTÉ") "cafe ete")) + (check (= (fold-text "Åsa Ärlig Öl Æble Ø") "åsa ärlig öl æble ø"))) + +(deftest "typos" + (check (= (typos "rust" "rust" 1) 0)) + (check (= (typos "rsut" "rust" 1) 1)) + (check (= (typos "rst" "rust" 1) 1)) + (check (= (typos "programing" "programming" 2) 1)) + (check (= (typos "abcdef" "uvwxyz" 2) 3))) + +(deftest "words" + (def (Tuple root v) (example)) + (check (= (vec-length (found v "")) 6)) + ;; The whole word in a title first, then the newest. + (check (= (found v "rust") [repo book gist])) + (check (= (found v "RUST lang") [repo book])) + (check (= (found v "prog") [book])) + (check (= (found v "gramming") [book])) + (check (= (found v "programing") [book])) + (check (= (found v "rsut") [repo book gist])) + (check (= (found v "rsu") [])) + (check (= (found v "async") [gist])) + (check (= (found v "cafe") [cafe])) + (check (= (found v "CAFÉ") [cafe])) + ;; ö is not o, but one typo away in a long enough word. + (check (= (found v "köttbullar") [kott])) + (check (= (found v "gräddsås") [kott])) + ;; Two typos in a word of eight letters, but not in a quoted text. + (check (= (found v "graddsas") [kott])) + (check (= (found v "\"graddsas\"") [])) + (check (= (found v "\"kottbullar\"") [kott])) + (check (= (found v "\"köttbullar med\"") [kott])) + (check (= (found v "\"med köttbullar\"") [])) + (directory-delete-tree root)) + +(deftest "tags, domains and days" + (def (Tuple root v) (example)) + (check (= (found v "t:rust") [gist book])) + (check (= (found v "tag:RUST") [gist book])) + (check (= (found v "t:rus") [])) + (check (= (found v "t:cafe") [cafe])) + (check (= (found v "t:\"c#\"") [cafe])) + (check (= (found v "t:rust -t:docs") [gist])) + (check (= (found v "d:github") [notgh gist repo])) + (check (= (found v "d:github.com") [gist repo])) + (check (= (found v "d:www.github.com") [gist repo])) + (check (= (found v "d:gist.github.com") [gist])) + (check (= (found v "-d:github") [cafe kott book])) + (check (= (found v "a:2012") [gist repo])) + (check (= (found v "a:2012-06") [repo])) + (check (= (found v "a:2012-06-30") [repo])) + (check (= (found v "a:2011:2012-06") [repo book])) + (check (= (found v "a:2013:") [notgh cafe kott])) + (check (= (found v "a::2011-03-04") [book])) + (check (= (found v "a:2014-02") [cafe])) + (check (= (found v "-a:2011:2014") [notgh])) + (check (= (found v "a:2012-13") [])) + (check (= (found v "rust a:2012 d:github.com") [repo gist])) + (check (= (found v "-rust") [notgh cafe kott])) + (directory-delete-tree root)) + +(run-tests) diff --git a/tests/store.bjo b/tests/store.bjo new file mode 100644 index 0000000..7bc26ec --- /dev/null +++ b/tests/store.bjo @@ -0,0 +1,660 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/store.bjo — (bjomarks store): vaults in folders of the +;; temp directory, with two or three devices that sync through one shared +;; folder, and files that were changed, replaced or renamed. +;; +;; bjo run tests/store.bjo +;; +;; The tests use a cost of 1 iteration over 8 KiB, so that they are quick. +;; `at` sets the clock, so that the order of changes is known. + +(import (std prelude)) +(import (std test)) +(import (std os)) +(import (std datetime)) +(import (std uuid)) +(import (text json)) +(import (bjosodium core)) +(import (bjomarks binary)) +(import (bjomarks bookmark)) +(import (bjomarks keys)) +(import (bjomarks store)) + +(def cheap (KeyCost (iterations 1) (memory-kib 8))) + +(: (-> string Instant)) +(defun (instant text) + (match (iso8601->instant text) + ((Some i) i) + (None (panic! (str "not an instant: " text))))) + +;; Calls `f` with the clock at `text`. +(: (-> string (-> %a) %a)) +(defun (at text f) + (parameterize ((current-clock (fixed-clock (instant text) utc))) (f))) + +;; Three folders: the shared one and one for each of two devices. +(type (: Folders (Record (: shared string) (: one string) (: two string) (: root string)))) + +(: (-> Folders)) +(defun (folders) + (def root (make-temp-directory #:prefix "bjomarks-test-")) + (Folders (shared (path-combine root "shared")) (one (path-combine root "one")) + (two (path-combine root "two")) (root root))) + +(: (-> StoreError string)) +(defun (store-error e) + (match e + (WrongPassword "WrongPassword") + ((NoVault why) (str "NoVault: " why)) + ((VaultExists why) (str "VaultExists: " why)) + ((OtherVault why) (str "OtherVault: " why)) + ((BadFile why) (str "BadFile: " why)))) + +(: (-> (Result StoreError Vault) Vault)) +(defun (must r) + (match r + ((Ok v) v) + ((Err e) (panic! (store-error e))))) + +(: (-> (Result StoreError (Tuple Vault SyncReport)) Vault)) +(defun (must-join r) + (match r + ((Ok (Tuple v _)) v) + ((Err e) (panic! (store-error e))))) + +(: (-> Folders string Vault)) +(defun (create f local) (must (create-vault (folder-storage (.shared f)) local "hunter2" #:cost cheap))) + +(: (-> Folders string Vault)) +(defun (join f local) (must-join (join-vault (folder-storage (.shared f)) local "hunter2"))) + +(: (-> Folders string string (Result StoreError Vault))) +(defun (reopen f local password) (open-vault (folder-storage (.shared f)) local password)) + +;; A new bookmark, at the clock's time. +(: (-> Vault string (Vec string) (Tuple Vault Bookmark))) +(defun (add-bookmark v url tags) + (match (vault-add v url #:tags tags) + ((Ok r) r) + ((Err why) (panic! why)))) + +(: (-> Vault (Tuple Vault SyncReport))) +(defun (sync v) (vault-sync v)) + +(: (-> Vault Vault)) +(defun (synced v) (fst (vault-sync v))) + +(: (-> Vault (Vec string))) +(defun (urls v) (vec-map #(.url &) (vault-bookmarks v))) + +(: (-> Vault Uuid (Vec string))) +(defun (tags-of v id) + (match (vault-find v id) + ((Some b) (.tags b)) + (None [""]))) + +(: (-> Folders Vault string)) +(defun (file-of f v) (path-combine (.shared f) "devices" (device-file-name (vault-device v)))) + +;; ---- One device ----------------------------------------------------------------- + +(deftest "a new vault keeps its bookmarks" + (def f (folders)) + (def v0 (create f (.one f))) + (check (file-exists? (path-combine (.shared f) "keys.bin"))) + (check (file-exists? (file-of f v0))) + (check (= (vault-revision v0) 1L)) + (def (Tuple v1 b1) (at "2026-11-11T09:00:00Z" #(add-bookmark v0 "https://example.org/a" ["x"]))) + (def (Tuple v2 _b2) (at "2026-11-11T10:00:00Z" #(add-bookmark v1 "https://example.org/b" []))) + (check (vault-dirty? v2)) + (def v3 (vault-save v2)) + (check (not (vault-dirty? v3))) + (check (= (vault-revision v3) 2L)) + (check (= (vault-revision (vault-save v3)) 2L)) + (vault-close v3) + (def again (must (reopen f (.one f) "hunter2"))) + (check (= (urls again) ["https://example.org/b" "https://example.org/a"])) + (check (= (tags-of again (.id b1)) ["x"])) + (check (= (vault-id again) (vault-id v0))) + (check (= (vault-device again) (vault-device v0))) + (check (= (vault-revision again) 2L)) + (check (not (vault-dirty? again))) + (directory-delete-tree (.root f))) + +(deftest "a wrong password, and a device with no vault" + (def f (folders)) + (ignore (create f (.one f))) + (check (= (match (reopen f (.one f) "hunter3") ((Ok _) "Ok") ((Err e) (store-error e))) "WrongPassword")) + (check-match (reopen f (.two f) "hunter2") (Err (NoVault _))) + (check-match (join-vault (folder-storage (.two f)) (.two f) "hunter2") (Err (NoVault _))) + (check (= (match (join-vault (folder-storage (.shared f)) (path-combine (.root f) "three") "nope") + ((Ok _) "Ok") ((Err e) (store-error e))) + "WrongPassword")) + (directory-delete-tree (.root f))) + +(deftest "a vault is not made twice" + (def f (folders)) + (ignore (create f (.one f))) + (check-match (create-vault (folder-storage (.shared f)) (.two f) "pw" #:cost cheap) (Err (VaultExists _))) + (check-match (create-vault (folder-storage (path-combine (.root f) "elsewhere")) (.one f) "pw" #:cost cheap) + (Err (VaultExists _))) + (check-match (join-vault (folder-storage (.shared f)) (.one f) "hunter2") (Err (VaultExists _))) + (directory-delete-tree (.root f))) + +(deftest "changes are deleted and put" + (def f (folders)) + (def v0 (create f (.one f))) + (def (Tuple v1 b) (add-bookmark v0 "https://example.org/a" ["x"])) + (def v2 (vault-put v1 (bookmark-with-tags b ["y" " z" "y"]))) + (check (= (tags-of v2 (.id b)) ["y" "z"])) + (def v3 (vault-delete v2 (.id b))) + (check (= (urls v3) [])) + (check (= (vault-find v3 (.id b)) None)) + ;; The tombstone stays, so that the delete reaches the other devices. + (check (= (map-length (vault-entries v3)) 1)) + (check (= (vault-delete v3 (.id b)) v3)) + (directory-delete-tree (.root f))) + +(deftest "a delete is undone, and the other devices see it" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" ["x"]))) + (def before (match (map-try-ref (vault-entries a1) (uuid->string (.id b))) + ((Some e) e) + (None (panic! "no entry")))) + (def a2 (synced (at "2026-11-11T09:01:00Z" #(vault-delete a1 (.id b))))) + (def b0 (join f (.two f))) + (check (= (urls b0) [])) + (def a3 (synced (at "2026-11-11T09:02:00Z" #(vault-restore a2 before)))) + (check (= (urls a3) ["https://example.org/"])) + (check (= (tags-of a3 (.id b)) ["x"])) + ;; Bound first: `(.stamp (match ...))` makes C# that does not compile. + (def restored (match (map-try-ref (vault-entries a3) (uuid->string (.id b))) ((Some e) e) (None before))) + (check (> (stamp-compare (.stamp restored) (.stamp before)) 0)) + (def b1 (synced b0)) + (check (= (urls b1) ["https://example.org/"])) + (check (= (vault-restore a3 (deleted-entry (.stamp before) (.id b))) a3)) + (directory-delete-tree (.root f))) + +(deftest "the files are padded" + (def f (folders)) + (def v0 (create f (.one f))) + (def size (array-length (file-read-bytes (file-of f v0)))) + ;; The header, the nonce and the tag are 51 + 2 * 32 bytes for AEGIS-256, + ;; and 51 + 24 + 16 for XChaCha20-Poly1305. + (def overhead (+ 51 (cipher-nonce-length (preferred-cipher)) (cipher-tag-length (preferred-cipher)))) + (check (= (- size overhead) 16384)) + (def more (vec-fold (fun (i v) (fst (add-bookmark v (str "https://example.org/" (int->string i)) ["tag"]))) + v0 (->vec (range 0 20)))) + (def saved (vault-save more)) + (check (= (- (array-length (file-read-bytes (file-of f saved))) overhead) 16384)) + (directory-delete-tree (.root f))) + +;; ---- Two devices ------------------------------------------------------------------- + +(deftest "two devices see each other's changes" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 b1) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/one" ["x"]))) + (def a2 (vault-save a1)) + (def b0 (join f (.two f))) + (check (= (urls b0) ["https://example.org/one"])) + (check (not (= (vault-device b0) (vault-device a2)))) + (def (Tuple b1x b2) (at "2026-11-11T10:00:00Z" #(add-bookmark b0 "https://example.org/two" []))) + (def b2x (at "2026-11-11T10:01:00Z" #(vault-delete b1x (.id b1)))) + (def (Tuple b3 report-b) (sync b2x)) + (check (.wrote report-b)) + (def (Tuple a3 report-a) (sync a2)) + (check (= (.files-merged report-a) 2)) + (check (= (.entries-changed report-a) 2)) + (check (= (.problems report-a) [])) + (check (= (urls a3) ["https://example.org/two"])) + (def a4 (at "2026-11-11T11:00:00Z" #(vault-put a3 (bookmark-with-tags b2 ["new"])))) + (def a5 (synced a4)) + (def b4 (synced b3)) + (check (= (tags-of b4 (.id b2)) ["new"])) + ;; Nothing new: nothing is written. + (def (Tuple _b5 again) (sync b4)) + (check (= (.entries-changed again) 0)) + (check (not (.wrote again))) + (check (= (vault-revision a5) (vault-revision (synced a5)))) + (directory-delete-tree (.root f))) + +(deftest "a title reaches the other devices, and a later title wins" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Ok (Tuple a1 b)) (vault-add a0 "https://example.org/" #:title (Some " Example\nDomain ")) + :leave-with (check-fail "vault-add refused a good address")) + (check (= (.title b) (Some "Example Domain"))) + (def a2 (vault-save a1)) + (def b0 (join f (.two f))) + (check (= (vec-map #(.title &) (vault-bookmarks b0)) [(Some "Example Domain")])) + (def b1 (synced (vault-put b0 (bookmark-with-title b (Some "Fetched"))))) + (def a3 (synced a2)) + (check (= (vec-map #(.title &) (vault-bookmarks a3)) [(Some "Fetched")])) + (check (= (vec-map #(.title &) (vault-bookmarks b1)) [(Some "Fetched")])) + (directory-delete-tree (.root f))) + +(deftest "the later change wins, whichever device syncs first" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" []))) + (def a2 (synced a1)) + (def b0 (join f (.two f))) + ;; Both change the bookmark before either syncs. The phone's change is later. + (def a3 (at "2026-11-11T12:00:00Z" #(vault-put a2 (bookmark-with-tags b ["laptop"])))) + (def b1 (at "2026-11-11T12:00:05Z" #(vault-put b0 (bookmark-with-tags b ["phone"])))) + (def a4 (synced a3)) + (def b2 (synced b1)) + (def a5 (synced a4)) + (check (= (tags-of a5 (.id b)) ["phone"])) + (check (= (tags-of b2 (.id b)) ["phone"])) + (directory-delete-tree (.root f))) + +(deftest "a delete wins over an older change, and a later change brings it back" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 b) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/" []))) + (def a2 (synced a1)) + (def b0 (join f (.two f))) + (def a3 (at "2026-11-11T12:00:00Z" #(vault-put a2 (bookmark-with-tags b ["edited"])))) + (def b1 (at "2026-11-11T12:00:05Z" #(vault-delete b0 (.id b)))) + (def a4 (synced (synced a3))) + (def b2 (synced b1)) + (def a5 (synced a4)) + (check (= (urls a5) [])) + (check (= (urls b2) [])) + (def a6 (at "2026-11-11T13:00:00Z" #(vault-put a5 (bookmark-with-tags b ["back"])))) + (def a7 (synced a6)) + (def b3 (synced b2)) + (check (= (tags-of b3 (.id b)) ["back"])) + (check (= (tags-of a7 (.id b)) ["back"])) + (directory-delete-tree (.root f))) + +(deftest "the clock does not go back when the wall clock does" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 b) (at "2026-11-11T12:00:00Z" #(add-bookmark a0 "https://example.org/" []))) + (def a2 (synced a1)) + (def b0 (join f (.two f))) + ;; This device's clock is an hour behind. Its change is still the later one. + (def b1 (at "2026-11-11T11:00:00Z" #(vault-put b0 (bookmark-with-tags b ["after"])))) + (def b2 (synced b1)) + (def a3 (synced a2)) + (check (= (tags-of a3 (.id b)) ["after"])) + (check (= (tags-of b2 (.id b)) ["after"])) + (directory-delete-tree (.root f))) + +(deftest "a sync in the background, and the changes made while it ran" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (join f (.two f))) + (def (Tuple b1 _) (at "2026-11-11T08:00:00Z" #(add-bookmark b0 "https://example.org/from-b" []))) + (def _b2 (synced b1)) + (def (Tuple a1 first) (at "2026-11-11T09:00:00Z" #(add-bookmark a0 "https://example.org/first" []))) + ;; The sync runs on a1; meanwhile the vault becomes a2. + (def (Tuple done _) (sync a1)) + (def (Tuple a2 _) (at "2026-11-11T09:00:01Z" #(add-bookmark a1 "https://example.org/meanwhile" []))) + (def a3 (at "2026-11-11T09:00:02Z" #(vault-put a2 (bookmark-with-tags first ["edited"])))) + (def merged (vault-merge a3 done)) + (check (= (urls merged) ["https://example.org/meanwhile" "https://example.org/first" + "https://example.org/from-b"])) + (check (= (tags-of merged (.id first)) ["edited"])) + (check (vault-dirty? merged)) + (check (= (vault-revision merged) (vault-revision done))) + ;; The next sync writes the changes made while the first ran. + (def (Tuple again report) (sync merged)) + (check (.wrote report)) + (check (= (vault-revision again) (+ (vault-revision done) 1L))) + (check (not (vault-dirty? (vault-merge again again)))) + ;; Nothing changed while a sync ran: nothing more to write. + (def (Tuple done2 _) (sync again)) + (check (not (vault-dirty? (vault-merge again done2)))) + (def c0 (join f (path-combine (.root f) "three"))) + (check (= (tags-of c0 (.id first)) ["edited"])) + (directory-delete-tree (.root f))) + +;; ---- Files that are not right ------------------------------------------------------ + +(: (-> SyncReport string)) +(defun (problems-of r) (string-join (.problems r) " | ")) + +(deftest "a changed file is skipped and reported" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (join f (.two f))) + (def (Tuple b1 _) (add-bookmark b0 "https://example.org/secret" [])) + (def b2 (synced b1)) + (def path (file-of f b2)) + (def bytes (file-read-bytes path)) + (put-u8! bytes 200 (bitwise-xor (get-u8 bytes 200) 1)) + (file-write-bytes path bytes) + (def (Tuple a1 report) (sync a0)) + (check (= (urls a1) [])) + (check (= (.files-merged report) 1)) + (check (string-contains? (problems-of report) "it does not decrypt")) + (check (string-contains? (problems-of report) (device-file-name (vault-device b2)))) + (directory-delete-tree (.root f))) + +(deftest "an older copy of a file is reported, and does not undo anything" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (join f (.two f))) + (def path (file-of f b0)) + (def old (file-read-bytes path)) + (def (Tuple b1 _) (at "2026-11-11T09:00:00Z" #(add-bookmark b0 "https://example.org/kept" []))) + (def _b2 (synced b1)) + (def a1 (synced a0)) + (check (= (urls a1) ["https://example.org/kept"])) + (file-write-bytes path old) + (def (Tuple a2 report) (sync a1)) + (check (string-contains? (problems-of report) "revision 1 is older than revision 2")) + (check (= (urls a2) ["https://example.org/kept"])) + (directory-delete-tree (.root f))) + +(deftest "a file of another vault, and a file under another name" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (join f (.two f))) + (def elsewhere (path-combine (.root f) "elsewhere")) + (def other (must (create-vault (folder-storage elsewhere) (path-combine (.root f) "three") "pw" #:cost cheap))) + (def devices (path-combine (.shared f) "devices")) + (file-copy (path-combine elsewhere "devices" (device-file-name (vault-device other))) + (path-combine devices (device-file-name (vault-device other)))) + (file-copy (file-of f b0) (path-combine devices (device-file-name (uuid-v4)))) + (file-copy (file-of f b0) (path-combine devices "laptop (conflicted copy).bin")) + (file-write-text (path-combine devices "notes.txt") "not a device file") + (def (Tuple _a1 report) (sync a0)) + (def text (problems-of report)) + (check (= (vec-length (.problems report)) 3)) + (check (string-contains? text "it belongs to another vault")) + (check (string-contains? text (str "it holds the file of the device " (uuid->string (vault-device b0))))) + (check (string-contains? text "laptop (conflicted copy).bin: the name is not .bin")) + (check (= (.files-merged report) 2)) + (directory-delete-tree (.root f))) + +(deftest "a file from a newer version is reported" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (join f (.two f))) + (def path (file-of f b0)) + (def bytes (file-read-bytes path)) + (put-u16! bytes 4 2) + (file-write-bytes path bytes) + (def (Tuple _a1 report) (sync a0)) + (check (string-contains? (problems-of report) "device file version 2 is newer than this version reads (1)")) + (directory-delete-tree (.root f))) + +;; ---- Losing files ------------------------------------------------------------------ + +(deftest "a device's file that the storage lost is written again" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 _) (add-bookmark a0 "https://example.org/" [])) + (def a2 (synced a1)) + (file-delete (file-of f a2)) + (def (Tuple a3 report) (sync a2)) + (check (.wrote report)) + (check (file-exists? (file-of f a3))) + (def b0 (join f (.two f))) + (check (= (urls b0) ["https://example.org/"])) + (directory-delete-tree (.root f))) + +(deftest "a vault opens from the storage when state.bin is gone, and from the local keys when keys.bin is" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Tuple a1 _) (add-bookmark a0 "https://example.org/" [])) + (def a2 (synced a1)) + (file-delete (path-combine (.one f) "state.bin")) + (def a3 (must (reopen f (.one f) "hunter2"))) + (check (= (urls a3) ["https://example.org/"])) + (check (= (vault-revision a3) (vault-revision a2))) + (file-delete (path-combine (.shared f) "keys.bin")) + (def a4 (must (reopen f (.one f) "hunter2"))) + (def (Tuple _a5 report) (sync a4)) + (check (string-contains? (problems-of report) "keys.bin was missing")) + (check (file-exists? (path-combine (.shared f) "keys.bin"))) + (directory-delete-tree (.root f))) + +(deftest "a storage of another vault does not open" + (def f (folders)) + (ignore (create f (.one f))) + (def elsewhere (path-combine (.root f) "elsewhere")) + (ignore (create-vault (folder-storage elsewhere) (path-combine (.root f) "three") "hunter2" #:cost cheap)) + (check-match (open-vault (folder-storage elsewhere) (.one f) "hunter2") (Err (OtherVault _))) + (directory-delete-tree (.root f))) + +;; ---- Passwords -------------------------------------------------------------------- + +(: (-> Folders (Array byte))) +(defun (shared-keys f) (file-read-bytes (path-combine (.shared f) "keys.bin"))) + +(: (-> Folders (Array byte) void)) +(defun (set-shared-keys! f keys) (file-write-bytes (path-combine (.shared f) "keys.bin") keys)) + +(: (-> Folders string (Array byte))) +(defun (own-keys f local) (file-read-bytes (path-combine local "keys.bin"))) + +(: (-> (Result string Vault) Vault)) +(defun (changed r) + (match r + ((Ok v) v) + ((Err why) (panic! why)))) + +(: (-> SyncReport string bool)) +(defun (told? report text) + (not (vec-empty? (vec-filter (fun (p) (string-contains? p text)) (.problems report))))) + +(: (-> (Result StoreError Vault) Vault)) +(defun (opened r) (must r)) + +(deftest "a new password comes with a new key, and the other devices read on" + (def f (folders)) + (def a0 (fst (add-bookmark (create f (.one f)) "https://example.org/before" []))) + (def b0 (join f (.two f))) + (def old-keys (shared-keys f)) + (def a1 (changed (vault-change-password (vault-save a0) "correct horse" #:cost cheap))) + (check-match (reopen f (.one f) "hunter2") (Err WrongPassword)) + (check-match (reopen f (.one f) "correct horse") (Ok _)) + (def a2 (vault-save (fst (add-bookmark a1 "https://example.org/after" [])))) + ;; An old copy of keys.bin and the old password do not open what was + ;; written after the change. + (def (Ok old) (unlock-keys old-keys "hunter2") :leave-with (check-fail "the old keys did not open")) + (check-match (decode-device-file (file-read-bytes (file-of f a2)) (.vault-id old) + [(Tuple (.key-id old) (.dek old))]) + (Err _)) + ;; The other device, open, reads on with the key it has, and is told. + (def (Tuple b1 report) (sync b0)) + (check (told? report "The password was changed on another device")) + (def b2 (synced (fst (add-bookmark b1 "https://example.org/from-b" [])))) + ;; Its file is written with the earlier key, which the first device reads. + (def a3 (synced a2)) + (check (vec-contains? (urls a3) "https://example.org/from-b")) + (check (not (= (vault-change-password b2 "another" #:cost cheap) (Ok b2)))) + (check-match (vault-change-password b2 "another" #:cost cheap) (Err _)) + ;; The old password no longer opens it. + (check-match (reopen f (.two f) "hunter2") (Err WrongPassword)) + (def (Tuple b3 report3) (sync (opened (reopen f (.two f) "correct horse")))) + (check (= (.problems report3) [])) + (check (vec-contains? (urls b3) "https://example.org/after")) + ;; Its copy of keys.bin is the new one, so it opens without the storage too. + (check (bytes=? (own-keys f (.two f)) (shared-keys f))) + (file-delete (path-combine (.shared f) "keys.bin")) + (check-match (reopen f (.two f) "correct horse") (Ok _)) + (check-match (reopen f (.two f) "hunter2") (Err WrongPassword)) + (directory-delete-tree (.root f))) + +(deftest "two devices change the password at once, to two passwords" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (synced (fst (add-bookmark (join f (.two f)) "https://example.org/b-before" [])))) + (def original (shared-keys f)) + (def a1 (changed (vault-change-password (synced a0) "pw-a" #:cost cheap))) + (def keys-a (shared-keys f)) + ;; The other device changes it too, before it sees the first change. + (set-shared-keys! f original) + (def b1 (changed (vault-change-password b0 "pw-b" #:cost cheap))) + (def b2 (vault-save (fst (add-bookmark b1 "https://example.org/b-after" [])))) + ;; The sync keeps the first device's keys.bin. + (set-shared-keys! f keys-a) + (def (Tuple b3 report) (sync b2)) + (check (told? report "at the same time")) + ;; It writes with the key that both have, so the first device reads it. + (def a2 (synced a1)) + (check (vec-contains? (urls a2) "https://example.org/b-after")) + (vault-close b3) + ;; Its own password still opens it, from its copy of keys.bin. + (def (Tuple b4 report4) (sync (opened (reopen f (.two f) "pw-b")))) + (check (told? report4 "at the same time")) + (vault-close b4) + ;; The other device's password opens all of it. + (def (Tuple b5 report5) (sync (opened (reopen f (.two f) "pw-a")))) + (check (= (.problems report5) [])) + (check (vec-contains? (urls b5) "https://example.org/b-after")) + (check (vec-contains? (urls b5) "https://example.org/b-before")) + (check (bytes=? (own-keys f (.two f)) keys-a)) + (directory-delete-tree (.root f))) + +(deftest "two devices change the password at once, to the same password" + (def f (folders)) + (def a0 (create f (.one f))) + (def b0 (synced (join f (.two f)))) + (def original (shared-keys f)) + (def a1 (changed (vault-change-password (synced a0) "same" #:cost cheap))) + (def keys-a (shared-keys f)) + (set-shared-keys! f original) + (def b1 (changed (vault-change-password b0 "same" #:cost cheap))) + (vault-close (vault-save (fst (add-bookmark b1 "https://example.org/b-after" [])))) + (set-shared-keys! f keys-a) + ;; It opens with both keys files: its file is written with its own key. + (def (Tuple b2 report) (sync (opened (reopen f (.two f) "same")))) + (check (= (.problems report) [])) + (check (vec-contains? (urls b2) "https://example.org/b-after")) + (check (vec-contains? (urls (synced a1)) "https://example.org/b-after")) + (check (bytes=? (own-keys f (.two f)) keys-a)) + (directory-delete-tree (.root f))) + +(deftest "a keys.bin that was replaced does not lock a device out" + (def f (folders)) + (def a0 (vault-save (fst (add-bookmark (create f (.one f)) "https://example.org/a" [])))) + (def mine (own-keys f (.one f))) + ;; The same vault id, another key, and another password. + (set-shared-keys! f (wrap-keys (vault-id a0) 7 (make-aead-key XChaCha20Poly1305) "not yours" #:cost cheap)) + (def (Tuple a1 report) (sync (opened (reopen f (.one f) "hunter2")))) + (check (told? report "holds none of this device's keys")) + (check (= (urls a1) ["https://example.org/a"])) + (check (bytes=? (own-keys f (.one f)) mine)) + (check-match (reopen f (.one f) "not yours") (Err _)) + (directory-delete-tree (.root f))) + +;; ---- Fields from a newer version -------------------------------------------------- + +(deftest "fields that a newer version wrote are kept through a change" + (def f (folders)) + (def a0 (create f (.one f))) + (def (Ok unlocked) (unlock-keys (file-read-bytes (path-combine (.shared f) "keys.bin")) "hunter2") + :leave-with (check-fail "the keys did not open")) + ;; A third device, of a newer version, wrote a bookmark with a rating. + (def newer (uuid-v4)) + (def id (uuid-v4)) + (def b (Bookmark (id id) (url "https://example.org/") (title (Some "Example")) + (added (instant "2026-11-11T09:00:00Z")) (tags []) (archive None))) + (def e (Entry (stamp (Stamp (ms 1000L) (counter 0) (device newer))) (state (Live b)) + (extra [(Tuple "rating" (JsonInt 4L))]))) + (def file (encode-device-file (FileHead (head-vault (.vault-id unlocked)) (head-device newer) + (head-revision 1L) (head-key-id (.key-id unlocked)) + (head-cipher XChaCha20Poly1305)) + (.dek unlocked) + (DeviceDoc (device newer) (seen (map-empty)) (entries [e])))) + (file-write-bytes (path-combine (.shared f) "devices" (device-file-name newer)) file) + (def a1 (synced a0)) + (def a2 (synced (vault-put a1 (bookmark-with-tags b ["tagged"])))) + (match (map-try-ref (vault-entries a2) (uuid->string id)) + ((Some kept) + (check (= (.extra kept) [(Tuple "rating" (JsonInt 4L))])) + (check (= (match (.state kept) ((Live k) (.title k)) ((Deleted _) None)) (Some "Example"))) + (check (> (stamp-compare (.stamp kept) (.stamp e)) 0))) + (None (check-fail "the bookmark is gone"))) + (directory-delete-tree (.root f))) + +;; ---- A storage of functions --------------------------------------------------------- + +;; A `FunctionStorage` that keeps its files in memory, by name, as the +;; folder of Android's Storage Access Framework is kept behind Avalonia. +(: (-> (Box (Map string (Array byte))) Storage)) +(defun (memory-storage files) + (: (-> string (Option (Array byte)))) + (defun (read name) (map-try-ref (box-ref files) name)) + (: (-> string (Array byte) void)) + (defun (write name bytes) (box-set! files (map-set (box-ref files) name bytes))) + (: (-> string (Vec string))) + (defun (list-names dir) + (def prefix (str dir "/")) + (vec-map (fun (k) (string-drop k (string-count prefix))) + (vec-filter (fun (k) (string-starts-with? k prefix)) (->vec (map-keys (box-ref files)))))) + (function-storage "memory" read write list-names)) + +(deftest "two devices sync through a storage of functions" + (def root (make-temp-directory #:prefix "bjomarks-test-")) + (def files (make-box (: (map-empty) (Map string (Array byte))))) + (def storage (memory-storage files)) + (check (= (storage-label storage) "memory")) + (def a0 (must (create-vault storage (path-combine root "one") "hunter2" #:cost cheap))) + (check (some? (storage-read storage "keys.bin"))) + (check (= (storage-list storage devices-dir) [(device-file-name (vault-device a0))])) + (def a1 (synced (fst (add-bookmark a0 "https://example.org/a" ["x"])))) + (def b0 (must-join (join-vault storage (path-combine root "two") "hunter2"))) + (check (= (urls b0) ["https://example.org/a"])) + (def b1 (synced (fst (at "2026-11-11T09:00:00Z" #(add-bookmark b0 "https://example.org/b" []))))) + (check (= (vec-length (storage-list storage devices-dir)) 2)) + (def a2 (synced a1)) + (check (= (vec-sort (urls a2)) ["https://example.org/a" "https://example.org/b"])) + ;; A temporary file of a syncer, beginning with ".", is not a device's. + (storage-write storage "devices/.syncthing.x.tmp" (make-array 3)) + (check (= (vec-length (storage-list storage devices-dir)) 2)) + (def (Tuple _ report) (vault-sync b1)) + (check (vec-empty? (.problems report))) + (directory-delete-tree root)) + +(deftest "each shared folder has a device folder of its own" + (def f (folders)) + (def first (folder-storage (.shared f))) + (def second-path (path-combine (.root f) "second")) + (def second (folder-storage second-path)) + (def a (device-folder (.one f) (.shared f) first)) + (def b (device-folder (.one f) second-path second)) + (check (not (= a b))) + (check (= a (device-folder (.one f) (.shared f) first))) + (ignore (must (create-vault first a "hunter2" #:cost cheap))) + ;; The second folder is empty: a new vault, not the first one. + (check-match (open-vault second b "hunter2") (Err (NoVault _))) + (ignore (must (create-vault second b "other" #:cost cheap))) + (check (= (vec-length (vault-bookmarks (must (open-vault first a "hunter2")))) 0)) + (check-match (open-vault second b "other") (Ok _)) + (directory-delete-tree (.root f))) + +(deftest "the files of the one device folder before move to its shared folder's" + (def f (folders)) + (def first (folder-storage (.shared f))) + (def v (must (create-vault first (.one f) "hunter2" #:cost cheap))) + (def other-path (path-combine (.root f) "other")) + (def other (folder-storage other-path)) + (ignore (must (create-vault other (.two f) "pw" #:cost cheap))) + ;; A folder of another vault leaves them where they are. + (def b (device-folder (.one f) other-path other)) + (check (not (file-exists? (path-combine b "device.json")))) + (check (file-exists? (path-combine (.one f) "device.json"))) + ;; The folder of their vault gets them. + (def a (device-folder (.one f) (.shared f) first)) + (check (file-exists? (path-combine a "device.json"))) + (check (file-exists? (path-combine a "keys.bin"))) + (check (not (file-exists? (path-combine (.one f) "device.json")))) + (def again (must (open-vault first a "hunter2"))) + (check (= (vault-id again) (vault-id v))) + (directory-delete-tree (.root f))) + +(run-tests) diff --git a/tests/title.bjo b/tests/title.bjo new file mode 100644 index 0000000..c3bc515 --- /dev/null +++ b/tests/title.bjo @@ -0,0 +1,272 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/title.bjo — (bjomarks title): the title in the bytes of a +;; page, and the title fetched from a server on the loopback. +;; +;; bjo run tests/title.bjo +;; +;; The server is written here, on (std net), so that a test can make it +;; slow, make it stop after the title, or send bytes of another charset. + +(import (std prelude)) +(import (std test)) +(import (std datetime)) +(import (std net)) +(import (std ports)) +(import (only (text encodings) iso-8859-1)) +(import (bjomarks title)) + +(: (-> string (Array byte))) +(defun (bytes-of text) (string->bytes text)) + +(: (-> (Array byte) (Option string) (Option string))) +(defun (title-in bytes content-type) (page-title bytes (array-length bytes) content-type)) + +;; ---- The title in the bytes ---------------------------------------------------------- + +(deftest "the title of a page" + #:cases ((html wanted) + ("Example Domain" (Some "Example Domain")) + ("Upper Case" (Some "Upper Case")) + ("With attributes" (Some "With attributes")) + ("noAfter a longer tag" (Some "After a longer tag")) + ("\n Rust\n docs\n " (Some "Rust docs")) + ("Tom & Jerry — "Home" 's x" + (Some "Tom & Jerry — \"Home\" 's x")) + ("FirstSecond" (Some "First")) + ("none" None) + ("" None) + ("   " None) + ("Cut off" None) + ("<title" None)) + (check (= (title-in (bytes-of html) None) wanted))) + +(deftest "only the first n bytes are read" + ;; 22 bytes; the end tag is whole at 21 without its `>`. + (def bytes (bytes-of "<title>Example")) + (check (= (page-title bytes 21 None) (Some "Example"))) + (check (= (page-title bytes 20 None) None)) + (check (= (page-title bytes 0 None) None))) + +(deftest "the charset is the header's, else the page's, else UTF-8" + (def latin (string->bytes "Café crème" #:encoding iso-8859-1)) + (check (= (title-in latin (Some "text/html; charset=ISO-8859-1")) (Some "Café crème"))) + (check (= (title-in latin (Some "text/html; charset=\"windows-1252\"")) (Some "Café crème"))) + (def meta (string->bytes "Café" #:encoding iso-8859-1)) + (check (= (title-in meta (Some "text/html")) (Some "Café"))) + (def equiv (string->bytes (str "" + "Café") + #:encoding iso-8859-1)) + (check (= (title-in equiv None) (Some "Café"))) + ;; The header wins over the page. + (check (= (title-in (bytes-of "Café") (Some "text/html; charset=utf-8")) + (Some "Café"))) + ;; No charset: UTF-8. + (check (= (title-in (bytes-of "Café") None) (Some "Café"))) + ;; A charset that nothing knows: UTF-8. + (check (= (title-in (bytes-of "Café") (Some "text/html; charset=x-nothing")) (Some "Café")))) + +(deftest "bytes that are not of the charset are read as Windows-1252" + (def latin (string->bytes "Café crème" #:encoding iso-8859-1)) + (check (= (title-in latin None) (Some "Café crème"))) + (check (= (title-in latin (Some "text/html; charset=utf-8")) (Some "Café crème")))) + +;; ---- A server on the loopback ---------------------------------------------------------- + +;; What the server answers to a path. +;; - `status` is as the status line gives it: "200 OK". +;; - `headers` are whole lines, without the line break. +;; - `pieces` are written one at a time, with `pause` ms between them. +;; - `wait` ms pass before the answer starts. +;; - With `hold`, the body has no length and the connection stays open, +;; after the pieces, until the server stops. +(type (: Reply (Record (: status string) + (: headers (Vec string)) + (: pieces (Vec (Array byte))) + (: pause long) + (: wait long) + (: hold bool)))) + +(: (-> string (Vec string) (Vec (Array byte)) (#:pause long) (#:wait long) (#:hold bool) Reply)) +(defun (reply status headers pieces #:pause 0L #:wait 0L #:hold #f) + (Reply (status status) (headers headers) (pieces pieces) (pause pause) (wait wait) (hold hold))) + +(: (-> (Vec (Array byte)) Reply)) +(defun (html pieces) (reply "200 OK" ["Content-Type: text/html; charset=utf-8"] pieces)) + +(: (-> string Reply)) +(defun (reply-for path) + (match path + ("/plain" + (html [(bytes-of (str "\n" + "Tom & Jerry — Homehi"))])) + ("/moved" (reply "301 Moved Permanently" ["Location: /plain"] [])) + ("/latin1" + (reply "200 OK" ["Content-Type: text/html; charset=ISO-8859-1"] + [(string->bytes "Café crème" #:encoding iso-8859-1)])) + ("/split" + (reply "200 OK" ["Content-Type: text/html"] + [(bytes-of "Split ac") (bytes-of "ross")] + #:pause 30L)) + ("/no-type" (reply "200 OK" [] [(bytes-of "No type")])) + ("/stalls" (reply "200 OK" ["Content-Type: text/html"] [(bytes-of "Early")] #:hold #t)) + ("/missing" (reply "404 Not Found" ["Content-Type: text/html"] [(bytes-of "Not Found")])) + ("/image" (reply "200 OK" ["Content-Type: image/png"] [#[137 80 78 71]])) + ("/untitled" (html [(bytes-of "no title")])) + ;; The title starts after 600 KiB: after the most that is read. + ("/huge" (html [(bytes-of "") (: (make-array 614400) (Array byte)) (bytes-of "Too late")])) + ("/slow" (reply "200 OK" ["Content-Type: text/html"] [(bytes-of "Slow")] #:wait 5000L)) + (_ (reply "404 Not Found" [] [])))) + +;; The path of the request line: "GET /plain HTTP/1.1" gives "/plain". +(: (-> string string)) +(defun (path-of head) + (def line (match (string-split-once head "\r\n") ((Some (Tuple l _)) l) (None head))) + (def parts (string-split line " ")) + (if (>= (vec-length parts) 2) (vec-ref parts 1) "/")) + +;; Reads the request's head, to its empty line, and returns its path. +(: (-bjo-> InputPort string)) +(defbjo (request-path in) + (let go ((seen "")) + (if (string-contains? seen "\r\n\r\n") + (path-of seen) + (match (read-some in) + ((Some bs) (go (str seen (bytes->string bs)))) + (None (path-of seen)))))) + +;; Waits `ms`, or less when the server stops. +(: (-bjo-> Listener long void)) +(defbjo (pause-for l ms) + (ignore (sync (choose (wrap (timeout (milliseconds ms)) (fun (_) 0)) + (wrap (listener-closed l) (fun (_) 0)))))) + +;; Writes the reply. Returns the length of its body. +(: (-bjo-> Listener OutputPort Reply int)) +(defbjo (send l out r) + (def length (vec-fold (fun (p n) (+ n (array-length p))) 0 (.pieces r))) + (def head (str "HTTP/1.1 " (.status r) "\r\n" + (string-join (vec-map #(str & "\r\n") (.headers r)) "") + (if (.hold r) "" (str "Content-Length: " (int->string length) "\r\n")) + "Connection: close\r\n\r\n")) + (write-bytes! out (bytes-of head)) + (flush-port out) + (let go ((i 0)) + (when (< i (vec-length (.pieces r))) + (when (and (> i 0) (> (.pause r) 0L)) (pause-for l (.pause r))) + (write-bytes! out (vec-ref (.pieces r) i)) + (flush-port out) + (go (+ i 1)))) + (when (.hold r) (ignore (sync (listener-closed l)))) + length) + +(: (-bjo-> InputPort OutputPort void)) +(defbjo (closing in out) + (close-input-port in) + (close-output-port out)) + +;; One connection: one request, one reply. A client that has gone, as the +;; client of /huge has, makes a write raise; that is not a failure here. +(: (-bjo-> Listener InputPort OutputPort int)) +(defbjo (answer l in out) + (def r (reply-for (request-path in))) + (when (> (.wait r) 0L) (pause-for l (.wait r))) + (def sent (match (try (send l out r) #:catch (System.Exception)) + ((Ok n) n) + ((Err _) -1))) + (ignore (try (closing in out) #:catch (System.Exception))) + sent) + +;; Accepts until the listener closes. Each connection has a fiber of its +;; own. Returns how many there were. +(: (-bjo-> Listener int)) +(defbjo (serve l) + (let go ((n 0)) + (match (sync (choose (wrap (accept-evt l) Some) + (wrap (listener-closed l) (fun (_) None)))) + ((Some (Ok (Tuple in out))) + (ignore (bjo (answer l in out))) + (go (+ n 1))) + ((Some (Err _)) n) + (None n)))) + +;; A port that nothing listens on: one the system gave and took back. +(: (-bjo-> int)) +(defbjo (free-port) + (match (tcp-listen "127.0.0.1" 0) + ((Err e) (raise e)) + ((Ok l) + (def port (listener-port l)) + (close-listener! l) + (close-owned-or-dispose l) + port))) + +;; Starts a server, fetches the title of `path` from it with a deadline of +;; `within` seconds, and stops the server. +(: (-bjo-> string int (Result string string))) +(defbjo (fetch-served path within) + (match (tcp-listen "127.0.0.1" 0) + ((Err e) (Err (str "listen failed: " (.-Message e)))) + ((Ok l) + (with-open ((listening l)) + (def server (bjo (serve l))) + (def got (fetch-title (str "http://127.0.0.1:" (int->string (listener-port l)) path) #:within within)) + (close-listener! l) + (ignore (sync (promise-join server))) + got)))) + +(: (-> (Result Exception (Result string string)) (Result string string))) +(defun (joined r) + (match r + ((Ok got) got) + ((Err e) (Err (str "raised: " (.-Message e)))))) + +;; `fetch-title` of `path` on a new server, with 3 seconds. +(: (-> string (Result string string))) +(defun (fetched path) (joined (sync/blocking (promise-join (bjo (fetch-served path 3)))))) + +;; `fetch-title` of `url`, with no server. +(: (-> string (Result string string))) +(defun (fetched-from url) (joined (sync/blocking (promise-join (bjo (fetch-title url #:within 3)))))) + +;; ---- Fetching ----------------------------------------------------------------------- + +(deftest "a page's title, fetched" + (check (= (fetched "/plain") (Ok "Tom & Jerry — Home"))) + (check (= (fetched "/latin1") (Ok "Café crème"))) + (check (= (fetched "/split") (Ok "Split across"))) + (check (= (fetched "/no-type") (Ok "No type")))) + +(deftest "a redirect is followed" + (check (= (fetched "/moved") (Ok "Tom & Jerry — Home")))) + +(deftest "reading stops at the end of the title" + ;; The server keeps the connection open after the title, past the deadline. + (check (= (fetched "/stalls") (Ok "Early")))) + +(deftest "why a page gives no title" + (check (= (fetched "/missing") (Err "the server answered 404"))) + (check (= (fetched "/image") (Err "it is not a web page, but image/png"))) + (check (= (fetched "/untitled") (Err "the page has no title"))) + (check (= (fetched "/huge") (Err "the page has no title")))) + +(deftest "a slow server meets the deadline" + (def started (now)) + (check (= (joined (sync/blocking (promise-join (bjo (fetch-served "/slow" 1))))) + (Err "no answer in 1 second"))) + ;; The server waits 5 seconds before it answers. + (check (< (instant->unix-milliseconds (now)) (+ (instant->unix-milliseconds started) 4000L)))) + +(deftest "a server that is not there is an Err" + (def port (match (sync/blocking (promise-join (bjo (free-port)))) ((Ok p) p) ((Err e) (raise e)))) + (check-match (fetched-from (str "http://127.0.0.1:" (int->string port) "/")) (Err _))) + +(deftest "only http and https are fetched" + (check (= (fetched-from "ftp://example.org/") (Err "only http and https addresses are fetched: ftp://example.org/"))) + (check (= (fetched-from "mailto:a@example.org") + (Err "only http and https addresses are fetched: mailto:a@example.org"))) + (check (= (fetched-from "example.org") (Err "only http and https addresses are fetched: example.org")))) + +(run-tests) diff --git a/tests/wayback.bjo b/tests/wayback.bjo new file mode 100644 index 0000000..050086a --- /dev/null +++ b/tests/wayback.bjo @@ -0,0 +1,150 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks/tests/wayback.bjo — (bjomarks wayback): the snapshot in an +;; answer of the availability API, and the snapshot fetched from a server on +;; the loopback, which answers as the API does. +;; +;; bjo run tests/wayback.bjo + +(import (std prelude)) +(import (std test)) +(import (std datetime)) +(import (std net)) +(import (std ports)) +(import (bjomarks wayback)) + +;; ---- The snapshot in the answer ------------------------------------------------------ + +(def found + (str "{\"url\": \"example.com\", \"archived_snapshots\": {\"closest\": {\"status\": \"200\", " + "\"available\": true, \"url\": \"http://web.archive.org/web/20261118035140/https://example.com/\", " + "\"timestamp\": \"20261118035140\"}}}")) + +(def none-found "{\"url\": \"nothing.example\", \"archived_snapshots\": {}}") + +(deftest "the snapshot in an answer" + #:cases ((answer wanted) + (found (Ok (Some "https://web.archive.org/web/20261118035140/https://example.com/"))) + ;; An address that is https already is kept. + ("{\"archived_snapshots\": {\"closest\": {\"available\": true, \"url\": \"https://web.archive.org/web/1/x\"}}}" + (Ok (Some "https://web.archive.org/web/1/x"))) + (none-found (Ok None)) + ("{\"archived_snapshots\": {\"closest\": {\"available\": false, \"url\": \"http://web.archive.org/x\"}}}" + (Ok None)) + ("{\"archived_snapshots\": {\"closest\": {\"available\": true}}}" (Ok None)) + ("{}" (Ok None)) + ("[]" (Ok None))) + (check (= (snapshot-in answer) wanted))) + +(deftest "an answer that is not JSON is an Err" + (check-match (snapshot-in "Service Unavailable") (Err _))) + +;; ---- A server on the loopback ---------------------------------------------------------- + +;; The status, the body and the wait in ms of the answer to a request line. +;; The page asked for is in the query: `url=` and its address, in which `:` +;; and `/` are not encoded. +(: (-> string (Tuple string string long))) +(defun (answer-for line) + (cond + ((string-contains? line "url=https://example.com/here ") (Tuple "200 OK" found 0L)) + ((string-contains? line "url=https://example.com/none ") (Tuple "200 OK" none-found 0L)) + ((string-contains? line "url=https://example.com/broken ") (Tuple "503 Service Unavailable" "" 0L)) + ((string-contains? line "url=https://example.com/html ") (Tuple "200 OK" "" 0L)) + ((string-contains? line "url=https://example.com/slow ") (Tuple "200 OK" found 5000L)) + (else (Tuple "404 Not Found" "" 0L)))) + +;; Reads the request's head, to its empty line, and returns its first line. +(: (-bjo-> InputPort string)) +(defbjo (request-line in) + (let go ((seen "")) + (if (string-contains? seen "\r\n\r\n") + (match (string-split-once seen "\r\n") ((Some (Tuple l _)) l) (None seen)) + (match (read-some in) + ((Some bs) (go (str seen (bytes->string bs)))) + (None seen))))) + +;; One connection: one request, one answer. The wait ends early when the +;; server stops. +(: (-bjo-> Listener InputPort OutputPort void)) +(defbjo (answer l in out) + (def (Tuple status body wait) (answer-for (request-line in))) + (when (> wait 0L) + (ignore (sync (choose (wrap (timeout (milliseconds wait)) (fun (_) 0)) + (wrap (listener-closed l) (fun (_) 0)))))) + (def bytes (string->bytes body)) + (ignore (try (let () + (write-bytes! out (string->bytes (str "HTTP/1.1 " status "\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " (int->string (array-length bytes)) "\r\n" + "Connection: close\r\n\r\n"))) + (write-bytes! out bytes) + (flush-port out) + (close-input-port in) + (close-output-port out)) + #:catch (System.Exception)))) + +;; Accepts until the listener closes. +(: (-bjo-> Listener void)) +(defbjo (serve l) + (match (sync (choose (wrap (accept-evt l) Some) + (wrap (listener-closed l) (fun (_) None)))) + ((Some (Ok (Tuple in out))) + (ignore (bjo (answer l in out))) + (serve l)) + (_ unit))) + +;; Starts a server, asks it for the snapshot of `url` with a deadline of +;; `within` seconds, and stops the server. +(: (-bjo-> string int (Result string string))) +(defbjo (fetch-served url within) + (match (tcp-listen "127.0.0.1" 0) + ((Err e) (Err (str "listen failed: " (.-Message e)))) + ((Ok l) + (with-open ((listening l)) + (def server (bjo (serve l))) + (def api (str "http://127.0.0.1:" (int->string (listener-port l)) "/wayback/available")) + (def got (fetch-archive url #:within within #:api api)) + (close-listener! l) + (ignore (sync (promise-join server))) + got)))) + +(: (-> (Result Exception (Result string string)) (Result string string))) +(defun (joined r) + (match r + ((Ok got) got) + ((Err e) (Err (str "raised: " (.-Message e)))))) + +;; `fetch-archive` of `url` on a new server, with 3 seconds. +(: (-> string (Result string string))) +(defun (fetched url) (joined (sync/blocking (promise-join (bjo (fetch-served url 3)))))) + +;; ---- Fetching ----------------------------------------------------------------------- + +(deftest "the latest snapshot, fetched" + (check (= (fetched "https://example.com/here") + (Ok "https://web.archive.org/web/20261118035140/https://example.com/"))) + ;; The spaces at the ends are not sent. + (check (= (fetched " https://example.com/here ") + (Ok "https://web.archive.org/web/20261118035140/https://example.com/")))) + +(deftest "why there is no snapshot" + (check (= (fetched "https://example.com/none") (Err "the Wayback Machine has no copy of this page"))) + (check (= (fetched "https://example.com/broken") (Err "the Wayback Machine answered 503"))) + (check-match (fetched "https://example.com/html") (Err _))) + +(deftest "a slow API meets the deadline" + (def started (now)) + (check (= (joined (sync/blocking (promise-join (bjo (fetch-served "https://example.com/slow" 1))))) + (Err "no answer in 1 second"))) + (check (< (instant->unix-milliseconds (now)) (+ (instant->unix-milliseconds started) 4000L)))) + +(deftest "only http and https are looked up" + (check (= (joined (sync/blocking (promise-join (bjo (fetch-archive "ftp://example.org/"))))) + (Err "only http and https addresses are looked up: ftp://example.org/"))) + (check (= (joined (sync/blocking (promise-join (bjo (fetch-archive "example.org"))))) + (Err "only http and https addresses are looked up: example.org")))) + +(run-tests)