bjomarks: bookmarks, their store, search and import

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-21 21:06:11 +01:00
commit 9f7718ad8f
25 changed files with 6658 additions and 0 deletions

104
src/binary.bjo Normal file
View file

@ -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)))

583
src/bookmark.bjo Normal file
View file

@ -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))))))

203
src/draft.bjo Normal file
View file

@ -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))

132
src/duplicates.bjo Normal file
View file

@ -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)))))

231
src/import.bjo Normal file
View file

@ -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) " "))

345
src/keys.bjo Normal file
View file

@ -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))))))

435
src/search.bjo Normal file
View file

@ -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)))

987
src/store.bjo Normal file
View file

@ -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)

232
src/title.bjo Normal file
View file

@ -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 `&amp;` and `&#8212;`, 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://"))))

110
src/wayback.bjo Normal file
View file

@ -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://"))))