├── packages └── rsapi │ ├── LICENSE │ ├── rustfmt.toml │ ├── npm │ ├── darwin-x64 │ │ ├── README.md │ │ └── package.json │ ├── darwin-arm64 │ │ ├── README.md │ │ └── package.json │ ├── freebsd-x64 │ │ ├── README.md │ │ └── package.json │ ├── linux-x64-gnu │ │ ├── README.md │ │ └── package.json │ ├── win32-x64-msvc │ │ ├── README.md │ │ └── package.json │ └── linux-arm64-gnu │ │ ├── README.md │ │ └── package.json │ ├── build.rs │ ├── .npmignore │ ├── Cargo.toml │ ├── package.json │ ├── src │ ├── age_task.rs │ └── lib.rs │ ├── index.d.ts │ └── index.js ├── rsapi-impl ├── README.md ├── Cargo.toml └── src │ ├── error.rs │ ├── lib.rs │ └── graph.rs ├── rust-toolchain ├── rustfmt.toml ├── .yarnrc.yml ├── rsapi-jni ├── README.md ├── src │ ├── error.rs │ └── lib.rs └── Cargo.toml ├── scripts ├── clean.sh ├── copy_jni_libs.sh ├── publish.sh ├── copy_napi_libs.sh ├── android_build.sh └── android_build.ps1 ├── .gitignore ├── lerna.json ├── sync ├── src │ ├── lib.rs │ ├── error.rs │ ├── helpers.rs │ ├── types.rs │ ├── doh.rs │ └── sync.rs ├── Cargo.toml └── README.md ├── decrypt-cli ├── Cargo.toml ├── readme.md └── src │ └── main.rs ├── README.md ├── lsq-encryption ├── Cargo.toml └── src │ ├── error.rs │ ├── fname.rs │ └── lib.rs ├── Cargo.toml ├── .cargo └── config.toml ├── package.json ├── .github └── workflows │ └── CI.yml └── LICENSE /packages/rsapi/LICENSE: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /rsapi-impl/README.md: -------------------------------------------------------------------------------- 1 | # rsapi-impl 2 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2024-12-09 2 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | tab_spaces = 4 2 | max_width = 100 3 | edition = "2021" 4 | -------------------------------------------------------------------------------- /packages/rsapi/rustfmt.toml: -------------------------------------------------------------------------------- 1 | tab_spaces = 4 2 | max_width = 100 3 | edition = "2021" 4 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | 3 | yarnPath: .yarn/releases/yarn-4.0.1.cjs 4 | -------------------------------------------------------------------------------- /rsapi-jni/README.md: -------------------------------------------------------------------------------- 1 | # rsapi-jni 2 | 3 | Used by [capacitor-file-sync](https://github.com/logseq/capacitor-file-sync). 4 | -------------------------------------------------------------------------------- /packages/rsapi/npm/darwin-x64/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-darwin-x64` 2 | 3 | This is the **x86_64-apple-darwin** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /packages/rsapi/npm/darwin-arm64/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-darwin-arm64` 2 | 3 | This is the **aarch64-apple-darwin** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /packages/rsapi/npm/freebsd-x64/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-freebsd-x64` 2 | 3 | This is the **x86_64-unknown-freebsd** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /scripts/clean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | set -o pipefail 5 | 6 | find ./packages -iname '*.node' -exec rm -rfv {} \; 7 | -------------------------------------------------------------------------------- /scripts/copy_jni_libs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | 5 | cp -rv ./jniLibs/* ../capacitor-file-sync/android/src/main/jniLibs/ 6 | -------------------------------------------------------------------------------- /packages/rsapi/npm/linux-x64-gnu/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-linux-x64-gnu` 2 | 3 | This is the **x86_64-unknown-linux-gnu** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /packages/rsapi/npm/win32-x64-msvc/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-win32-x64-msvc` 2 | 3 | This is the **x86_64-pc-windows-msvc** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /packages/rsapi/build.rs: -------------------------------------------------------------------------------- 1 | extern crate napi_build; 2 | 3 | fn main() { 4 | static_vcruntime::metabuild(); 5 | napi_build::setup(); 6 | } 7 | -------------------------------------------------------------------------------- /packages/rsapi/npm/linux-arm64-gnu/README.md: -------------------------------------------------------------------------------- 1 | # `rsapi-linux-arm64-gnu` 2 | 3 | This is the **aarch64-unknown-linux-gnu** binary for `rsapi` 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | # Cargo.lock 3 | 4 | node_modules/ 5 | yarn.lock 6 | yarn-error.log 7 | *.node 8 | trash/ 9 | 10 | .yarn/install-state.gz 11 | -------------------------------------------------------------------------------- /packages/rsapi/.npmignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .cargo 4 | .github 5 | npm 6 | .eslintrc 7 | .prettierignore 8 | rustfmt.toml 9 | yarn.lock 10 | *.node 11 | examples 12 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "npmClient": "yarn", 3 | "version": "independent", 4 | "command": { 5 | "version": { 6 | "message": "chore(release): publish" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /scripts/publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | 5 | DIRS=$(find ./packages -type d | sort -r) 6 | 7 | for dir in $DIRS 8 | do 9 | if [ -f "$dir/package.json" ]; then 10 | echo "Publishing $dir" 11 | (cd $dir && npm publish --access public) 12 | fi 13 | done 14 | -------------------------------------------------------------------------------- /sync/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub use error::SyncError as Error; 2 | pub use sync::{reset_user, set_dev, set_prod, set_proxy, SyncClient}; 3 | 4 | mod doh; 5 | mod error; 6 | pub mod helpers; 7 | pub mod sync; 8 | pub mod types; 9 | 10 | pub type Result = std::result::Result; 11 | -------------------------------------------------------------------------------- /scripts/copy_napi_libs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | 5 | cp -v ./packages/rsapi/rsapi.darwin-arm64.node ../logseq/static/node_modules/@logseq/rsapi-darwin-arm64/ 6 | 7 | codesign -f -s - ../logseq/static/node_modules/@logseq/rsapi-darwin-arm64/rsapi.darwin-arm64.node 8 | 9 | cp -v ./packages/rsapi/index.* ../logseq/static/node_modules/@logseq/rsapi/ 10 | -------------------------------------------------------------------------------- /decrypt-cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "decrypt-cli" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | clap = { version = "4.5.13", features = ["derive"] } 10 | edn-format = "3.3.0" 11 | lsq-encryption = { path = "../lsq-encryption" } 12 | -------------------------------------------------------------------------------- /rsapi-jni/src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum Error { 5 | #[error("jni: {0}")] 6 | Jni(#[from] jni::errors::Error), 7 | #[error("io: {0}")] 8 | Io(#[from] std::io::Error), 9 | #[error("lsq encryption: {0}")] 10 | Encrypt(#[from] lsq_encryption::error::Error), 11 | #[error("sync: {0}")] 12 | Sync(#[from] rsapi_impl::error::Error), 13 | #[error("{0}")] 14 | Other(String), 15 | } 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rsapi 2 | 3 | This Project contains the following exported libraries: 4 | 5 | - rsapi: @logseq/rsapi napi node package 6 | - rsapi-jni: rsapi for Android JNI 7 | - lsq-encryption: file encryption based on [age-encryption](http://age-encryption.org/) 8 | 9 | ## npm matrix 10 | 11 | ``` 12 | darwin-arm64 13 | darwin-x64 14 | linux-arm64-gnu 15 | linux-x64-gnu 16 | win32-x64-msvc 17 | freebsd-x64-gnu 18 | ``` 19 | 20 | ## How to Build 21 | 22 | TODO 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/darwin-x64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-darwin-x64", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "darwin" 10 | ], 11 | "cpu": [ 12 | "x64" 13 | ], 14 | "main": "rsapi.darwin-x64.node", 15 | "files": [ 16 | "rsapi.darwin-x64.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/freebsd-x64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-freebsd-x64", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "freebsd" 10 | ], 11 | "cpu": [ 12 | "x64" 13 | ], 14 | "main": "rsapi.freebsd-x64.node", 15 | "files": [ 16 | "rsapi.freebsd-x64.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/darwin-arm64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-darwin-arm64", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "darwin" 10 | ], 11 | "cpu": [ 12 | "arm64" 13 | ], 14 | "main": "rsapi.darwin-arm64.node", 15 | "files": [ 16 | "rsapi.darwin-arm64.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/linux-x64-gnu/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-linux-x64-gnu", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "linux" 10 | ], 11 | "cpu": [ 12 | "x64" 13 | ], 14 | "main": "rsapi.linux-x64-gnu.node", 15 | "files": [ 16 | "rsapi.linux-x64-gnu.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/win32-x64-msvc/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-win32-x64-msvc", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "win32" 10 | ], 11 | "cpu": [ 12 | "x64" 13 | ], 14 | "main": "rsapi.win32-x64-msvc.node", 15 | "files": [ 16 | "rsapi.win32-x64-msvc.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/rsapi/npm/linux-arm64-gnu/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi-linux-arm64-gnu", 3 | "private": false, 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "version": "0.0.0", 8 | "os": [ 9 | "linux" 10 | ], 11 | "cpu": [ 12 | "arm64" 13 | ], 14 | "main": "rsapi.linux-arm64-gnu.node", 15 | "files": [ 16 | "rsapi.linux-arm64-gnu.node" 17 | ], 18 | "license": "MIT", 19 | "engines": { 20 | "node": ">= 10" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lsq-encryption/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2021" 3 | name = "lsq-encryption" 4 | version = "0.0.1" 5 | 6 | [dependencies] 7 | thiserror = "1" 8 | napi = { version = "2", default-features = false, optional = true } 9 | md-5 = "0.10" 10 | age = { version = "0.9.2", features = ["armor"] } 11 | secrecy = "0.8.0" 12 | x25519-dalek = "1" 13 | chacha20poly1305 = "0.10" 14 | hex = "0.4" 15 | unicode-normalization = "0.1" 16 | 17 | [features] 18 | default = [] 19 | napi = ["dep:napi"] 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | 2 | [workspace] 3 | members = [ 4 | "sync", 5 | "lsq-encryption", 6 | "rsapi-impl", 7 | "rsapi-jni", 8 | "packages/rsapi", 9 | "decrypt-cli", 10 | ] 11 | resolver = "2" 12 | 13 | [profile.release-jni] 14 | inherits = "release" 15 | strip = true # Automatically strip symbols from the binary. 16 | opt-level = "z" # Optimize for size. 17 | lto = true # Enable link time optimization 18 | codegen-units = 1 # Reduce parallel code generation units 19 | panic = "unwind" 20 | 21 | [profile.release] 22 | lto = true 23 | -------------------------------------------------------------------------------- /rsapi-jni/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rsapi-jni" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | name = "rsapi" 8 | crate_type = ["cdylib"] 9 | 10 | [dependencies] 11 | thiserror = "1" 12 | tokio = { version = "1", features = ["default", "fs", "rt", "rt-multi-thread"] } 13 | jni = { version = "0.20", default-features = false } 14 | log = "0.4" 15 | 16 | lsq-encryption = { path = "../lsq-encryption" } 17 | rsapi-impl = { path = "../rsapi-impl" } 18 | 19 | [target.'cfg(target_os = "android")'.dependencies] 20 | android_log-sys = { version = "0.3" } 21 | -------------------------------------------------------------------------------- /sync/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sync" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | reqwest = { version = "0.11.14", default-features = false, features = [ 8 | "json", 9 | "rustls-tls", 10 | "stream", 11 | "gzip", 12 | "socks", 13 | ] } 14 | md-5 = "0.10" 15 | serde_json = "1.0" 16 | serde = { version = "1.0", features = ["derive"] } 17 | 18 | s3-presign = "0.0.2" 19 | http = "0.2" 20 | thiserror = "1.0" 21 | chrono = { version = "0.4", features = ["serde"] } 22 | anyhow = "1.0" 23 | rand = "0.8" 24 | futures = { version = "0.3", features = ["executor"] } 25 | bytes = "1.2" 26 | log = "0.4" 27 | hyper = "0.14" 28 | once_cell = "1.18.0" 29 | -------------------------------------------------------------------------------- /sync/README.md: -------------------------------------------------------------------------------- 1 | # The sync protocol 2 | 3 | ```clojure 4 | (defprotocol IRSAPI 5 | (get-local-files-meta [this graph-uuid base-path filepaths] "get local files' metadata") 6 | (get-local-all-files-meta [this graph-uuid base-path] "get all local files' metadata") 7 | (rename-local-file [this graph-uuid base-path from to access-token]) 8 | (update-local-file [this graph-uuid base-path filepath access-token] "remote -> local") 9 | (delete-local-file [this graph-uuid base-path filepath access-token]) 10 | (update-remote-file [this graph-uuid base-path filepath local-txid access-token] "local -> remote") 11 | (delete-remote-file [this graph-uuid base-path filepath local-txid access-token])) 12 | ``` 13 | -------------------------------------------------------------------------------- /rsapi-impl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rsapi-impl" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { version = "1", features = ["derive"] } 8 | tokio = { version = "1", features = ["default", "fs", "macros"] } 9 | futures = "0.3" 10 | md-5 = "0.10" 11 | walkdir = "2" 12 | dunce = "1.0.2" 13 | once_cell = "1.14.0" 14 | thiserror = "1" 15 | 16 | napi = { version = "2", default-features = false, optional = true } 17 | napi-derive = { version = "2", optional = true } 18 | 19 | lsq-encryption = { path = "../lsq-encryption" } 20 | sync = { path = "../sync" } 21 | unicode-normalization = "0.1" 22 | log = "0.4" 23 | 24 | [features] 25 | default = [] 26 | napi = ["dep:napi", "dep:napi-derive"] 27 | -------------------------------------------------------------------------------- /packages/rsapi/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2021" 3 | name = "rsapi" 4 | version = "0.0.1" 5 | 6 | [lib] 7 | crate-type = ["cdylib"] 8 | 9 | [dependencies] 10 | # Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix 11 | napi = { version = "2", default-features = false, features = [ 12 | "napi4", 13 | "tokio_rt", 14 | "serde-json", 15 | "async", 16 | "experimental", 17 | ] } 18 | napi-derive = "2" 19 | 20 | dunce = "1.0.4" 21 | rayon = "1.8" 22 | log = "0.4" 23 | 24 | lsq-encryption = { path = "../../lsq-encryption", features = ["napi"] } 25 | rsapi-impl = { path = "../../rsapi-impl", features = ["napi"] } 26 | 27 | [build-dependencies] 28 | napi-build = "2" 29 | static_vcruntime = "2" 30 | -------------------------------------------------------------------------------- /rsapi-impl/src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum Error { 5 | #[error("{0}")] 6 | Encryption(#[from] lsq_encryption::Error), 7 | #[error(transparent)] 8 | SyncClient(#[from] sync::Error), 9 | #[error("graph env not set, uuid not found")] 10 | GraphNotSet, 11 | #[error("io: {0}")] 12 | Io(#[from] std::io::Error), 13 | #[error("invalid arguments")] 14 | InvalidArg, 15 | #[error("cancelled")] 16 | Cancelled, 17 | } 18 | 19 | pub type Result = std::result::Result; 20 | 21 | #[cfg(feature = "napi")] 22 | impl From for napi::Error { 23 | fn from(error: Error) -> Self { 24 | napi::Error::new(napi::Status::GenericFailure, error.to_string()) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /lsq-encryption/src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum Error { 5 | #[error("Invalid key format, cannot parse")] 6 | ParseKey, 7 | #[error("io error: {0}")] 8 | Io(#[from] std::io::Error), 9 | #[error("cannot decrypt")] 10 | Decrypt, 11 | #[error("cannot encrypt")] 12 | Encrypt, 13 | #[error("invalid arguments")] 14 | InvalidArg, 15 | #[error("cannot age decrypt: {0}")] 16 | AgeDecrypt(#[from] age::DecryptError), 17 | #[error("cannot age encrypt: {0}")] 18 | AgeEncrypt(#[from] age::EncryptError), 19 | } 20 | 21 | pub type Result = std::result::Result; 22 | 23 | #[cfg(feature = "napi")] 24 | impl From for napi::Error { 25 | fn from(error: Error) -> Self { 26 | napi::Error::new(napi::Status::InvalidArg, error.to_string()) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/rsapi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@logseq/rsapi", 3 | "publishConfig": { 4 | "access": "public" 5 | }, 6 | "version": "0.0.92", 7 | "main": "index.js", 8 | "types": "index.d.ts", 9 | "files": [ 10 | "index.js", 11 | "index.d.ts" 12 | ], 13 | "napi": { 14 | "binaryName": "rsapi", 15 | "targets": [ 16 | "x86_64-apple-darwin", 17 | "aarch64-apple-darwin", 18 | "x86_64-pc-windows-msvc", 19 | "x86_64-unknown-linux-gnu", 20 | "aarch64-unknown-linux-gnu", 21 | "x86_64-unknown-freebsd" 22 | ] 23 | }, 24 | "license": "MIT", 25 | "devDependencies": { 26 | "@napi-rs/cli": "^3.0.0-alpha.33" 27 | }, 28 | "engines": { 29 | "node": ">= 10" 30 | }, 31 | "scripts": { 32 | "artifacts": "napi artifacts -d ../../artifacts", 33 | "build": "napi build --platform --release", 34 | "build:debug": "napi build --platform", 35 | "prepublishOnly": "napi prepublish", 36 | "version": "napi version" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | # [target.'cfg(all(any(unix)))'] 2 | # rustflags = [] 3 | 4 | [target.'cfg(all(windows, target_env = "msvc"))'] 5 | rustflags = [ 6 | "-C", "target-feature=+crt-static", 7 | "-C", "link-args=/DEFAULTLIB:ucrt.lib /DEFAULTLIB:libvcruntime.lib libcmt.lib", 8 | "-C", "link-args=/NODEFAULTLIB:libvcruntimed.lib /NODEFAULTLIB:vcruntime.lib /NODEFAULTLIB:vcruntimed.lib", 9 | "-C", "link-args=/NODEFAULTLIB:libcmtd.lib /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcrtd.lib", 10 | "-C", "link-args=/NODEFAULTLIB:libucrt.lib /NODEFAULTLIB:libucrtd.lib /NODEFAULTLIB:ucrtd.lib", 11 | ] 12 | 13 | #[target.aarch64-apple-darwin] 14 | #linker = "lld" 15 | 16 | [target.aarch64-unknown-linux-gnu] 17 | linker = "aarch64-linux-gnu-gcc" 18 | 19 | # See-also: https://github.com/napi-rs/napi-rs/issues/1688 20 | # No idea why this is needed, but it is. 21 | [target.x86_64-apple-darwin] 22 | rustflags = ["-C", "link-args=-Wl,-undefined,dynamic_lookup"] 23 | 24 | [target.aarch64-apple-darwin] 25 | rustflags = ["-C", "link-args=-Wl,-undefined,dynamic_lookup"] 26 | -------------------------------------------------------------------------------- /sync/src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum SyncError { 5 | #[error("authorize failed")] 6 | Unauthorized, 7 | #[error("unknown error")] 8 | Unknown, 9 | #[error("ExpiredToken: s3 token expired")] 10 | ExpiredToken, 11 | // TODO: handle status code 12 | #[error("reqwest error: {0}")] 13 | Request(#[from] reqwest::Error), 14 | #[error("serde error: {0}")] 15 | Serde(#[from] serde_json::Error), 16 | #[error("utf8 error: {0}")] 17 | Utf8(#[from] std::str::Utf8Error), 18 | #[error("{0}")] 19 | Custom(String), 20 | #[error(transparent)] 21 | Other(#[from] anyhow::Error), 22 | } 23 | 24 | impl SyncError { 25 | pub fn from_message(message: String) -> Result { 26 | match &*message { 27 | "Unauthorized" => Err(SyncError::Unauthorized), 28 | "ExistedGraphErr" => Err(SyncError::Custom(message)), 29 | // invalid content-type 30 | "Internal Server Error" => Err(SyncError::Custom("Server Error".to_string())), 31 | _ => Err(SyncError::Custom(message)), 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /scripts/android_build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | # set the version to use the library 6 | NDK_APL_LEVEL=21 7 | 8 | cargo ndk -t aarch64-linux-android --platform ${NDK_APL_LEVEL} -- build --profile=release-jni -p rsapi-jni -Zbuild-std 9 | cargo ndk -t armv7-linux-androideabi --platform ${NDK_APL_LEVEL} -- build --profile=release-jni -p rsapi-jni -Zbuild-std 10 | cargo ndk -t i686-linux-android --platform ${NDK_APL_LEVEL} -- build --profile=release-jni -p rsapi-jni -Zbuild-std 11 | cargo ndk -t x86_64-linux-android --platform ${NDK_APL_LEVEL} -- build --profile=release-jni -p rsapi-jni -Zbuild-std 12 | 13 | jniLibs=`pwd`/jniLibs 14 | 15 | libName=librsapi.so 16 | 17 | rm -rf ${jniLibs} 18 | 19 | mkdir -p ${jniLibs} 20 | mkdir -p ${jniLibs}/arm64-v8a 21 | mkdir -p ${jniLibs}/armeabi-v7a 22 | mkdir -p ${jniLibs}/x86 23 | mkdir -p ${jniLibs}/x86_64 24 | 25 | cp target/aarch64-linux-android/release-jni/${libName} ${jniLibs}/arm64-v8a/${libName} 26 | cp target/armv7-linux-androideabi/release-jni/${libName} ${jniLibs}/armeabi-v7a/${libName} 27 | cp target/i686-linux-android/release-jni/${libName} ${jniLibs}/x86/${libName} 28 | cp target/x86_64-linux-android/release-jni/${libName} ${jniLibs}/x86_64/${libName} 29 | 30 | # STRIP=$HOME/Library/Android/sdk/ndk/*/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-strip 31 | -------------------------------------------------------------------------------- /sync/src/helpers.rs: -------------------------------------------------------------------------------- 1 | use bytes::Bytes; 2 | use futures::Stream; 3 | use std::{ 4 | pin::Pin, 5 | task::{Context, Poll}, 6 | }; 7 | 8 | /// Progressed stream of bytes. 9 | pub struct ProgressedBytesStream { 10 | inner: Vec, 11 | offset: usize, 12 | callback: Box, 13 | } 14 | 15 | impl ProgressedBytesStream { 16 | pub fn new(inner: Vec, callback: F) -> Self 17 | where 18 | F: Fn(usize, usize) + Send + Sync + 'static, 19 | { 20 | Self { 21 | inner, 22 | offset: 0, 23 | callback: Box::new(callback), 24 | } 25 | } 26 | } 27 | 28 | impl Stream for ProgressedBytesStream { 29 | type Item = Result; 30 | 31 | fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 32 | if self.offset >= self.inner.len() { 33 | return Poll::Ready(None); 34 | } 35 | 36 | let mut buf = [0; 8 * 1024]; 37 | let mut len = 0; 38 | // TODO: optimize 39 | while len < buf.len() && self.offset < self.inner.len() { 40 | buf[len] = self.inner[self.offset]; 41 | len += 1; 42 | self.offset += 1; 43 | } 44 | 45 | (self.callback)(self.offset, self.inner.len()); 46 | Poll::Ready(Some(Ok(Bytes::from(buf[..len].to_vec())))) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /decrypt-cli/readme.md: -------------------------------------------------------------------------------- 1 | # Build 2 | `cargo build --release` 3 | 4 | # How to use 5 | - requirement: encrypted-graph-data, contact the Logseq team to fetch it. 6 | 7 | ``` 8 | > /target/release/decrypt-cli -h 9 | Usage: decrypt-cli [OPTIONS] --pwd --dir 10 | 11 | Options: 12 | --pwd graph password 13 | --dir graph data dir path 14 | --dst dir to store decrypted data [default: ./decrypted] 15 | -h, --help Print help 16 | ``` 17 | 18 | ``` 19 | > /target/release/decrypt-cli --pwd --dir 20 | keys.edn: Keys { encrypted_secret_key: "-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNjcnlwdCBaRmJkNmZzUGtlbnE0S04v\nMzhCaXBBIDIwCkw0K3hZRm95cU9kdktwMTZQSGNOL3J0VTBsaWx0U2JCQTl1UFM0\nWlR4cDAKLS0tIHdaWkZ1M3kxa1BnSDRHK0JIZkRMcDMxS3RwSmhhczFRbGVWV3pV\nUHRKeXcK7qCa3dYt76DU2yeXGujkN1mMIoDIBl4XhVf2Q8x1UnftPuXMqP8Y9+2D\n21l1sd1iW6SdsNavtwFQXIqFUOuR/d0ztPx3Zkv8/rflpDPxkwweIX5FBAxx+r4A\nxNfNY1Rz5lRjgLRURR8vFA==\n-----END AGE ENCRYPTED FILE-----\n", _public_key: "age1gf0ez92csj597krdv05sgu7ge63j69lyt0d9m3tq55y96l5cyvrqcm6ysd" } 21 | secret key: AGE-SECRET-KEY-1HZVUHUUAPJEFAT46W67WC5QQHVDXQCD7UVRHJSR0DS2P3NEFJ4VSKVNTAG 22 | dst dir: "./decrypted" 23 | Generated "./decrypted/logseq/custom.css" 24 | Generated "./decrypted/logseq/config.edn" 25 | Generated "./decrypted/journals/2024_08_02.md" 26 | Generated "./decrypted/pages/contents.md" 27 | ``` 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rsapi", 3 | "packageManager": "yarn@4.0.1", 4 | "version": "0.0.0", 5 | "description": "Node & Rust bindings", 6 | "author": "Logseq devs ", 7 | "license": "MIT", 8 | "private": true, 9 | "workspaces": [ 10 | "packages/*" 11 | ], 12 | "scripts": { 13 | "artifacts": "yarn workspaces foreach -A --no-private run artifacts", 14 | "bench": "lerna run bench --concurrency 1 --stream --no-prefix", 15 | "build": "yarn workspaces foreach -A --no-private -j 1 run build", 16 | "lint": "true", 17 | "test": "true", 18 | "format": "true", 19 | "typecheck": "true" 20 | }, 21 | "devDependencies": { 22 | "@napi-rs/cli": "^3.0.0-alpha.33", 23 | "@swc-node/core": "^1.10.6", 24 | "@swc-node/register": "^1.6.8", 25 | "@swc/core": "^1.3.101", 26 | "@taplo/cli": "^0.5.2", 27 | "@types/node": "^20.8.9", 28 | "@typescript-eslint/eslint-plugin": "^6.16.0", 29 | "@typescript-eslint/parser": "^6.16.0", 30 | "ava": "^6.0.1", 31 | "benchmark": "^2.1.4", 32 | "codecov": "^3.8.3", 33 | "cross-env": "^7.0.3", 34 | "eslint": "^8.52.0", 35 | "eslint-config-prettier": "^9.0.0", 36 | "eslint-plugin-import": "^2.29.0", 37 | "eslint-plugin-prettier": "^5.0.1", 38 | "lerna": "^7.4.1", 39 | "lint-staged": "^15.0.2", 40 | "npm-run-all": "^4.1.5", 41 | "prettier": "^3.0.3", 42 | "ts-node": "^10.9.1", 43 | "tslib": "^2.6.2", 44 | "typescript": "^5.2.2" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /scripts/android_build.ps1: -------------------------------------------------------------------------------- 1 | # set the version to use the library 2 | $NDK_APL_LEVEL = 21 3 | 4 | # verify before executing this that you have the proper targets installed 5 | cargo ndk -t aarch64-linux-android --platform $NDK_APL_LEVEL -- build --release -p rsapi-jni -Zbuild-std 6 | cargo ndk -t armv7-linux-androideabi --platform $NDK_APL_LEVEL -- build --release -p rsapi-jni -Zbuild-std 7 | cargo ndk -t i686-linux-android --platform $NDK_APL_LEVEL -- build --release -p rsapi-jni -Zbuild-std 8 | cargo ndk -t x86_64-linux-android --platform $NDK_APL_LEVEL -- build --release -p rsapi-jni -Zbuild-std 9 | 10 | $jniLibs = "${pwd}\jniLibs" 11 | 12 | $libName = "librsapi.so" 13 | 14 | Remove-Item -Recurse -Force ${jniLibs} 15 | 16 | mkdir -Force ${jniLibs} 17 | mkdir -Force ${jniLibs}/arm64-v8a 18 | mkdir -Force ${jniLibs}/armeabi-v7a 19 | mkdir -Force ${jniLibs}/x86 20 | mkdir -Force ${jniLibs}/x86_64 21 | 22 | Copy-Item target/aarch64-linux-android/release/${libName} ${jniLibs}/arm64-v8a/${libName} 23 | Copy-Item target/armv7-linux-androideabi/release/${libName} ${jniLibs}/armeabi-v7a/${libName} 24 | Copy-Item target/i686-linux-android/release/${libName} ${jniLibs}/x86/${libName} 25 | Copy-Item target/x86_64-linux-android/release/${libName} ${jniLibs}/x86_64/${libName} 26 | 27 | # $STRIP = "${env:ANDROID_NDK_HOME}\toolchains\llvm\prebuilt\windows-x86_64\bin\llvm-strip.exe" 28 | # NOTE: strip is handled by cargo build profile 29 | # foreach ($lib in $(Get-ChildItem .\jniLibs\*\*.so)) { 30 | # Write-Output "Stripping ${lib}" 31 | # & $STRIP $lib.FullName 32 | # } 33 | 34 | tree /F $jniLibs 35 | 36 | Get-ChildItem .\jniLibs\*\*.so 37 | -------------------------------------------------------------------------------- /rsapi-impl/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(async_closure)] 2 | 3 | #[cfg(feature = "napi")] 4 | use napi_derive::napi; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | use crate::error::Result; 8 | pub use crate::graph::{cancel_all_requests, set_env, set_proxy, FileMeta}; 9 | use crate::graph::{Graph, GRAPHS}; 10 | 11 | pub mod error; 12 | pub mod graph; 13 | 14 | // re-exports 15 | pub use lsq_encryption::keygen; 16 | 17 | // Global progress callback 18 | pub(crate) static mut PROGRESS_CALLBACK: Option> = None; 19 | 20 | /// Download/Upload Progress Info 21 | #[cfg_attr(feature = "napi", napi(object))] 22 | #[derive(Serialize, Deserialize, Clone, Debug)] 23 | pub struct Progress { 24 | #[serde(rename = "graphUUID")] 25 | pub graph_uuid: String, 26 | pub file: String, 27 | pub r#type: &'static str, 28 | pub progress: i64, 29 | pub total: i64, 30 | pub percent: i32, 31 | } 32 | 33 | impl Progress { 34 | pub fn download(graph_uuid: &str, file: &str, progress: i64, total: i64) -> Self { 35 | Self { 36 | graph_uuid: graph_uuid.into(), 37 | file: file.into(), 38 | r#type: "download", 39 | progress, 40 | total, 41 | percent: (progress as f64 / total as f64 * 100.0) as i32, 42 | } 43 | } 44 | 45 | pub fn upload(graph_uuid: &str, file: &str, progress: i64, total: i64) -> Self { 46 | Self { 47 | graph_uuid: graph_uuid.into(), 48 | file: file.into(), 49 | r#type: "upload", 50 | progress, 51 | total, 52 | percent: (progress as f64 / total as f64 * 100.0) as i32, 53 | } 54 | } 55 | } 56 | 57 | pub fn set_progress_callback(cb: F) 58 | where 59 | F: Fn(Progress) + 'static, 60 | { 61 | unsafe { 62 | PROGRESS_CALLBACK = Some(Box::new(cb)); 63 | } 64 | } 65 | 66 | pub fn get_graph(graph_uuid: &str) -> Result<&'static Graph> { 67 | unsafe { GRAPHS.get_graph(graph_uuid) } 68 | } 69 | -------------------------------------------------------------------------------- /sync/src/types.rs: -------------------------------------------------------------------------------- 1 | use chrono::{DateTime, Utc}; 2 | use serde::{Deserialize, Serialize}; 3 | use std::collections::HashMap; 4 | 5 | #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] 6 | pub struct Graph { 7 | // error message 8 | pub(crate) message: Option, 9 | #[serde(default, rename = "StorageUsage")] 10 | pub storage_usage: u64, 11 | #[serde(default, rename = "TXId")] 12 | pub txid: i64, 13 | #[serde(default, rename = "GraphName")] 14 | pub graph_name: String, 15 | #[serde(default, rename = "GraphUUID")] 16 | pub graph_uuid: String, 17 | } 18 | 19 | #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] 20 | pub struct SimpleGraph { 21 | #[serde(default, rename = "GraphName")] 22 | pub graph_name: String, 23 | #[serde(default, rename = "GraphUUID")] 24 | pub graph_uuid: String, 25 | } 26 | 27 | impl From for SimpleGraph { 28 | fn from(graph: Graph) -> Self { 29 | SimpleGraph { 30 | graph_name: graph.graph_name, 31 | graph_uuid: graph.graph_uuid, 32 | } 33 | } 34 | } 35 | 36 | // get_temp_credential 37 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 38 | #[serde(rename_all = "PascalCase")] 39 | pub struct TempCredential { 40 | pub credentials: Credentials, 41 | pub s3_prefix: String, 42 | } 43 | 44 | /// S3 credentials 45 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 46 | #[serde(rename_all = "PascalCase")] 47 | pub struct Credentials { 48 | pub access_key_id: String, 49 | pub expiration: DateTime, 50 | pub secret_key: String, 51 | pub session_token: String, 52 | } 53 | 54 | impl Credentials { 55 | // 5min to be expired 56 | pub fn is_expired(&self) -> bool { 57 | self.expiration < Utc::now() + chrono::Duration::seconds(60 * 5) 58 | } 59 | } 60 | 61 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 62 | #[serde(rename_all = "PascalCase")] 63 | pub struct FileObject { 64 | #[serde(rename = "ETag")] 65 | pub etag: String, 66 | pub key: String, 67 | pub last_modified: DateTime, 68 | //pub storage_class: String, 69 | //pub owner: Option, 70 | pub size: u64, 71 | } 72 | 73 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 74 | pub struct UpdateFiles { 75 | pub(crate) message: Option, 76 | #[serde(default, rename = "TXId")] 77 | pub txid: i64, 78 | #[serde(default, rename = "UpdateSuccFiles")] 79 | pub updated_files: Vec, 80 | #[serde(default, rename = "UpdateFailedFiles")] 81 | failed_files: HashMap, 82 | } 83 | 84 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 85 | pub struct DeleteFiles { 86 | pub(crate) message: Option, 87 | #[serde(default, rename = "TXId")] 88 | pub txid: i64, 89 | #[serde(default, rename = "DeleteSuccFiles")] 90 | pub deleted_files: Vec, 91 | #[serde(default, rename = "DeleteFailedFiles")] 92 | failed_files: HashMap, 93 | } 94 | 95 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 96 | pub struct Transaction { 97 | #[serde(rename = "TXId")] 98 | pub txid: i64, 99 | #[serde(rename = "TXType")] 100 | pub r#type: String, 101 | #[serde(rename = "TXContent")] 102 | pub content: String, 103 | } 104 | 105 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 106 | pub(crate) struct TypicalResponse { 107 | pub message: Option, 108 | #[serde(default, rename = "TXId")] 109 | pub txid: i64, 110 | #[serde(default, flatten)] 111 | pub data: serde_json::Value, 112 | } 113 | 114 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 115 | pub struct GetObject { 116 | pub message: Option, 117 | } 118 | -------------------------------------------------------------------------------- /packages/rsapi/src/age_task.rs: -------------------------------------------------------------------------------- 1 | //! Age-encryption with user passphrase 2 | 3 | use napi::{ 4 | bindgen_prelude::{Buffer, Either}, 5 | Env, JsBuffer, JsBufferValue, Ref, Result, Task, 6 | }; 7 | use napi_derive::napi; 8 | 9 | /// Shared encrypt input and decrypt input 10 | pub enum EncryptInput { 11 | String(String), 12 | Buffer(Ref), 13 | Bytes(Vec), 14 | } 15 | 16 | impl EncryptInput { 17 | #[inline] 18 | pub fn from_either(input: Either) -> Result { 19 | match input { 20 | Either::A(s) => Ok(Self::String(s)), 21 | Either::B(b) => Ok(Self::Buffer(b.into_ref()?)), 22 | } 23 | } 24 | } 25 | 26 | impl AsRef<[u8]> for EncryptInput { 27 | #[inline] 28 | fn as_ref(&self) -> &[u8] { 29 | match self { 30 | Self::String(s) => s.as_bytes(), 31 | Self::Buffer(b) => b.as_ref(), 32 | Self::Bytes(b) => b.as_slice(), 33 | } 34 | } 35 | } 36 | 37 | pub struct EncryptTask { 38 | buf: EncryptInput, 39 | passphrase: String, 40 | } 41 | 42 | impl EncryptTask { 43 | #[inline] 44 | pub fn new(passphrase: String, buf: EncryptInput) -> EncryptTask { 45 | EncryptTask { buf, passphrase } 46 | } 47 | 48 | #[inline] 49 | pub fn encrypt(passphrase: &str, buf: &[u8]) -> Result> { 50 | Ok(lsq_encryption::encrypt_with_user_passphrase(passphrase, buf, true)?.to_vec()) 51 | } 52 | } 53 | 54 | #[napi] 55 | impl Task for EncryptTask { 56 | // output of compute fn 57 | type Output = Vec; 58 | // output of resolve fn 59 | type JsValue = Buffer; 60 | 61 | fn compute(&mut self) -> Result { 62 | match &self.buf { 63 | EncryptInput::String(s) => Self::encrypt(&self.passphrase, s.as_bytes()), 64 | EncryptInput::Buffer(buf) => Self::encrypt(&self.passphrase, buf.as_ref()), 65 | EncryptInput::Bytes(b) => Self::encrypt(&self.passphrase, b), 66 | } 67 | } 68 | 69 | fn resolve(&mut self, _env: Env, output: Self::Output) -> Result { 70 | Ok(output.into()) 71 | } 72 | 73 | fn finally(&mut self, env: Env) -> Result<()> { 74 | if let EncryptInput::Buffer(buf) = &mut self.buf { 75 | buf.unref(env)?; 76 | } 77 | Ok(()) 78 | } 79 | } 80 | 81 | // for decryption 82 | 83 | pub struct DecryptTask { 84 | buf: EncryptInput, 85 | passphrase: String, 86 | } 87 | 88 | impl DecryptTask { 89 | #[inline] 90 | pub fn new(passphrase: String, buf: EncryptInput) -> DecryptTask { 91 | DecryptTask { buf, passphrase } 92 | } 93 | 94 | #[inline] 95 | pub fn decrypt(passphrase: &str, buf: &[u8]) -> Result> { 96 | Ok(lsq_encryption::decrypt_with_user_passphrase(passphrase, buf)?.to_vec()) 97 | } 98 | } 99 | 100 | #[napi] 101 | impl Task for DecryptTask { 102 | // output of compute fn 103 | type Output = Vec; 104 | // output of resolve fn 105 | type JsValue = Buffer; 106 | 107 | fn compute(&mut self) -> Result { 108 | match &self.buf { 109 | EncryptInput::String(s) => Self::decrypt(&self.passphrase, s.as_bytes()), 110 | EncryptInput::Buffer(buf) => Self::decrypt(&self.passphrase, buf.as_ref()), 111 | EncryptInput::Bytes(b) => Self::decrypt(&self.passphrase, b), 112 | } 113 | } 114 | 115 | fn resolve(&mut self, _env: Env, output: Self::Output) -> Result { 116 | Ok(output.into()) 117 | } 118 | 119 | fn finally(&mut self, env: Env) -> Result<()> { 120 | if let EncryptInput::Buffer(buf) = &mut self.buf { 121 | buf.unref(env)?; 122 | } 123 | Ok(()) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /lsq-encryption/src/fname.rs: -------------------------------------------------------------------------------- 1 | //! encryption/decryption for file name 2 | use md5::{Digest, Md5}; 3 | use unicode_normalization::UnicodeNormalization; 4 | 5 | use crate::{Error, Result}; 6 | 7 | pub fn md5_digest(raw: &[u8]) -> [u8; 16] { 8 | let mut hasher = Md5::new(); 9 | hasher.update(raw); 10 | let digest = hasher.finalize(); 11 | digest.into() 12 | } 13 | 14 | pub fn md5_hexdigest(raw: &[u8]) -> String { 15 | let mut hasher = Md5::new(); 16 | hasher.update(raw); 17 | let digest = hasher.finalize(); 18 | format!("{:x}", digest) 19 | } 20 | 21 | pub fn encrypt_filename(fname: &str, encryption_key: &[u8; 32]) -> Result { 22 | use chacha20poly1305::aead::{Aead, KeyInit}; 23 | use chacha20poly1305::{ChaCha20Poly1305, Nonce}; 24 | 25 | if fname.is_empty() { 26 | return Err(Error::InvalidArg); 27 | } 28 | let fname = fname.nfc().collect::(); 29 | 30 | let nonce = Nonce::from([0u8; 12]); 31 | let cipher = ChaCha20Poly1305::new(encryption_key.into()); 32 | 33 | let ciphertext = cipher 34 | .encrypt(&nonce, fname.as_bytes()) 35 | .map_err(|_| Error::Encrypt)?; 36 | Ok("e.".to_string() + &hex::encode(ciphertext.as_slice())) 37 | } 38 | 39 | pub fn decrypt_filename(encrypted_fname: &str, encryption_key: &[u8; 32]) -> Result { 40 | use chacha20poly1305::aead::{Aead, KeyInit}; 41 | use chacha20poly1305::{ChaCha20Poly1305, Nonce}; 42 | 43 | // e.<16 byte auth_tag> 44 | // also reject empty fname 45 | if !encrypted_fname.starts_with("e.") || encrypted_fname.len() <= 36 { 46 | return Err(Error::InvalidArg); 47 | } 48 | 49 | let ciphertext = 50 | hex::decode(&encrypted_fname.as_bytes()[2..]).map_err(|_| Error::InvalidArg)?; 51 | let nonce = Nonce::from([0u8; 12]); 52 | let cipher = ChaCha20Poly1305::new(encryption_key.into()); 53 | 54 | let plaintext = cipher 55 | .decrypt(&nonce, &ciphertext[..]) 56 | .map_err(|_| Error::Decrypt)?; 57 | 58 | let plaintext = String::from_utf8(plaintext).unwrap(); 59 | Ok(plaintext.nfc().collect::()) 60 | } 61 | 62 | #[cfg(test)] 63 | mod tests { 64 | use super::*; 65 | 66 | #[test] 67 | fn test_consistency() { 68 | let key = "AGE-SECRET-KEY-1KZEJZYUPL49REUU985PT673PZWSA85HGSE2Z7ZPRRRQX9MJF8DXQRRA7J0"; 69 | let raw_key = crate::to_raw_x25519_key(key).unwrap(); 70 | let encrypted = encrypt_filename("pages/contents.md", &raw_key).unwrap(); 71 | 72 | assert_eq!( 73 | encrypted, 74 | "e.6dd3a5340dd904be0e509ff824c32cdc1db108166bf58a4a8f3f5299651282ffca" 75 | ); 76 | } 77 | 78 | #[test] 79 | fn test_fname_encryption() { 80 | let key = [8u8; 32]; 81 | let fname = "logseq/config.edn"; 82 | let encrypted_fname = encrypt_filename(fname, &key).unwrap(); 83 | println!("{:?} => {:?}", fname, encrypted_fname); 84 | let decrypted_fname = decrypt_filename(&encrypted_fname, &key).unwrap(); 85 | assert_eq!(fname, decrypted_fname); 86 | } 87 | 88 | #[test] 89 | fn test_fname_encryption_unicode_normalization() { 90 | let key = "AGE-SECRET-KEY-1KZEJZYUPL49REUU985PT673PZWSA85HGSE2Z7ZPRRRQX9MJF8DXQRRA7J0"; 91 | let enc_key = crate::to_raw_x25519_key(key).unwrap(); 92 | 93 | let s1 = "プ"; // 12501, 12442 94 | let s2 = "プ"; // 12503 95 | 96 | assert_ne!(s1, s2, "s1 != s2"); 97 | 98 | let es1 = encrypt_filename(s1, &enc_key).unwrap(); 99 | let es2 = encrypt_filename(s2, &enc_key).unwrap(); 100 | 101 | assert_eq!(es1, es2, "es1 == es2"); 102 | } 103 | 104 | #[test] 105 | fn test_fname_encryption_empty() { 106 | let key = [8u8; 32]; 107 | let fname = ""; 108 | assert!(encrypt_filename(fname, &key).is_err()); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /packages/rsapi/index.d.ts: -------------------------------------------------------------------------------- 1 | /* auto-generated by NAPI-RS */ 2 | /* eslint-disable */ 3 | 4 | export function ageDecryptWithPassphrase(passphrase: string, data: Uint8Array, signal?: AbortSignal | undefined | null): Promise 5 | 6 | /** Encryption API */ 7 | export function ageEncryptWithPassphrase(passphrase: string, data: Uint8Array, signal?: AbortSignal | undefined | null): Promise 8 | 9 | export function cancelAllRequests(): Promise 10 | 11 | /** Helper */ 12 | export function canonicalizePath(filePath: string): Promise 13 | 14 | export function decryptFnames(graphUuid: string, fnames: Array): Array 15 | 16 | /** 17 | * (delete-local-file [this graph-uuid base-path filepath access-token]) 18 | * NOTE: token is not used 19 | */ 20 | export function deleteLocalFiles(graphUuid: string, basePath: string, filePaths: Array): Promise 21 | 22 | /** (delete-remote-file [this graph-uuid base-path filepath local-txid access-token]))#[napi] */ 23 | export function deleteRemoteFiles(graphUuid: string, basePath: string, filePaths: Array, txid: number, token: string): Promise 24 | 25 | export function encryptFnames(graphUuid: string, fnames: Array): Array 26 | 27 | export function fetchRemoteFiles(graphUuid: string, basePath: string, filePaths: Array, token: string): Promise> 28 | 29 | export interface FileMeta { 30 | size: number 31 | /** modified time, in milliseconds */ 32 | mtime: number 33 | /** creation time, in milliseconds */ 34 | ctime: number 35 | md5: string 36 | fname: string 37 | incomingFname: string 38 | normalizedFname: string 39 | encryptedFname: string 40 | } 41 | 42 | /** (get-local-all-files-meta [this graph-uuid base-path] "get all local files' metadata") */ 43 | export function getLocalAllFilesMeta(graphUuid: string, basePath: string): Promise> 44 | 45 | /** 46 | * get local files' metadata: file-size, md5 47 | * (get-local-files-meta [this graph-uuid base-path filepaths] "get local files' metadata") 48 | */ 49 | export function getLocalFilesMeta(graphUuid: string, basePath: string, filePaths: Array): Promise> 50 | 51 | /** Set rsapi Logger */ 52 | export function initLogger(jsLoggingFn: (...args: any[]) => any): void 53 | 54 | /** Age encryption key generation */ 55 | export function keygen(): Promise> 56 | 57 | /** Metadata for batch remote update */ 58 | export interface Metadata { 59 | fsCaseSensitive: boolean 60 | version: string 61 | revision: string 62 | platform: string 63 | } 64 | 65 | /** Download/Upload Progress Info */ 66 | export interface Progress { 67 | graphUuid: string 68 | file: string 69 | type: string 70 | progress: number 71 | total: number 72 | percent: number 73 | } 74 | 75 | /** (rename-local-file [this graph-uuid base-path from to access-token]) */ 76 | export function renameLocalFile(graphUuid: string, basePath: string, from: string, to: string): Promise 77 | 78 | /** Set dev environment along with encryption key */ 79 | export function setEnv(graphUuid: string, env: string, secretKey: string, publicKey: string): Promise 80 | 81 | export function setProgressCallback(callback: (...args: any[]) => any): void 82 | 83 | export function setProxy(proxy?: string | undefined | null): Promise 84 | 85 | /** 86 | * remote -> local 87 | * (update-local-file [this graph-uuid base-path filepath access-token] "remote -> local") 88 | */ 89 | export function updateLocalFiles(graphUuid: string, basePath: string, filePaths: Array, token: string): Promise 90 | 91 | export function updateLocalVersionFiles(graphUuid: string, basePath: string, filePaths: Array, token: string): Promise 92 | 93 | export function updateRemoteFiles(graphUuid: string, basePath: string, filePaths: Array, txid: number, token: string, metadata?: Metadata | undefined | null): Promise 94 | 95 | -------------------------------------------------------------------------------- /decrypt-cli/src/main.rs: -------------------------------------------------------------------------------- 1 | use clap::{value_parser, Arg, Command}; 2 | use std::fs; 3 | use std::path; 4 | 5 | #[derive(Debug)] 6 | struct Keys { 7 | encrypted_secret_key: String, 8 | _public_key: String, 9 | } 10 | 11 | fn read_keys>(path: P) -> Keys { 12 | let file_content = 13 | fs::read_to_string(&path).expect(&format!("Unable to read file: {:?}", path.as_ref())); 14 | let edn = edn_format::parse_str(&file_content).expect("Failed to read keys-file as edn"); 15 | match edn { 16 | edn_format::Value::Map(map) => { 17 | let edn_format::Value::String(encrypted_secret_key) = map 18 | .get(&edn_format::Value::String( 19 | "encrypted-private-key".to_string(), 20 | )) 21 | .expect("Failed to get encrypted-private-key") 22 | else { 23 | panic!("encrypted_secret_key") 24 | }; 25 | let edn_format::Value::String(public_key) = map 26 | .get(&edn_format::Value::String("public-key".to_string())) 27 | .expect("Failed to get public-key") 28 | else { 29 | panic!("public_key") 30 | }; 31 | Keys { 32 | encrypted_secret_key: encrypted_secret_key.to_owned(), 33 | _public_key: public_key.to_owned(), 34 | } 35 | } 36 | _ => { 37 | panic!("Failed to parse edn") 38 | } 39 | } 40 | } 41 | 42 | fn decrypt_file>( 43 | path: P, 44 | secret_key: &str, 45 | filename_encrypt_key: [u8; 32], 46 | dst: P, 47 | ) { 48 | let file_content = fs::read(&path).unwrap(); 49 | let decrypted_content = lsq_encryption::decrypt_with_x25519(secret_key, &file_content) 50 | .expect(&format!("Failed to decrypt: {:?}", path.as_ref())); 51 | let mut dst_path = path::PathBuf::from(dst.as_ref()); 52 | let filename = path 53 | .as_ref() 54 | .file_name() 55 | .unwrap() 56 | .to_string_lossy() 57 | .into_owned(); 58 | let decrypted_filename = 59 | lsq_encryption::decrypt_filename(&filename, &filename_encrypt_key).unwrap_or(filename); 60 | dst_path.push(decrypted_filename); 61 | let parent = dst_path.parent(); 62 | if parent.is_some() { 63 | fs::create_dir_all(parent.unwrap()) 64 | .expect(&format!("Failed to create dir: {:?}", parent.unwrap())); 65 | } 66 | fs::write(&dst_path, decrypted_content).expect(&format!("Failed to write: {:?}", dst_path)); 67 | println!("Generated {:?}", dst_path); 68 | } 69 | 70 | fn main() { 71 | let matches = Command::new("decrypt cli") 72 | .arg( 73 | Arg::new("password") 74 | .help("graph password") 75 | .long("pwd") 76 | .required(true), 77 | ) 78 | .arg( 79 | Arg::new("dir") 80 | .help("graph data dir path") 81 | .long("dir") 82 | .value_name("PATH") 83 | .required(true) 84 | .value_parser(value_parser!(path::PathBuf)), 85 | ) 86 | .arg( 87 | Arg::new("dst") 88 | .help("dir to store decrypted data") 89 | .long("dst") 90 | .value_name("PATH") 91 | .default_value("./decrypted") 92 | .value_parser(value_parser!(path::PathBuf)), 93 | ) 94 | .get_matches(); 95 | let passwd = matches.get_one::("password").unwrap(); 96 | let dir = matches.get_one::("dir").unwrap(); 97 | let dst = matches.get_one::("dst").unwrap(); 98 | let mut pathbuf = path::PathBuf::from(dir); 99 | pathbuf.push("keys.edn"); 100 | let keys_edn_path = pathbuf.to_str().unwrap(); 101 | let keys = read_keys(keys_edn_path); 102 | println!("keys.edn: {:?}", &keys); 103 | let secret_key_ = lsq_encryption::decrypt_with_user_passphrase( 104 | &passwd, 105 | &keys.encrypted_secret_key.as_bytes(), 106 | ) 107 | .expect("Failed to decrypt secret_key, wrong password"); 108 | let secret_key = std::str::from_utf8(&secret_key_).unwrap(); 109 | let filename_encrypt_key = 110 | lsq_encryption::to_raw_x25519_key(secret_key).expect("Failed to get filename encrypt key"); 111 | println!("secret key: {}", secret_key); 112 | println!("dst dir: {:?}", dst); 113 | fs::create_dir_all(dst).expect(&format!("Failed to create dir: {:?}", dst)); 114 | let entries = fs::read_dir(dir).expect(&format!("Failed to read dir: {:?}", dir)); 115 | for entry in entries { 116 | match entry { 117 | Ok(entry) => { 118 | let path = entry.path(); 119 | if path.is_file() && path.file_name().unwrap() != "keys.edn" { 120 | decrypt_file(path, secret_key, filename_encrypt_key, dst.clone()); 121 | } 122 | } 123 | _ => {} 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /lsq-encryption/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Age-encryption impl from rage-wasm 2 | use std::mem; 3 | use std::{ 4 | io::{Read, Write}, 5 | iter, 6 | }; 7 | 8 | use age::{ 9 | armor::{ArmoredReader, ArmoredWriter, Format}, 10 | x25519, Decryptor, Encryptor, 11 | }; 12 | use secrecy::{ExposeSecret, Secret}; 13 | 14 | pub use crate::error::{Error, Result}; 15 | pub use crate::fname::{decrypt_filename, encrypt_filename, md5_digest, md5_hexdigest}; 16 | 17 | pub mod error; 18 | mod fname; 19 | 20 | pub const AGE_MAGIC: &[u8] = b"age-encryption.org/"; 21 | pub const ARMORED_BEGIN_MARKER: &[u8] = b"-----BEGIN AGE ENCRYPTED FILE-----"; 22 | 23 | /// Generate (secret, public) key pairs 24 | pub fn keygen() -> (String, String) { 25 | let secret = x25519::Identity::generate(); 26 | let public = secret.to_public(); 27 | ( 28 | secret.to_string().expose_secret().clone(), 29 | public.to_string(), 30 | ) 31 | } 32 | 33 | pub fn encrypt_with_x25519(public_key: &str, data: &[u8], armor: bool) -> Result> { 34 | let key: x25519::Recipient = public_key.parse().map_err(|_| Error::ParseKey)?; 35 | let recipients = vec![Box::new(key) as Box]; 36 | let encryptor = Encryptor::with_recipients(recipients).expect("not empty; qed"); 37 | let mut output = vec![]; 38 | let format = if armor { 39 | Format::AsciiArmor 40 | } else { 41 | Format::Binary 42 | }; 43 | let armor = ArmoredWriter::wrap_output(&mut output, format)?; 44 | let mut writer = encryptor.wrap_output(armor).map_err(|_| Error::Encrypt)?; 45 | writer.write_all(data)?; 46 | writer.finish().and_then(|armor| armor.finish())?; 47 | Ok(output.into_boxed_slice()) 48 | } 49 | 50 | pub fn decrypt_with_x25519(secret_key: &str, data: &[u8]) -> Result> { 51 | let identity: x25519::Identity = secret_key.parse().map_err(|_| Error::ParseKey)?; 52 | let armor = ArmoredReader::new(data); 53 | let decryptor = match Decryptor::new(armor)? { 54 | Decryptor::Recipients(d) => d, 55 | _ => return Err(Error::Decrypt), 56 | }; 57 | let mut decrypted = vec![]; 58 | let mut reader = decryptor.decrypt(iter::once(&identity as &dyn age::Identity))?; 59 | reader.read_to_end(&mut decrypted)?; 60 | Ok(decrypted.into_boxed_slice()) 61 | } 62 | 63 | pub fn encrypt_with_user_passphrase( 64 | passphrase: &str, 65 | data: &[u8], 66 | armor: bool, 67 | ) -> Result> { 68 | let encryptor = Encryptor::with_user_passphrase(Secret::new(passphrase.to_owned())); 69 | let mut output = vec![]; 70 | let format = if armor { 71 | Format::AsciiArmor 72 | } else { 73 | Format::Binary 74 | }; 75 | let armor = ArmoredWriter::wrap_output(&mut output, format)?; 76 | let mut writer = encryptor.wrap_output(armor)?; 77 | writer.write_all(data)?; 78 | writer.finish().and_then(|armor| armor.finish())?; 79 | Ok(output.into_boxed_slice()) 80 | } 81 | 82 | pub fn decrypt_with_user_passphrase(passphrase: &str, data: &[u8]) -> Result> { 83 | let armor = ArmoredReader::new(data); 84 | let decryptor = match age::Decryptor::new(armor)? { 85 | age::Decryptor::Passphrase(d) => d, 86 | _ => return Err(Error::Decrypt), 87 | }; 88 | let mut decrypted = vec![]; 89 | // NOTE: use bigger max work factor here 90 | let mut reader = decryptor.decrypt(&Secret::new(passphrase.to_owned()), Some(100))?; 91 | reader.read_to_end(&mut decrypted)?; 92 | Ok(decrypted.into_boxed_slice()) 93 | } 94 | 95 | /// Unsafe export private x25519 key as bytes 96 | pub fn to_raw_x25519_key(secret_key: &str) -> Result<[u8; 32]> { 97 | use x25519_dalek::StaticSecret; 98 | 99 | let identity: x25519::Identity = secret_key.parse().map_err(|_| Error::ParseKey)?; 100 | let secret: &StaticSecret = unsafe { mem::transmute(&identity) }; 101 | 102 | Ok(secret.to_bytes()) 103 | } 104 | 105 | #[cfg(test)] 106 | mod tests { 107 | use super::*; 108 | 109 | #[test] 110 | fn test_keygen() { 111 | let keys = keygen(); 112 | println!("=> {:?}", keys); 113 | 114 | let raw = b"hello world"; 115 | 116 | let encrypted = encrypt_with_x25519(&keys.1, raw, false).unwrap(); 117 | let decrypted = decrypt_with_x25519(&keys.0, &encrypted).unwrap(); 118 | 119 | assert_eq!(&*decrypted, &raw[..]); 120 | } 121 | 122 | #[test] 123 | fn encryption_size_expansion() { 124 | let keys = keygen(); 125 | 126 | for i in [0, 1, 2, 3, 10, 100, 200, 300, 400, 500, 1000, 2000, 10000] { 127 | let content = vec![0u8; i]; 128 | 129 | let encrypted = encrypt_with_x25519(&keys.1, &content, true).unwrap(); 130 | let encrypted2 = encrypt_with_x25519(&keys.1, &content, false).unwrap(); 131 | 132 | println!( 133 | "size={} before={} after={}", 134 | i, 135 | encrypted.len(), 136 | encrypted2.len() 137 | ); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /sync/src/doh.rs: -------------------------------------------------------------------------------- 1 | //! A DoH client for the sync crate 2 | //! 3 | //! To be used in ClientBuilder.dns_resolver 4 | //! 5 | //! Ratioonale: Some Proxy servers has special handling of DNS requests, so we need to use DoH to bypass it. 6 | 7 | use futures::lock::Mutex; 8 | use once_cell::sync::Lazy; 9 | use std::{ 10 | collections::{HashMap, HashSet}, 11 | net::SocketAddr, 12 | sync::RwLock, 13 | time::{Duration, Instant}, 14 | }; 15 | 16 | use hyper::client::connect::dns::Name; 17 | use reqwest::{ 18 | dns::{Addrs, Resolve, Resolving}, 19 | Client, 20 | }; 21 | use serde::Deserialize; 22 | 23 | static DNS_CACHE: Lazy = Lazy::new(DNSCache::new); 24 | static DNS_HTTP_CLIENT: Lazy = Lazy::new(|| { 25 | Client::builder() 26 | .timeout(Duration::from_secs(5)) 27 | .http2_prior_knowledge() 28 | .http2_keep_alive_interval(Duration::from_secs(5)) 29 | .http2_keep_alive_timeout(Duration::from_secs(5)) 30 | .build() 31 | .unwrap() 32 | }); 33 | // Avoid concurrent queries 34 | static QUERY_LOCK: Lazy> = Lazy::new(|| Mutex::new(())); 35 | 36 | pub struct DoHResolver; 37 | 38 | impl Resolve for DoHResolver { 39 | fn resolve(&self, name: Name) -> Resolving { 40 | let url = format!("https://1.1.1.1/dns-query?name={}&type=A", name); 41 | Box::pin(async move { 42 | let lock = QUERY_LOCK.lock().await; 43 | 44 | let mut ret = vec![]; 45 | if let Some(mut addrs) = DNS_CACHE.get(&name) { 46 | ret.append(&mut addrs); 47 | } else { 48 | let resp = DNS_HTTP_CLIENT.get(&url).send().await?; 49 | let resp = resp.json::().await?; 50 | 51 | if let Some(ans) = resp.answer { 52 | for record in ans { 53 | if record.typ == 1 { 54 | // A record 55 | let addr = SocketAddr::new(record.data.parse().unwrap(), 443); 56 | DNS_CACHE.insert(name.clone(), addr, record.ttl); 57 | ret.push(addr); 58 | } 59 | } 60 | } 61 | log::debug!("DoH resolved: {}: {:?}", name, ret); 62 | } 63 | 64 | drop(lock); 65 | let addrs: Addrs = Box::new(ret.into_iter()); 66 | Ok(addrs) 67 | }) 68 | } 69 | } 70 | 71 | #[derive(Debug)] 72 | pub struct Entry { 73 | addr: SocketAddr, 74 | expiration: Option, 75 | } 76 | 77 | #[derive(Debug, Default)] 78 | pub struct DNSCache { 79 | cache: RwLock>>, 80 | } 81 | 82 | unsafe impl Send for DNSCache {} 83 | unsafe impl Sync for DNSCache {} 84 | 85 | impl DNSCache { 86 | pub fn new() -> Self { 87 | Self { 88 | cache: Default::default(), 89 | } 90 | } 91 | 92 | // if ttl is expired, remove it from cache 93 | pub fn get(&self, name: &Name) -> Option> { 94 | let cache = self.cache.read().unwrap(); 95 | let now = Instant::now(); 96 | let mut addrs = HashSet::new(); 97 | if let Some(entries) = cache.get(name) { 98 | for e in entries { 99 | if let Some(expiration) = e.expiration { 100 | if expiration >= now { 101 | addrs.insert(e.addr); 102 | } 103 | if addrs.len() > 5 { 104 | // enough 105 | break; 106 | } 107 | } 108 | } 109 | if entries.is_empty() { 110 | return None; 111 | } 112 | } 113 | if addrs.is_empty() { 114 | None 115 | } else { 116 | Some(addrs.into_iter().collect()) 117 | } 118 | } 119 | 120 | pub fn insert(&self, name: Name, addr: SocketAddr, ttl: Option) { 121 | let now = Instant::now(); 122 | let expiration = 123 | ttl.map(|ttl| now + Duration::from_secs(ttl.into()) + Duration::from_secs(300)); 124 | let entry = Entry { addr, expiration }; 125 | 126 | let mut cache = self.cache.write().unwrap(); 127 | let entries = cache.entry(name).or_default(); 128 | entries.retain(|e| e.expiration.is_none() || e.expiration > Some(now) || e.addr != addr); 129 | entries.push(entry); 130 | } 131 | } 132 | 133 | #[derive(Deserialize, Debug)] 134 | pub struct DnsResponse { 135 | #[serde(rename = "Status")] 136 | pub status: u8, 137 | #[serde(rename = "TC")] 138 | pub truncated: bool, 139 | 140 | // "Always true for Google Public DNS" 141 | #[serde(rename = "RD")] 142 | pub recursion_desired: bool, 143 | #[serde(rename = "RA")] 144 | pub recursion_available: bool, 145 | 146 | #[serde(rename = "AD")] 147 | pub dnssec_validated: bool, 148 | #[serde(rename = "CD")] 149 | pub dnssec_disabled: bool, 150 | 151 | #[serde(rename = "Question")] 152 | pub question: Vec, 153 | 154 | #[serde(rename = "Answer")] 155 | pub answer: Option>, 156 | 157 | #[serde(rename = "Comment")] 158 | pub comment: Option, 159 | } 160 | 161 | #[derive(Deserialize, Debug)] 162 | pub struct DnsQuestion { 163 | pub name: String, 164 | #[serde(rename = "type")] 165 | pub typ: u16, 166 | } 167 | 168 | #[derive(Deserialize, Debug)] 169 | pub struct DnsAnswer { 170 | pub name: String, 171 | #[serde(rename = "type")] 172 | pub typ: u16, 173 | #[serde(rename = "TTL")] 174 | pub ttl: Option, 175 | pub data: String, 176 | } 177 | -------------------------------------------------------------------------------- /.github/workflows/CI.yml: -------------------------------------------------------------------------------- 1 | name: Build rsapi 2 | env: 3 | DEBUG: 'napi:*' 4 | MACOSX_DEPLOYMENT_TARGET: '10.13' 5 | NODE_OPTIONS: '--max-old-space-size=3072' 6 | CARGO_UNSTABLE_TARGET_APPLIES_TO_HOST: true 7 | CARGO_TARGET_APPLIES_TO_HOST: false 8 | 9 | on: 10 | push: 11 | branches: 12 | - master 13 | # tags-ignore: 14 | # - '**' 15 | # paths: 16 | # - 'packages/rsapi' 17 | # - 'sync' 18 | pull_request: 19 | # paths: 20 | # - 'packages/rsapi' 21 | # - 'sync' 22 | 23 | jobs: 24 | build-freebsd: 25 | runs-on: ubuntu-latest 26 | if: "startsWith(github.event.head_commit.message, 'chore(release): publish')" 27 | name: Build FreeBSD 28 | steps: 29 | - uses: actions/checkout@v3 30 | - name: Build 31 | id: build 32 | uses: cross-platform-actions/action@v0.26.0 33 | env: 34 | DEBUG: 'napi:*' 35 | RUSTUP_HOME: /home/runner/rustup 36 | CARGO_HOME: /home/runner/cargo 37 | RUSTUP_IO_THREADS: 1 38 | with: 39 | operating_system: freebsd 40 | version: '14.2' 41 | memory: 13G 42 | cpu_count: 3 43 | hypervisor: qemu 44 | environment_variables: 'DEBUG RUSTUP_IO_THREADS' 45 | shell: bash 46 | run: | 47 | env | sort 48 | sudo pkg install -y -f curl node libnghttp2 npm 49 | sudo npm install -g yarn --ignore-scripts 50 | curl https://sh.rustup.rs -sSf --output rustup.sh 51 | sh rustup.sh -y --default-toolchain nightly-2024-12-09 52 | source "$HOME/.cargo/env" 53 | echo "~~~~ rustc --version ~~~~" 54 | rustc --version 55 | echo "~~~~ node -v ~~~~" 56 | node -v 57 | echo "~~~~ yarn --version ~~~~" 58 | yarn --version 59 | pwd 60 | ls -lah 61 | whoami 62 | env 63 | freebsd-version 64 | yarn install --immutable --mode=skip-build 65 | yarn build 66 | strip -x packages/*/*.node 67 | rm -rf node_modules 68 | rm -rf target 69 | rm -rf .yarn/cache 70 | - name: Upload artifact 71 | uses: actions/upload-artifact@v4 72 | with: 73 | name: bindings-freebsd-amd64 74 | path: packages/*/*.node 75 | if-no-files-found: error 76 | build: 77 | if: "!contains(github.event.head_commit.message, 'skip ci')" 78 | strategy: 79 | fail-fast: false 80 | matrix: 81 | settings: 82 | - host: macos-latest 83 | architecture: x64 84 | target: 'x86_64-apple-darwin' 85 | build: | 86 | yarn build --target x86_64-apple-darwin 87 | strip -x packages/*/*.node 88 | - host: windows-latest 89 | architecture: x64 90 | build: yarn build 91 | target: 'x86_64-pc-windows-msvc' 92 | 93 | # Blocked by https://github.com/briansmith/ring/pull/1554 94 | #- host: windows-latest 95 | # architecture: x64 96 | # build: | 97 | # yarn lerna exec "yarn build --target aarch64-pc-windows-msvc" --concurrency 1 --stream --no-prefix 98 | # target: 'aarch64-pc-windows-msvc' 99 | 100 | - host: ubuntu-latest 101 | architecture: x64 102 | target: 'x86_64-unknown-linux-gnu' 103 | build: >- 104 | set -e && 105 | cargo install cargo-zigbuild && 106 | cargo zigbuild -p rsapi --target x86_64-unknown-linux-gnu.2.17 --release && 107 | cp -v target/x86_64-unknown-linux-gnu/release/librsapi.so ./packages/rsapi/rsapi.linux-x64-gnu.node && 108 | strip -x packages/*/*.node 109 | - host: macos-latest 110 | architecture: x64 111 | target: 'aarch64-apple-darwin' 112 | build: | 113 | sudo rm -Rf /Library/Developer/CommandLineTools/SDKs/*; 114 | export CC=$(xcrun -f clang); 115 | export CXX=$(xcrun -f clang++); 116 | SYSROOT=$(xcrun --sdk macosx --show-sdk-path); 117 | export CFLAGS="-isysroot $SYSROOT -isystem $SYSROOT"; 118 | yarn build --target aarch64-apple-darwin 119 | strip -x packages/*/*.node 120 | - host: ubuntu-22.04 121 | architecture: x64 122 | target: 'aarch64-unknown-linux-gnu' 123 | setup: | 124 | sudo apt-get update 125 | sudo apt-get install g++-aarch64-linux-gnu gcc-aarch64-linux-gnu -y 126 | build: | 127 | rustup toolchain install $(cat ./rust-toolchain) 128 | rustup target add aarch64-unknown-linux-gnu 129 | yarn lerna exec "yarn build --target aarch64-unknown-linux-gnu" --concurrency 1 --stream --no-prefix 130 | aarch64-linux-gnu-strip packages/*/*.node 131 | 132 | name: stable - ${{ matrix.settings.target }} - node@20 133 | runs-on: ${{ matrix.settings.host }} 134 | 135 | steps: 136 | - uses: actions/checkout@v3 137 | 138 | - name: Setup node 139 | uses: actions/setup-node@v3 140 | if: ${{ !matrix.settings.docker }} 141 | with: 142 | node-version: 20 143 | check-latest: true 144 | cache: yarn 145 | architecture: ${{ matrix.settings.architecture }} 146 | 147 | - name: Install 148 | uses: actions-rs/toolchain@v1 149 | if: ${{ !matrix.settings.docker }} 150 | with: 151 | toolchain: nightly-2024-12-09 152 | profile: minimal 153 | override: true 154 | target: ${{ matrix.settings.target }} 155 | 156 | - name: Install Zig 157 | uses: goto-bus-stop/setup-zig@v2 158 | 159 | - name: Generate Cargo.lock 160 | uses: actions-rs/cargo@v1 161 | if: ${{ !matrix.settings.docker }} 162 | with: 163 | command: generate-lockfile 164 | 165 | - name: Cache cargo registry 166 | uses: actions/cache@v3 167 | with: 168 | path: ~/.cargo/registry 169 | key: ${{ matrix.settings.target }}-node@20-cargo-registry-trimmed-${{ hashFiles('**/Cargo.lock') }} 170 | 171 | - name: Cache cargo index 172 | uses: actions/cache@v3 173 | with: 174 | path: ~/.cargo/git 175 | key: ${{ matrix.settings.target }}-node@20-cargo-index-trimmed-${{ hashFiles('**/Cargo.lock') }} 176 | 177 | - name: Cache NPM dependencies 178 | uses: actions/cache@v3 179 | with: 180 | path: node_modules 181 | key: npm-cache-${{ matrix.settings.target }}-node@20-${{ hashFiles('yarn.lock') }} 182 | 183 | - name: Setup toolchain 184 | run: ${{ matrix.settings.setup }} 185 | if: ${{ matrix.settings.setup }} 186 | shell: bash 187 | 188 | - name: 'Install dependencies' 189 | run: yarn install --immutable --mode=skip-build 190 | 191 | - name: Build in docker 192 | uses: addnab/docker-run-action@v3 193 | if: ${{ matrix.settings.docker }} 194 | with: 195 | image: ${{ matrix.settings.docker }} 196 | options: -v ${{ env.HOME }}/.cargo/git:/root/.cargo/git -v ${{ env.HOME }}/.cargo/registry:/root/.cargo/registry -v ${{ github.workspace }}:/build -w /build 197 | run: ${{ matrix.settings.build }} 198 | 199 | - name: 'Or Build without docker' 200 | run: ${{ matrix.settings.build }} 201 | if: ${{ !matrix.settings.docker }} 202 | shell: bash 203 | 204 | - name: Upload artifact 205 | uses: actions/upload-artifact@v4 206 | with: 207 | name: bindings-${{ matrix.settings.target }} 208 | path: packages/*/*.node 209 | if-no-files-found: error 210 | 211 | publish: 212 | name: Publish 213 | if: "startsWith(github.event.head_commit.message, 'chore(release): publish')" 214 | runs-on: ubuntu-latest 215 | needs: 216 | - build 217 | - build-freebsd 218 | steps: 219 | - uses: actions/checkout@v3 220 | 221 | - name: Setup node 222 | uses: actions/setup-node@v3 223 | with: 224 | node-version: 20 225 | check-latest: true 226 | cache: yarn 227 | 228 | - name: Cache NPM dependencies 229 | uses: actions/cache@v3 230 | with: 231 | path: node_modules 232 | key: npm-cache-ubuntu-latest-publish-${{ hashFiles('yarn.lock') }} 233 | 234 | - name: Install dependencies 235 | run: yarn install --immutable --mode=skip-build 236 | 237 | - name: Download all artifacts 238 | uses: actions/download-artifact@v4 239 | with: 240 | path: artifacts 241 | 242 | - name: List artifacts 243 | run: ls -R artifacts 244 | shell: bash 245 | 246 | # BUGGY 247 | #- name: Move artifacts 248 | # run: yarn artifacts 249 | 250 | - name: Move artifacts manually 251 | run: | 252 | mv artifacts/bindings-x86_64-unknown-linux-gnu/rsapi/rsapi.linux-x64-gnu.node packages/rsapi/npm/linux-x64-gnu/ 253 | mv artifacts/bindings-x86_64-pc-windows-msvc/rsapi/rsapi.win32-x64-msvc.node packages/rsapi/npm/win32-x64-msvc/ 254 | mv artifacts/bindings-x86_64-apple-darwin/rsapi/rsapi.darwin-x64.node packages/rsapi/npm/darwin-x64/ 255 | mv artifacts/bindings-aarch64-apple-darwin/rsapi/rsapi.darwin-arm64.node packages/rsapi/npm/darwin-arm64/ 256 | mv artifacts/bindings-aarch64-unknown-linux-gnu/rsapi/rsapi.linux-arm64-gnu.node packages/rsapi/npm/linux-arm64-gnu/ 257 | mv artifacts/bindings-freebsd-amd64/rsapi/rsapi.freebsd-x64.node packages/rsapi/npm/freebsd-x64/ 258 | 259 | - name: List packages 260 | run: ls -R packages 261 | shell: bash 262 | 263 | - name: Lerna publish 264 | if: "startsWith(github.event.head_commit.message, 'chore(release): publish')" 265 | run: | 266 | echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc 267 | cd packages/rsapi && npm publish --access public 268 | env: 269 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 270 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 271 | -------------------------------------------------------------------------------- /packages/rsapi/index.js: -------------------------------------------------------------------------------- 1 | // prettier-ignore 2 | /* eslint-disable */ 3 | /* auto-generated by NAPI-RS */ 4 | 5 | const { existsSync, readFileSync } = require('fs') 6 | const { join } = require('path') 7 | 8 | const { platform, arch } = process 9 | 10 | let nativeBinding = null 11 | let localFileExisted = false 12 | let loadError = null 13 | 14 | const isMusl = () => { 15 | let musl = false 16 | if (process.platform === 'linux') { 17 | musl = isMuslFromFilesystem() 18 | if (musl === null) { 19 | musl = isMuslFromReport() 20 | } 21 | if (musl === null) { 22 | musl = isMuslFromChildProcess() 23 | } 24 | } 25 | return musl 26 | } 27 | 28 | const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') 29 | 30 | const isMuslFromFilesystem = () => { 31 | try { 32 | return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') 33 | } catch { 34 | return null 35 | } 36 | } 37 | 38 | const isMuslFromReport = () => { 39 | const report = typeof process.report.getReport === 'function' ? process.report.getReport() : null 40 | if (!report) { 41 | return null 42 | } 43 | if (report.header && report.header.glibcVersionRuntime) { 44 | return false 45 | } 46 | if (Array.isArray(report.sharedObjects)) { 47 | if (report.sharedObjects.some(isFileMusl)) { 48 | return true 49 | } 50 | } 51 | return false 52 | } 53 | 54 | const isMuslFromChildProcess = () => { 55 | try { 56 | return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') 57 | } catch (e) { 58 | // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false 59 | return false 60 | } 61 | } 62 | 63 | switch (platform) { 64 | case 'android': 65 | switch (arch) { 66 | case 'arm64': 67 | localFileExisted = existsSync(join(__dirname, 'rsapi.android-arm64.node')) 68 | try { 69 | if (localFileExisted) { 70 | nativeBinding = require('./rsapi.android-arm64.node') 71 | } else { 72 | nativeBinding = require('@logseq/rsapi-android-arm64') 73 | } 74 | } catch (e) { 75 | loadError = e 76 | } 77 | break 78 | case 'arm': 79 | localFileExisted = existsSync(join(__dirname, 'rsapi.android-arm-eabi.node')) 80 | try { 81 | if (localFileExisted) { 82 | nativeBinding = require('./rsapi.android-arm-eabi.node') 83 | } else { 84 | nativeBinding = require('@logseq/rsapi-android-arm-eabi') 85 | } 86 | } catch (e) { 87 | loadError = e 88 | } 89 | break 90 | default: 91 | throw new Error(`Unsupported architecture on Android ${arch}`) 92 | } 93 | break 94 | case 'win32': 95 | switch (arch) { 96 | case 'x64': 97 | localFileExisted = existsSync( 98 | join(__dirname, 'rsapi.win32-x64-msvc.node') 99 | ) 100 | try { 101 | if (localFileExisted) { 102 | nativeBinding = require('./rsapi.win32-x64-msvc.node') 103 | } else { 104 | nativeBinding = require('@logseq/rsapi-win32-x64-msvc') 105 | } 106 | } catch (e) { 107 | loadError = e 108 | } 109 | break 110 | case 'ia32': 111 | localFileExisted = existsSync( 112 | join(__dirname, 'rsapi.win32-ia32-msvc.node') 113 | ) 114 | try { 115 | if (localFileExisted) { 116 | nativeBinding = require('./rsapi.win32-ia32-msvc.node') 117 | } else { 118 | nativeBinding = require('@logseq/rsapi-win32-ia32-msvc') 119 | } 120 | } catch (e) { 121 | loadError = e 122 | } 123 | break 124 | case 'arm64': 125 | localFileExisted = existsSync( 126 | join(__dirname, 'rsapi.win32-arm64-msvc.node') 127 | ) 128 | try { 129 | if (localFileExisted) { 130 | nativeBinding = require('./rsapi.win32-arm64-msvc.node') 131 | } else { 132 | nativeBinding = require('@logseq/rsapi-win32-arm64-msvc') 133 | } 134 | } catch (e) { 135 | loadError = e 136 | } 137 | break 138 | default: 139 | throw new Error(`Unsupported architecture on Windows: ${arch}`) 140 | } 141 | break 142 | case 'darwin': 143 | localFileExisted = existsSync(join(__dirname, 'rsapi.darwin-universal.node')) 144 | try { 145 | if (localFileExisted) { 146 | nativeBinding = require('./rsapi.darwin-universal.node') 147 | } else { 148 | nativeBinding = require('@logseq/rsapi-darwin-universal') 149 | } 150 | break 151 | } catch {} 152 | switch (arch) { 153 | case 'x64': 154 | localFileExisted = existsSync(join(__dirname, 'rsapi.darwin-x64.node')) 155 | try { 156 | if (localFileExisted) { 157 | nativeBinding = require('./rsapi.darwin-x64.node') 158 | } else { 159 | nativeBinding = require('@logseq/rsapi-darwin-x64') 160 | } 161 | } catch (e) { 162 | loadError = e 163 | } 164 | break 165 | case 'arm64': 166 | localFileExisted = existsSync( 167 | join(__dirname, 'rsapi.darwin-arm64.node') 168 | ) 169 | try { 170 | if (localFileExisted) { 171 | nativeBinding = require('./rsapi.darwin-arm64.node') 172 | } else { 173 | nativeBinding = require('@logseq/rsapi-darwin-arm64') 174 | } 175 | } catch (e) { 176 | loadError = e 177 | } 178 | break 179 | default: 180 | throw new Error(`Unsupported architecture on macOS: ${arch}`) 181 | } 182 | break 183 | case 'freebsd': 184 | if (arch !== 'x64') { 185 | throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) 186 | } 187 | localFileExisted = existsSync(join(__dirname, 'rsapi.freebsd-x64.node')) 188 | try { 189 | if (localFileExisted) { 190 | nativeBinding = require('./rsapi.freebsd-x64.node') 191 | } else { 192 | nativeBinding = require('@logseq/rsapi-freebsd-x64') 193 | } 194 | } catch (e) { 195 | loadError = e 196 | } 197 | break 198 | case 'linux': 199 | switch (arch) { 200 | case 'x64': 201 | if (isMusl()) { 202 | localFileExisted = existsSync( 203 | join(__dirname, 'rsapi.linux-x64-musl.node') 204 | ) 205 | try { 206 | if (localFileExisted) { 207 | nativeBinding = require('./rsapi.linux-x64-musl.node') 208 | } else { 209 | nativeBinding = require('@logseq/rsapi-linux-x64-musl') 210 | } 211 | } catch (e) { 212 | loadError = e 213 | } 214 | } else { 215 | localFileExisted = existsSync( 216 | join(__dirname, 'rsapi.linux-x64-gnu.node') 217 | ) 218 | try { 219 | if (localFileExisted) { 220 | nativeBinding = require('./rsapi.linux-x64-gnu.node') 221 | } else { 222 | nativeBinding = require('@logseq/rsapi-linux-x64-gnu') 223 | } 224 | } catch (e) { 225 | loadError = e 226 | } 227 | } 228 | break 229 | case 'arm64': 230 | if (isMusl()) { 231 | localFileExisted = existsSync( 232 | join(__dirname, 'rsapi.linux-arm64-musl.node') 233 | ) 234 | try { 235 | if (localFileExisted) { 236 | nativeBinding = require('./rsapi.linux-arm64-musl.node') 237 | } else { 238 | nativeBinding = require('@logseq/rsapi-linux-arm64-musl') 239 | } 240 | } catch (e) { 241 | loadError = e 242 | } 243 | } else { 244 | localFileExisted = existsSync( 245 | join(__dirname, 'rsapi.linux-arm64-gnu.node') 246 | ) 247 | try { 248 | if (localFileExisted) { 249 | nativeBinding = require('./rsapi.linux-arm64-gnu.node') 250 | } else { 251 | nativeBinding = require('@logseq/rsapi-linux-arm64-gnu') 252 | } 253 | } catch (e) { 254 | loadError = e 255 | } 256 | } 257 | break 258 | case 'arm': 259 | localFileExisted = existsSync( 260 | join(__dirname, 'rsapi.linux-arm-gnueabihf.node') 261 | ) 262 | try { 263 | if (localFileExisted) { 264 | nativeBinding = require('./rsapi.linux-arm-gnueabihf.node') 265 | } else { 266 | nativeBinding = require('@logseq/rsapi-linux-arm-gnueabihf') 267 | } 268 | } catch (e) { 269 | loadError = e 270 | } 271 | break 272 | case 'riscv64': 273 | if (isMusl()) { 274 | localFileExisted = existsSync( 275 | join(__dirname, 'rsapi.linux-riscv64-musl.node') 276 | ) 277 | try { 278 | if (localFileExisted) { 279 | nativeBinding = require('./rsapi.linux-riscv64-musl.node') 280 | } else { 281 | nativeBinding = require('@logseq/rsapi-linux-riscv64-musl') 282 | } 283 | } catch (e) { 284 | loadError = e 285 | } 286 | } else { 287 | localFileExisted = existsSync( 288 | join(__dirname, 'rsapi.linux-riscv64-gnu.node') 289 | ) 290 | try { 291 | if (localFileExisted) { 292 | nativeBinding = require('./rsapi.linux-riscv64-gnu.node') 293 | } else { 294 | nativeBinding = require('@logseq/rsapi-linux-riscv64-gnu') 295 | } 296 | } catch (e) { 297 | loadError = e 298 | } 299 | } 300 | break 301 | default: 302 | throw new Error(`Unsupported architecture on Linux: ${arch}`) 303 | } 304 | break 305 | default: 306 | throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) 307 | } 308 | 309 | if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { 310 | try { 311 | nativeBinding = require('./rsapi.wasi.cjs') 312 | } catch { 313 | // ignore 314 | } 315 | if (!nativeBinding) { 316 | try { 317 | nativeBinding = require('@logseq/rsapi-wasm32-wasi') 318 | } catch (err) { 319 | console.error(err) 320 | } 321 | } 322 | } 323 | 324 | if (!nativeBinding) { 325 | if (loadError) { 326 | throw loadError 327 | } 328 | throw new Error(`Failed to load native binding`) 329 | } 330 | 331 | module.exports.ageDecryptWithPassphrase = nativeBinding.ageDecryptWithPassphrase 332 | module.exports.ageEncryptWithPassphrase = nativeBinding.ageEncryptWithPassphrase 333 | module.exports.cancelAllRequests = nativeBinding.cancelAllRequests 334 | module.exports.canonicalizePath = nativeBinding.canonicalizePath 335 | module.exports.decryptFnames = nativeBinding.decryptFnames 336 | module.exports.deleteLocalFiles = nativeBinding.deleteLocalFiles 337 | module.exports.deleteRemoteFiles = nativeBinding.deleteRemoteFiles 338 | module.exports.encryptFnames = nativeBinding.encryptFnames 339 | module.exports.fetchRemoteFiles = nativeBinding.fetchRemoteFiles 340 | module.exports.getLocalAllFilesMeta = nativeBinding.getLocalAllFilesMeta 341 | module.exports.getLocalFilesMeta = nativeBinding.getLocalFilesMeta 342 | module.exports.initLogger = nativeBinding.initLogger 343 | module.exports.keygen = nativeBinding.keygen 344 | module.exports.renameLocalFile = nativeBinding.renameLocalFile 345 | module.exports.setEnv = nativeBinding.setEnv 346 | module.exports.setProgressCallback = nativeBinding.setProgressCallback 347 | module.exports.setProxy = nativeBinding.setProxy 348 | module.exports.updateLocalFiles = nativeBinding.updateLocalFiles 349 | module.exports.updateLocalVersionFiles = nativeBinding.updateLocalVersionFiles 350 | module.exports.updateRemoteFiles = nativeBinding.updateRemoteFiles 351 | -------------------------------------------------------------------------------- /packages/rsapi/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(clippy::all)] 2 | #![feature(result_flattening)] 3 | #![feature(async_closure)] 4 | 5 | use std::time::Instant; 6 | use std::{collections::HashMap, path::PathBuf}; 7 | 8 | use napi::bindgen_prelude::*; 9 | use napi::threadsafe_function::{ 10 | ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode, 11 | }; 12 | use napi::Result; 13 | use napi_derive::napi; 14 | 15 | use rsapi_impl as implementation; 16 | pub use rsapi_impl::{graph::Metadata, FileMeta, Progress}; 17 | 18 | use crate::age_task::{DecryptTask, EncryptInput, EncryptTask}; 19 | 20 | pub mod age_task; 21 | 22 | type ProgressCallbackFunction = ThreadsafeFunction; 23 | static mut PROGRESS_CALLBACK: Option = None; 24 | 25 | static LOGGER: NodeJsLogger = NodeJsLogger; 26 | static mut LOGGING_CALLBACK: Option< 27 | ThreadsafeFunction<(String, String), ErrorStrategy::CalleeHandled>, 28 | > = None; 29 | 30 | pub struct NodeJsLogger; 31 | 32 | impl log::Log for NodeJsLogger { 33 | fn enabled(&self, metadata: &log::Metadata) -> bool { 34 | (metadata.target().starts_with("rsapi") || metadata.target().starts_with("sync")) 35 | && metadata.level() <= log::Level::Debug 36 | } 37 | 38 | fn log(&self, record: &log::Record) { 39 | if self.enabled(record.metadata()) { 40 | if let Some(callback) = unsafe { LOGGING_CALLBACK.as_ref() } { 41 | callback.call( 42 | Ok((record.level().to_string(), format!("{}", record.args()))), 43 | ThreadsafeFunctionCallMode::NonBlocking, 44 | ); 45 | } else { 46 | eprintln!("W: logger callback not set!"); 47 | } 48 | } 49 | } 50 | 51 | fn flush(&self) {} 52 | } 53 | 54 | /// Set rsapi Logger 55 | #[napi] 56 | pub fn init_logger(js_logging_fn: JsFunction) -> Result<()> { 57 | if unsafe { LOGGING_CALLBACK.is_some() } { 58 | return Ok(()); 59 | } 60 | 61 | eprintln!("(rsapi) init loggers"); 62 | let logging_fn: ThreadsafeFunction<(String, String), ErrorStrategy::CalleeHandled> = 63 | js_logging_fn.create_threadsafe_function( 64 | 1000, 65 | |ctx: ThreadSafeCallContext<(String, String)>| { 66 | Ok(vec![ctx.env.to_js_value(&ctx.value)?.into_unknown()]) 67 | }, 68 | )?; 69 | 70 | unsafe { 71 | LOGGING_CALLBACK = Some(logging_fn); 72 | } 73 | let _ = log::set_logger(&LOGGER); 74 | log::set_max_level(log::LevelFilter::Debug); 75 | 76 | Ok(()) 77 | } 78 | 79 | /// Age encryption key generation 80 | #[napi] 81 | pub async fn keygen() -> Result> { 82 | let (secret_key, pub_key) = implementation::keygen(); 83 | 84 | let mut map = HashMap::new(); 85 | map.insert("publicKey".into(), pub_key); 86 | map.insert("secretKey".into(), secret_key); 87 | Ok(map) 88 | } 89 | 90 | /// Set dev environment along with encryption key 91 | #[napi] 92 | pub async fn set_env( 93 | graph_uuid: String, 94 | env: String, 95 | secret_key: String, 96 | public_key: String, 97 | ) -> Result<()> { 98 | implementation::set_env(&graph_uuid, &env, &secret_key, &public_key)?; 99 | Ok(()) 100 | } 101 | 102 | #[napi] 103 | pub async fn set_proxy(proxy: Option) -> Result<()> { 104 | implementation::set_proxy(proxy.as_ref().map(|x| &**x))?; 105 | Ok(()) 106 | } 107 | 108 | #[napi] 109 | pub fn set_progress_callback(callback: JsFunction) -> Result<()> { 110 | // ThreadsafeFunction 111 | // queue = 1000, control maximum number of notification in queue 112 | let progress_fn: ProgressCallbackFunction = 113 | callback.create_threadsafe_function(1000, |ctx: ThreadSafeCallContext| { 114 | Ok(vec![ctx.env.to_js_value(&ctx.value)?.into_unknown()]) 115 | })?; 116 | 117 | unsafe { 118 | PROGRESS_CALLBACK = Some(progress_fn); 119 | } 120 | 121 | fn progress_callback(info: Progress) { 122 | if let Some(callback) = unsafe { PROGRESS_CALLBACK.as_ref() } { 123 | callback.call(Ok(info), ThreadsafeFunctionCallMode::NonBlocking); 124 | } else { 125 | log::warn!("progress callback not set!"); 126 | } 127 | } 128 | 129 | implementation::set_progress_callback(progress_callback); 130 | 131 | Ok(()) 132 | } 133 | 134 | #[napi] 135 | pub async fn cancel_all_requests() -> Result<()> { 136 | implementation::cancel_all_requests()?; 137 | Ok(()) 138 | } 139 | 140 | /// get local files' metadata: file-size, md5 141 | /// (get-local-files-meta [this graph-uuid base-path filepaths] "get local files' metadata") 142 | #[napi] 143 | pub async fn get_local_files_meta( 144 | graph_uuid: String, 145 | base_path: String, 146 | file_paths: Vec, 147 | ) -> Result> { 148 | log::trace!("get local files metadata {:?}", file_paths); 149 | let graph = implementation::get_graph(&graph_uuid)?; 150 | Ok(graph.get_files_meta(base_path, file_paths).await?) 151 | } 152 | 153 | /// (get-local-all-files-meta [this graph-uuid base-path] "get all local files' metadata") 154 | #[napi] 155 | pub async fn get_local_all_files_meta( 156 | graph_uuid: String, 157 | base_path: String, 158 | ) -> Result> { 159 | let start_time = Instant::now(); 160 | 161 | let graph = implementation::get_graph(&graph_uuid)?; 162 | let files_meta: HashMap = graph 163 | .get_all_files_meta(&base_path) 164 | .await? 165 | .into_iter() 166 | .map(|meta| (meta.fname.clone(), meta)) 167 | .collect(); 168 | 169 | let elapsed = start_time.elapsed(); 170 | log::info!( 171 | "get file meta of {:?}: {} files in {}ms", 172 | base_path, 173 | files_meta.len(), 174 | elapsed.as_millis() 175 | ); 176 | 177 | Ok(files_meta) 178 | } 179 | 180 | /// (rename-local-file [this graph-uuid base-path from to access-token]) 181 | #[napi] 182 | pub async fn rename_local_file( 183 | graph_uuid: String, 184 | base_path: String, 185 | from: String, 186 | to: String, 187 | ) -> Result<()> { 188 | log::info!("rename local file: {:?} => {:?}", from, to); 189 | 190 | let graph = implementation::get_graph(&graph_uuid)?; 191 | graph.rename_local_file(&base_path, &from, &to).await?; 192 | 193 | Ok(()) 194 | } 195 | 196 | /// (delete-local-file [this graph-uuid base-path filepath access-token]) 197 | /// NOTE: token is not used 198 | #[napi] 199 | pub async fn delete_local_files( 200 | graph_uuid: String, 201 | base_path: String, 202 | file_paths: Vec, 203 | ) -> Result<()> { 204 | log::info!("delete local files: {:?}", file_paths); 205 | 206 | let graph = implementation::get_graph(&graph_uuid)?; 207 | graph.delete_local_files(base_path, file_paths).await?; 208 | 209 | Ok(()) 210 | } 211 | 212 | #[napi] 213 | pub async fn fetch_remote_files( 214 | graph_uuid: String, 215 | base_path: String, 216 | file_paths: Vec, 217 | token: String, 218 | ) -> Result> { 219 | log::info!("fetch remote files: {:?}", file_paths); 220 | 221 | let graph = implementation::get_graph(&graph_uuid)?; 222 | match graph 223 | .fetch_remote_files(base_path, file_paths, &token) 224 | .await 225 | { 226 | Ok(val) => Ok(val), 227 | Err(e) => { 228 | log::error!("fetch remote files error: {:?}", e); 229 | return Err(e.into()); 230 | } 231 | } 232 | } 233 | 234 | /// remote -> local 235 | /// (update-local-file [this graph-uuid base-path filepath access-token] "remote -> local") 236 | #[napi] 237 | pub async fn update_local_files( 238 | graph_uuid: String, 239 | base_path: String, 240 | file_paths: Vec, 241 | token: String, 242 | ) -> Result<()> { 243 | log::info!("update local files: {:?}", file_paths); 244 | 245 | let graph = implementation::get_graph(&graph_uuid)?; 246 | if let Err(e) = graph 247 | .update_local_files(base_path, file_paths, &token) 248 | .await 249 | { 250 | log::error!("update local files error: {:?}", e); 251 | return Err(e.into()); 252 | } 253 | 254 | Ok(()) 255 | } 256 | 257 | // Version files are saved in S3 with uuid as file names. 258 | #[napi] 259 | pub async fn update_local_version_files( 260 | graph_uuid: String, 261 | base_path: String, 262 | file_paths: Vec, 263 | token: String, 264 | ) -> Result<()> { 265 | log::debug!("download version files: {:?}", file_paths); 266 | 267 | let graph = implementation::get_graph(&graph_uuid)?; 268 | graph 269 | .update_local_version_files(base_path, file_paths, &token) 270 | .await?; 271 | 272 | Ok(()) 273 | } 274 | 275 | #[napi] 276 | pub async fn update_remote_files( 277 | graph_uuid: String, 278 | base_path: String, 279 | file_paths: Vec, 280 | txid: i64, 281 | token: String, 282 | _metadata: Option, 283 | ) -> Result { 284 | log::info!("update remote files[txid={}]: {:?}", txid, file_paths); 285 | 286 | let graph = implementation::get_graph(&graph_uuid)?; 287 | let mut retries = 0; 288 | loop { 289 | match graph 290 | .update_remote_files(&base_path, &file_paths, txid, &token, None) 291 | .await 292 | { 293 | Ok(txid) => { 294 | log::debug!("update remote files success, txid={}", txid); 295 | return Ok(txid); 296 | } 297 | Err(e) => { 298 | if e.to_string().contains("ExpiredToken") { 299 | log::warn!("token expired, retry"); 300 | } 301 | if retries >= 2 { 302 | log::error!("update remote files: {}", e); 303 | return Err(e.into()); 304 | } 305 | log::warn!("update remote files(retry={}): {}", retries, e); 306 | retries += 1; 307 | } 308 | } 309 | } 310 | } 311 | 312 | /// (delete-remote-file [this graph-uuid base-path filepath local-txid access-token]))#[napi] 313 | #[napi] 314 | pub async fn delete_remote_files( 315 | graph_uuid: String, 316 | base_path: String, 317 | file_paths: Vec, 318 | txid: i64, 319 | token: String, 320 | ) -> Result { 321 | log::info!("delete remote files[txid={}]: {:?}", txid, file_paths); 322 | 323 | let graph = implementation::get_graph(&graph_uuid)?; 324 | let txid = graph 325 | .delete_remote_files(base_path, file_paths, txid, &token) 326 | .await?; 327 | 328 | Ok(txid) 329 | } 330 | 331 | /// Encryption API 332 | 333 | #[napi] 334 | pub fn age_encrypt_with_passphrase( 335 | passphrase: String, 336 | data: Uint8Array, 337 | signal: Option, 338 | ) -> Result> { 339 | let task = EncryptTask::new(passphrase, EncryptInput::Bytes(data.to_vec())); 340 | Ok(AsyncTask::with_optional_signal(task, signal)) 341 | } 342 | 343 | #[napi] 344 | pub fn age_decrypt_with_passphrase( 345 | passphrase: String, 346 | data: Uint8Array, 347 | signal: Option, 348 | ) -> Result> { 349 | let task = DecryptTask::new(passphrase, EncryptInput::Bytes(data.to_vec())); 350 | Ok(AsyncTask::with_optional_signal(task, signal)) 351 | } 352 | 353 | #[napi] 354 | pub fn encrypt_fnames(graph_uuid: String, fnames: Vec) -> Result> { 355 | use rayon::prelude::*; 356 | 357 | let graph = implementation::get_graph(&graph_uuid)?; 358 | fnames 359 | .par_iter() 360 | .map(|p| Ok(graph.encrypt_filename(p)?)) 361 | .collect() 362 | } 363 | 364 | #[napi] 365 | pub fn decrypt_fnames(graph_uuid: String, fnames: Vec) -> Result> { 366 | use rayon::prelude::*; 367 | 368 | let graph = implementation::get_graph(&graph_uuid)?; 369 | fnames 370 | .par_iter() 371 | .map(|p| Ok(graph.decrypt_filename(p)?)) 372 | .collect() 373 | } 374 | 375 | /// Helper 376 | #[napi] 377 | pub async fn canonicalize_path(file_path: String) -> Result { 378 | let new_path = std::fs::canonicalize(PathBuf::from(file_path))?; 379 | let strip_windows_prefix = dunce::canonicalize(new_path)?; 380 | Ok(strip_windows_prefix.to_str().unwrap().to_string()) 381 | } 382 | -------------------------------------------------------------------------------- /sync/src/sync.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::collections::HashMap; 3 | // use std::sync::Arc; 4 | use std::time::Duration; 5 | 6 | use serde_json::json; 7 | 8 | use crate::error::SyncError; 9 | use crate::helpers::ProgressedBytesStream; 10 | use crate::types::{self, Credentials, TempCredential}; 11 | use crate::Result; 12 | 13 | static mut TEMP_CREDENTIAL: Option = None; 14 | 15 | static mut HTTPS_PROXY: Option = None; 16 | 17 | // API URL base 18 | static mut URL_BASE: &str = "https://api-dev.logseq.com/file-sync/"; 19 | static mut BUCKET: &str = "logseq-file-sync-bucket"; 20 | static mut REGION: &str = "us-east-2"; 21 | 22 | const URL_BASE_DEV: &str = "https://api-dev.logseq.com/file-sync/"; 23 | const BUCKET_DEV: &str = "logseq-file-sync-bucket"; 24 | const REGION_DEV: &str = "us-east-2"; 25 | 26 | const URL_BASE_PROD: &str = "https://api.logseq.com/file-sync/"; 27 | const BUCKET_PROD: &str = "logseq-file-sync-bucket-prod"; 28 | const REGION_PROD: &str = "us-east-1"; 29 | 30 | fn url_base() -> &'static str { 31 | unsafe { URL_BASE } 32 | } 33 | 34 | fn bucket() -> &'static str { 35 | unsafe { BUCKET } 36 | } 37 | 38 | fn region() -> &'static str { 39 | unsafe { REGION } 40 | } 41 | 42 | /// set environment to prod 43 | pub fn set_prod() { 44 | unsafe { 45 | URL_BASE = URL_BASE_PROD; 46 | BUCKET = BUCKET_PROD; 47 | REGION = REGION_PROD; 48 | } 49 | } 50 | 51 | pub fn set_dev() { 52 | unsafe { 53 | URL_BASE = URL_BASE_DEV; 54 | BUCKET = BUCKET_DEV; 55 | REGION = REGION_DEV; 56 | } 57 | } 58 | 59 | pub fn set_proxy(proxy: Option<&str>) -> Result<()> { 60 | unsafe { 61 | if let Some(proxy) = proxy { 62 | // Check proxy 63 | let _ = reqwest::Proxy::https(proxy)?; 64 | HTTPS_PROXY = Some(proxy.to_string()); 65 | } else { 66 | HTTPS_PROXY = None; 67 | } 68 | } 69 | Ok(()) 70 | } 71 | 72 | pub fn reset_user() { 73 | unsafe { 74 | TEMP_CREDENTIAL = None; 75 | } 76 | } 77 | 78 | pub struct SyncClient { 79 | client: reqwest::Client, 80 | txid: i64, 81 | graph_uuid: String, 82 | credentials: Option, 83 | s3_prefix: Option, 84 | auth_token: String, 85 | } 86 | unsafe impl Sync for SyncClient {} 87 | unsafe impl Send for SyncClient {} 88 | 89 | impl SyncClient { 90 | pub fn new(token: &str) -> SyncClient { 91 | let accept_invalid_certs = true; 92 | // env::var("NODE_TLS_REJECT_UNAUTHORIZED").unwrap_or_default() == "0"; 93 | let client = { 94 | let mut builder = reqwest::Client::builder() 95 | .user_agent("Logseq-sync/0.3") 96 | .connection_verbose(false) 97 | // .dns_resolver(Arc::new(crate::doh::DoHResolver)) 98 | .timeout(Duration::from_secs(30)) 99 | .connect_timeout(Duration::from_secs(15)) 100 | .http2_keep_alive_interval(Duration::from_secs(10)) 101 | .http2_keep_alive_timeout(Duration::from_secs(60)) 102 | .http2_keep_alive_while_idle(true); 103 | if let Some(proxy) = unsafe { HTTPS_PROXY.as_ref() } { 104 | builder = builder.proxy(reqwest::Proxy::https(proxy).unwrap()); 105 | } 106 | if accept_invalid_certs { 107 | // log::info!("NODE_TLS_REJECT_UNAUTHORIZED=0, won't validate certs"); 108 | builder = builder.danger_accept_invalid_certs(true); 109 | } 110 | builder.build().unwrap() 111 | }; 112 | 113 | SyncClient { 114 | client, 115 | txid: -1, // uninited 116 | credentials: None, 117 | graph_uuid: String::new(), 118 | s3_prefix: None, 119 | auth_token: token.to_string(), 120 | } 121 | } 122 | 123 | /// for stateless access 124 | pub fn set_graph(&mut self, uuid: &str, txid: i64) { 125 | self.graph_uuid = uuid.to_string(); 126 | self.txid = txid; 127 | } 128 | 129 | // ========== 130 | // API helpers 131 | // ========== 132 | 133 | // update temp credentials if needed 134 | pub async fn refresh_temp_credential(&mut self) -> Result<()> { 135 | unsafe { 136 | if self.credentials.is_none() && TEMP_CREDENTIAL.is_some() { 137 | let temp_credential = TEMP_CREDENTIAL.clone().unwrap(); 138 | self.credentials = Some(temp_credential.credentials); 139 | self.s3_prefix = Some(temp_credential.s3_prefix); 140 | } 141 | } 142 | if self 143 | .credentials 144 | .as_ref() 145 | .map(|c| c.is_expired()) 146 | .unwrap_or(true) 147 | { 148 | let temp_credential = self.get_temp_credential().await?; 149 | 150 | unsafe { 151 | TEMP_CREDENTIAL = Some(temp_credential.clone()); 152 | } 153 | 154 | log::debug!( 155 | "credential refreshed, next expiration at {}", 156 | temp_credential.credentials.expiration 157 | ); 158 | self.credentials = Some(temp_credential.credentials); 159 | self.s3_prefix = Some(temp_credential.s3_prefix); 160 | } 161 | Ok(()) 162 | } 163 | 164 | // ========== 165 | // APIs 166 | // ========== 167 | 168 | // create a new graph 169 | // NOTE: actually the return type is SimpleGraph, 170 | // but the default values is reasonable, so we use Graph instead 171 | pub async fn create_graph(&self, name: &str) -> Result { 172 | let payload = json!({ "GraphName": name }); 173 | let resp = self 174 | .client 175 | .post(url_base().to_owned() + "create_graph") 176 | .body(payload.to_string()) 177 | .bearer_auth(&self.auth_token) 178 | .header("Content-Type", "application/octet-stream") 179 | .send() 180 | .await?; 181 | let graph: types::Graph = resp.json().await?; 182 | match graph.message { 183 | None => Ok(graph), 184 | Some(text) => SyncError::from_message(text), 185 | } 186 | } 187 | 188 | // get the graph 189 | // FIXME: get a non-existing graph will return an empty string! 190 | pub async fn get_graph(&self, name: &str) -> Result { 191 | let payload = json!({ "GraphName": name }); 192 | let resp = self 193 | .client 194 | .post(url_base().to_owned() + "get_graph") 195 | .body(payload.to_string()) 196 | .bearer_auth(&self.auth_token) 197 | .header("Content-Type", "application/octet-stream") 198 | .send() 199 | .await? 200 | .error_for_status()?; 201 | 202 | let graph: types::Graph = resp.json().await?; 203 | match graph.message { 204 | None => Ok(graph), 205 | Some(text) => SyncError::from_message(text), 206 | } 207 | } 208 | 209 | pub async fn get_graph_by_uuid(&self, uuid: &str) -> Result { 210 | let payload = json!({ "GraphUUID": uuid }); 211 | let resp = self 212 | .client 213 | .post(url_base().to_owned() + "get_graph") 214 | .body(payload.to_string()) 215 | .bearer_auth(&self.auth_token) 216 | .header("Content-Type", "application/octet-stream") 217 | .send() 218 | .await? 219 | .error_for_status()?; 220 | 221 | let graph: types::Graph = resp.json().await?; 222 | match graph.message { 223 | None => Ok(graph), 224 | Some(text) => SyncError::from_message(text), 225 | } 226 | } 227 | 228 | pub async fn list_graphs(&self) -> Result> { 229 | let resp = self 230 | .client 231 | .post(url_base().to_owned() + "list_graphs") 232 | .bearer_auth(&self.auth_token) 233 | .header("Content-Type", "application/octet-stream") 234 | .send() 235 | .await?; 236 | 237 | let result: types::TypicalResponse = resp.json().await?; 238 | match result.message { 239 | None => Ok(serde_json::from_value(result.data["Graphs"].clone())?), 240 | Some(text) => SyncError::from_message(text), 241 | } 242 | } 243 | 244 | // get all files metadata: size, etag, key(filepath), last-modified 245 | pub async fn get_all_files(&self) -> Result> { 246 | let payload = json!({ "GraphUUID": self.graph_uuid }); 247 | let resp = self 248 | .client 249 | .post(url_base().to_owned() + "get_all_files") 250 | .body(payload.to_string()) 251 | .bearer_auth(&self.auth_token) 252 | .header("Content-Type", "application/octet-stream") 253 | .send() 254 | .await?; 255 | 256 | let result: types::TypicalResponse = resp.json().await?; 257 | match result.message { 258 | None => { 259 | let files: Vec = 260 | serde_json::from_value(result.data["Objects"].clone())?; 261 | Ok(files) 262 | } 263 | Some(text) => SyncError::from_message(text), 264 | } 265 | } 266 | 267 | // files' s3 get-object presigned-url 268 | pub async fn get_files, I: IntoIterator>( 269 | &self, 270 | files: I, 271 | ) -> Result> { 272 | let payload = json!({ 273 | "GraphUUID": self.graph_uuid, 274 | "Files": files.into_iter().map(|f| f.as_ref().to_owned()).collect::>(), 275 | }); 276 | let resp = self 277 | .client 278 | .post(url_base().to_owned() + "get_files") 279 | .body(payload.to_string()) 280 | .bearer_auth(&self.auth_token) 281 | .header("Content-Type", "application/octet-stream") 282 | .send() 283 | .await?; 284 | 285 | let result: serde_json::Value = resp.json().await?; 286 | let files: HashMap = 287 | serde_json::from_value(result["PresignedFileUrls"].clone())?; 288 | Ok(files) 289 | } 290 | 291 | pub async fn get_version_files, I: IntoIterator>( 292 | &self, 293 | files: I, 294 | ) -> Result> { 295 | let payload = json!({ 296 | "GraphUUID": self.graph_uuid, 297 | "Files": files.into_iter().map(|f| f.as_ref().to_owned()).collect::>(), 298 | }); 299 | let resp = self 300 | .client 301 | .post(url_base().to_owned() + "get_version_files") 302 | .body(payload.to_string()) 303 | .bearer_auth(&self.auth_token) 304 | .header("Content-Type", "application/octet-stream") 305 | .send() 306 | .await?; 307 | let result: serde_json::Value = resp.json().await?; 308 | let files: HashMap = 309 | serde_json::from_value(result["PresignedFileUrls"].clone())?; 310 | Ok(files) 311 | } 312 | 313 | // expire after 1h 314 | pub async fn get_temp_credential(&self) -> Result { 315 | let resp = self 316 | .client 317 | .post(url_base().to_owned() + "get_temp_credential") 318 | .body("") 319 | .bearer_auth(&self.auth_token) 320 | .header("Content-Type", "application/octet-stream") 321 | .send() 322 | .await? 323 | .error_for_status()?; 324 | 325 | let mut credential: TempCredential = resp.json().await?; 326 | // FIXME: prefix is path style 327 | credential.s3_prefix = credential 328 | .s3_prefix 329 | .strip_prefix(bucket()) 330 | .unwrap() 331 | .trim_start_matches('/') 332 | .to_owned() 333 | + "/"; 334 | Ok(credential) 335 | } 336 | 337 | // TODO: Use temp file to hold download content 338 | pub async fn download_file(&self, url: &str, progress_callback: F) -> Result> 339 | where 340 | F: Fn(usize, usize) + Send + Sync + 'static, 341 | { 342 | // FIXME: HEAD requires different signature in presigned URL. 343 | // Use simulated HEAD request to get file size. 344 | let head_resp = self 345 | .client 346 | .get(url) 347 | .header("Content-Range", "bytes=0-0") 348 | .send() 349 | .await? 350 | .error_for_status()?; 351 | let content_length = head_resp.content_length().unwrap_or_default() as usize; 352 | 353 | let timeout = if content_length == 0 { 354 | // FIXME: unreachable, s3 file should always have a non-zero content-length 355 | Duration::from_secs(100) 356 | } else { 357 | let tt = (content_length / 20 / 1024) as u64; 358 | Duration::from_secs(u64::max(tt, 50)) 359 | }; 360 | 361 | let mut resp = self 362 | .client 363 | .get(url) 364 | .timeout(timeout) 365 | .send() 366 | .await? 367 | .error_for_status()?; 368 | 369 | let mut buf = Vec::with_capacity(1024 * 4); 370 | 371 | let mut nbytes = 0; 372 | while let Some(chunk) = resp.chunk().await? { 373 | nbytes += chunk.len(); 374 | buf.extend(chunk); 375 | progress_callback(nbytes, content_length); 376 | } 377 | if content_length != 0 && content_length != nbytes { 378 | return Err(SyncError::Custom("Incomplete download".to_owned())); 379 | } 380 | Ok(buf) 381 | } 382 | 383 | // upload with Credentials, return remote temp path 384 | // AccessKeyId, SecretKey, SessionToken 385 | pub async fn upload_tempfile( 386 | &self, 387 | content: Cow<'_, [u8]>, 388 | progress_callback: F, 389 | ) -> Result 390 | where 391 | F: Fn(usize, usize) + Send + Sync + 'static, 392 | { 393 | use s3_presign::Bucket; 394 | use s3_presign::Credentials; 395 | 396 | let credentials = self.credentials.as_ref().unwrap(); 397 | 398 | let credentials = Credentials::new( 399 | credentials.access_key_id.clone(), 400 | credentials.secret_key.clone(), 401 | Some(credentials.session_token.clone()), 402 | ); 403 | let bucket = Bucket::new(region(), bucket()); 404 | 405 | let key = self.s3_prefix.clone().unwrap() + &*random_string(12); 406 | // 1 hour expiration 407 | let presign_url = s3_presign::put(&credentials, &bucket, &key, 60 * 60) 408 | .ok_or(SyncError::Custom("can not generate presign url".to_owned()))?; 409 | 410 | let content = content.to_owned().to_vec(); 411 | let content_size = content.len(); 412 | 413 | // allow 20k/s upload speed 414 | let timeout = usize::max(content_size / 20 / 1024, 30); 415 | 416 | let stream = ProgressedBytesStream::new(content, progress_callback); 417 | 418 | let resp = self 419 | .client 420 | .put(presign_url) 421 | .body(reqwest::Body::wrap_stream(stream)) 422 | .header("content-length", content_size) 423 | .header("content-type", "application/octet-stream") 424 | .timeout(Duration::from_secs(timeout as _)) 425 | .send() 426 | .await?; 427 | 428 | let code = resp.status().as_u16(); 429 | if code != 200 { 430 | let body = resp.bytes().await?; 431 | let content = String::from_utf8_lossy(&body); 432 | if content.contains("ExpiredToken") || content.contains("Request has expired") { 433 | return Err(SyncError::ExpiredToken); 434 | } else { 435 | return Err(SyncError::Custom(format!( 436 | "Can not upload temp file, code={}: {}", 437 | code, content 438 | ))); 439 | } 440 | } 441 | 442 | Ok(key) 443 | } 444 | 445 | // key: pages/page1.md 446 | // value: [s3-prefix]/xxxxxxxxxxx.md 447 | // key: pages/Hello%20World.md 448 | // value: [s3-prefix]/xxxxxxxxxxx 449 | // (key, value, checksum) => (page/page1.md, s3-prefix/xxxxxxxxxxx.md, md5-checksum) 450 | pub async fn update_files(&self, files: I) -> Result 451 | where 452 | PK: AsRef, 453 | PV: AsRef, 454 | PH: AsRef, 455 | I: IntoIterator, 456 | { 457 | let files: HashMap = files 458 | .into_iter() 459 | .map(|(k, v, checksum)| { 460 | ( 461 | k.as_ref().to_string(), 462 | (v.as_ref().to_string(), checksum.as_ref().to_string()), 463 | ) 464 | }) 465 | .collect::>(); 466 | let payload = json!({ 467 | "GraphUUID": self.graph_uuid, 468 | "TXId": self.txid, 469 | "Files": files 470 | }); 471 | let resp = self 472 | .client 473 | .post(url_base().to_owned() + "update_files") 474 | .body(payload.to_string()) 475 | .bearer_auth(&self.auth_token) 476 | .header("Content-Type", "application/octet-stream") 477 | .send() 478 | .await?; 479 | 480 | let result: types::UpdateFiles = resp.json().await?; 481 | match result.message { 482 | None => { 483 | // FIXME: not updated due to self mutablity 484 | // self.txid = result.txid; 485 | Ok(result) 486 | } 487 | Some(message) => Err(SyncError::Custom(message)), 488 | } 489 | } 490 | 491 | pub async fn delete_files, I: IntoIterator>( 492 | &mut self, 493 | files: I, 494 | ) -> Result { 495 | let payload = json!({ 496 | "GraphUUID": self.graph_uuid, 497 | "TXId": self.txid, 498 | "Files": files.into_iter().map(|s| s.as_ref().to_owned()).collect::>(), 499 | }); 500 | 501 | let resp = self 502 | .client 503 | .post(url_base().to_owned() + "delete_files") 504 | .body(payload.to_string()) 505 | .bearer_auth(&self.auth_token) 506 | .header("Content-Type", "application/octet-stream") 507 | .send() 508 | .await?; 509 | 510 | let result: types::DeleteFiles = resp.json().await?; 511 | match result.message { 512 | None => { 513 | self.txid += result.txid; 514 | Ok(result) 515 | } 516 | Some(message) => Err(SyncError::Custom(message)), 517 | } 518 | } 519 | 520 | // FIXME: the API returns redundant paths, since graph_uuid is known, 521 | // The prefix is useless. 522 | pub async fn get_diff(&self, txid0: u64) -> Result> { 523 | let payload = json!({ 524 | "GraphUUID": self.graph_uuid, 525 | "FromTXId": txid0, 526 | }); 527 | 528 | let resp = self 529 | .client 530 | .post(url_base().to_owned() + "get_diff") 531 | .body(payload.to_string()) 532 | .bearer_auth(&self.auth_token) 533 | .header("Content-Type", "application/octet-stream") 534 | .send() 535 | .await?; 536 | 537 | let result: types::TypicalResponse = resp.json().await?; 538 | match result.message { 539 | None => { 540 | let txns: Vec = 541 | serde_json::from_value(result.data["Transactions"].clone())?; 542 | Ok(txns) 543 | } 544 | Some(message) => Err(SyncError::Custom(message)), 545 | } 546 | } 547 | 548 | // non-ex: 500 549 | pub async fn rename_file, P2: AsRef>( 550 | &mut self, 551 | from: P1, 552 | to: P2, 553 | ) -> Result<()> { 554 | let payload = json!({ 555 | "GraphUUID": self.graph_uuid, 556 | "TXId": self.txid, 557 | "SrcFile": from.as_ref(), 558 | "DstFile": to.as_ref(), 559 | }); 560 | 561 | let resp = self 562 | .client 563 | .post(url_base().to_owned() + "rename_file") 564 | .body(payload.to_string()) 565 | .bearer_auth(&self.auth_token) 566 | .header("Content-Type", "application/octet-stream") 567 | .send() 568 | .await? 569 | .error_for_status()?; 570 | 571 | let result: types::TypicalResponse = resp.json().await?; 572 | match result.message { 573 | None => { 574 | self.txid += result.txid; 575 | Ok(()) 576 | } 577 | Some(message) => Err(SyncError::Custom(message)), 578 | } 579 | } 580 | } 581 | 582 | fn random_string(len: usize) -> String { 583 | use rand::Rng; 584 | let mut rng = rand::thread_rng(); 585 | let chars: Vec = (0..len) 586 | .map(|_| { 587 | let c: u8 = rng.gen_range(b'a'..=b'z'); 588 | c as char 589 | }) 590 | .collect(); 591 | chars.iter().collect::() 592 | } 593 | -------------------------------------------------------------------------------- /rsapi-jni/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(read_buf)] 2 | #![feature(result_flattening)] 3 | #![allow(non_snake_case)] 4 | 5 | use std::path::PathBuf; 6 | 7 | use jni::objects::{JClass, JObject, JString, JValue}; 8 | use jni::sys::{jbyteArray, jint, jlong, jobjectArray, jstring, JNI_VERSION_1_6}; 9 | use jni::{JNIEnv, JavaVM}; 10 | 11 | use rsapi_impl as implementation; 12 | pub use rsapi_impl::{FileMeta, Progress}; 13 | 14 | use crate::error::Error; 15 | 16 | pub mod error; 17 | 18 | pub type Result = ::std::result::Result; 19 | 20 | /// Used for error handling 21 | static mut LAST_ERROR: Option = None; 22 | 23 | static mut VM: Option = Option::None; 24 | 25 | static mut RUNNER: Option = Option::None; 26 | 27 | fn runtime() -> &'static tokio::runtime::Runtime { 28 | unsafe { 29 | RUNNER 30 | .as_ref() 31 | .expect("tokio runner is inited in JNI_OnLoad") 32 | } 33 | } 34 | 35 | pub struct AndroidLogger; 36 | 37 | impl log::Log for AndroidLogger { 38 | fn enabled(&self, metadata: &log::Metadata) -> bool { 39 | (metadata.target().starts_with("rsapi") || metadata.target().starts_with("sync")) 40 | && metadata.level() <= log::Level::Debug 41 | } 42 | 43 | fn log(&self, record: &log::Record) { 44 | #[cfg(target_os = "android")] 45 | if self.enabled(record.metadata()) { 46 | use android_log_sys::{LogPriority, __android_log_print}; 47 | 48 | let priority = match record.level() { 49 | log::Level::Error => LogPriority::ERROR, 50 | log::Level::Warn => LogPriority::WARN, 51 | log::Level::Info => LogPriority::INFO, 52 | log::Level::Debug => LogPriority::DEBUG, 53 | log::Level::Trace => LogPriority::VERBOSE, 54 | }; 55 | // NOTE: Android logcat doesn't support %, so we replace it with _ 56 | let message = format!("{}\0", record.args()).replace("%", "_"); 57 | let tag = b"rsapi-jni\0"; 58 | unsafe { 59 | __android_log_print( 60 | priority as _, 61 | tag.as_ptr() as *const _, 62 | message.as_ptr() as *const _, 63 | ); 64 | } 65 | } 66 | } 67 | 68 | fn flush(&self) {} 69 | } 70 | 71 | #[no_mangle] 72 | pub extern "system" fn JNI_OnLoad(vm: JavaVM, _reserved: *mut ()) -> jint { 73 | unsafe { 74 | VM = Some(vm); 75 | } 76 | 77 | log::set_logger(&AndroidLogger).expect("JNI_OnLoad is called at most once"); 78 | log::set_max_level(log::LevelFilter::Debug); 79 | 80 | log::debug!("rsapi JNI_OnLoad called"); 81 | 82 | std::panic::set_hook(Box::new(|panic_info| { 83 | let msg = panic_info.payload().downcast_ref::<&str>().unwrap(); 84 | debug_log(format!("PANIC: {}", msg)); 85 | debug_log(panic_info.to_string()); 86 | })); 87 | 88 | // tokio runner 89 | let rt = tokio::runtime::Builder::new_multi_thread() 90 | .worker_threads(4) 91 | .enable_all() 92 | .build() 93 | .expect("tokio runtime"); 94 | unsafe { 95 | RUNNER = Some(rt); 96 | } 97 | 98 | // Ref: https://developer.android.com/training/articles/perf-jni#faq_FindClass 99 | let env: JNIEnv = unsafe { VM.as_ref().unwrap().get_env().unwrap() }; 100 | let inst = { 101 | env.call_static_method( 102 | "com/logseq/app/filesync/FileSyncPlugin", 103 | "getInstance", 104 | "()Lcom/logseq/app/filesync/FileSyncPlugin;", 105 | &[], 106 | ) 107 | .unwrap() 108 | .l() 109 | .unwrap() 110 | }; 111 | let inst = env.new_global_ref(inst).unwrap(); 112 | 113 | let (tx, rx) = std::sync::mpsc::channel::(); 114 | std::thread::spawn(move || { 115 | let env = unsafe { VM.as_ref().unwrap() } 116 | .attach_current_thread() 117 | .expect("VM cannot attach to current thread"); 118 | 119 | while let Ok(info) = rx.recv() { 120 | let _ret = env 121 | .call_method( 122 | &inst, 123 | "progressNotify", 124 | "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJ)V", 125 | &[ 126 | JValue::Object(env.new_string(&info.graph_uuid).unwrap().into()), 127 | JValue::Object(env.new_string(&info.file).unwrap().into()), 128 | JValue::Object(env.new_string(&info.r#type).unwrap().into()), 129 | JValue::Long(info.progress), 130 | JValue::Long(info.total), 131 | ], 132 | ) 133 | .expect("progressNotify"); 134 | } 135 | }); 136 | 137 | let progress_callback = move |info: Progress| { 138 | tx.send(info).unwrap(); 139 | }; 140 | 141 | implementation::set_progress_callback(progress_callback); 142 | 143 | JNI_VERSION_1_6 144 | } 145 | 146 | // MARK: Export JNI functions 147 | #[no_mangle] 148 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_getLastError( 149 | env: JNIEnv, 150 | _class: JClass, 151 | ) -> jstring { 152 | unsafe { 153 | if let Some(err) = &LAST_ERROR { 154 | let ret = env.new_string(err.to_string()).unwrap().into_raw(); 155 | LAST_ERROR = None; 156 | ret 157 | } else { 158 | JObject::null().into_raw() 159 | } 160 | } 161 | } 162 | 163 | // Public rsapi API Part 164 | #[no_mangle] 165 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_cancelAllRequests( 166 | _env: JNIEnv, 167 | _class: JClass, 168 | ) -> jlong { 169 | debug_log("cancel all requests"); 170 | match implementation::cancel_all_requests() { 171 | Ok(()) => 0, 172 | Err(err) => { 173 | unsafe { 174 | LAST_ERROR = Some(err.into()); 175 | } 176 | -1 177 | } 178 | } 179 | } 180 | 181 | /// String[secret, public], won't fail 182 | #[no_mangle] 183 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_keygen( 184 | env: JNIEnv, 185 | _class: JClass, 186 | ) -> jobjectArray { 187 | let array = env 188 | .new_object_array(2, "java/lang/String", JObject::null()) 189 | .unwrap(); 190 | 191 | let (secret, public) = implementation::keygen(); 192 | 193 | let _ = env.set_object_array_element(array, 0, env.new_string(secret).unwrap()); 194 | let _ = env.set_object_array_element(array, 1, env.new_string(public).unwrap()); 195 | 196 | return array; 197 | } 198 | 199 | #[no_mangle] 200 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_setEnvironment( 201 | env: JNIEnv, 202 | _class: JClass, 203 | graph_uuid: JString, 204 | variant: JString, 205 | secret_key: JString, 206 | public_key: JString, 207 | ) -> jlong { 208 | let variant = env.get_string(variant).map(String::from).expect("env"); 209 | let graph_uuid = env 210 | .get_string(graph_uuid) 211 | .map(String::from) 212 | .expect("graph_uuid"); 213 | debug_log(format!("setting env: {} {:?}", graph_uuid, variant)); 214 | let secret_key = env 215 | .get_string(secret_key) 216 | .map(String::from) 217 | .expect("secret key must set"); 218 | let public_key = env 219 | .get_string(public_key) 220 | .map(String::from) 221 | .expect("public key must set"); 222 | 223 | match implementation::set_env(&graph_uuid, &variant, &secret_key, &public_key) { 224 | Ok(()) => 0, 225 | Err(err) => { 226 | unsafe { 227 | LAST_ERROR = Some(err.into()); 228 | } 229 | -1 230 | } 231 | } 232 | } 233 | 234 | /// Return null when error 235 | #[no_mangle] 236 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_encryptFilenames( 237 | env: JNIEnv, 238 | _class: JClass, 239 | graph_uuid: JString, 240 | fnames: JObject, // List 241 | ) -> jobjectArray { 242 | fn inner( 243 | env: JNIEnv, 244 | graph_uuid: JString, 245 | fnames: JObject, // List 246 | ) -> Result { 247 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 248 | let fnames = jlist_to_string_vec(env, fnames)?; 249 | 250 | let graph = implementation::get_graph(&graph_uuid)?; 251 | let array = 252 | env.new_object_array(fnames.len() as i32, "java/lang/String", JObject::null())?; 253 | for (i, fname) in fnames.iter().enumerate() { 254 | let encrypted = graph.encrypt_filename(fname)?; 255 | env.set_object_array_element(array, i as i32, env.new_string(encrypted)?)?; 256 | } 257 | 258 | Ok(array) 259 | } 260 | 261 | match inner(env, graph_uuid, fnames) { 262 | Ok(array) => array, 263 | Err(err) => { 264 | unsafe { 265 | LAST_ERROR = Some(err.into()); 266 | } 267 | JObject::null().into_raw() 268 | } 269 | } 270 | } 271 | 272 | /// Return null when error 273 | #[no_mangle] 274 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_decryptFilenames( 275 | env: JNIEnv, 276 | _class: JClass, 277 | graph_uuid: JString, 278 | encrypted_fnames: JObject, // List 279 | ) -> jobjectArray { 280 | fn inner( 281 | env: JNIEnv, 282 | graph_uuid: JString, 283 | fnames: JObject, // List 284 | ) -> Result { 285 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 286 | let fnames = jlist_to_string_vec(env, fnames)?; 287 | 288 | let graph = implementation::get_graph(&graph_uuid)?; 289 | let array = 290 | env.new_object_array(fnames.len() as i32, "java/lang/String", JObject::null())?; 291 | for (i, fname) in fnames.iter().enumerate() { 292 | let encrypted = graph.decrypt_filename(fname)?; 293 | env.set_object_array_element(array, i as i32, env.new_string(encrypted)?)?; 294 | } 295 | 296 | Ok(array) 297 | } 298 | 299 | match inner(env, graph_uuid, encrypted_fnames) { 300 | Ok(array) => array, 301 | Err(err) => { 302 | unsafe { 303 | LAST_ERROR = Some(err.into()); 304 | } 305 | JObject::null().into_raw() 306 | } 307 | } 308 | } 309 | 310 | #[no_mangle] 311 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_getLocalFilesMeta( 312 | env: JNIEnv, 313 | _class: JClass, 314 | graph_uuid: JString, 315 | base_path: JString, 316 | file_paths: JObject, // List 317 | ) -> jobjectArray { 318 | fn inner( 319 | env: JNIEnv, 320 | graph_uuid: JString, 321 | base_path: JString, 322 | file_paths: JObject, 323 | ) -> Result { 324 | let base_path = uri_to_full_path(env, base_path)?; 325 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 326 | let mut file_paths = jlist_to_string_vec(env, file_paths)?; 327 | 328 | file_paths.sort(); 329 | file_paths.dedup(); 330 | // NOTE: Assume Android is using a case-sensitive fs. 331 | 332 | let graph = implementation::get_graph(&graph_uuid)?; 333 | let files_meta = runtime().block_on(graph.get_files_meta(base_path, file_paths))?; 334 | let nfiles = files_meta.len(); 335 | let array = 336 | env.new_object_array(nfiles as i32, "com/logseq/sync/FileMeta", JObject::null())?; 337 | // TODO: use real filename key 338 | for (i, (_file_name, file_meta)) in files_meta.iter().enumerate() { 339 | env.set_object_array_element(array, i as i32, to_java_file_meta(env, file_meta)?)?; 340 | } 341 | 342 | Ok(array) 343 | } 344 | 345 | match inner(env, graph_uuid, base_path, file_paths) { 346 | Ok(array) => array, 347 | Err(err) => { 348 | unsafe { 349 | LAST_ERROR = Some(err.into()); 350 | } 351 | JObject::null().into_raw() 352 | } 353 | } 354 | } 355 | 356 | #[no_mangle] 357 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_getLocalAllFilesMeta( 358 | env: JNIEnv, 359 | _class: JClass, 360 | graph_uuid: JString, 361 | base_path: JString, 362 | ) -> jobjectArray { 363 | fn inner(env: JNIEnv, graph_uuid: JString, base_path: JString) -> Result { 364 | let base_path = uri_to_full_path(env, base_path)?; 365 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 366 | 367 | let graph = implementation::get_graph(&graph_uuid)?; 368 | let files_meta = runtime() 369 | .block_on(graph.get_all_files_meta(base_path))? 370 | .collect::>(); 371 | let nfiles = files_meta.len(); 372 | let array = 373 | env.new_object_array(nfiles as i32, "com/logseq/sync/FileMeta", JObject::null())?; 374 | for (i, file_meta) in files_meta.iter().enumerate() { 375 | env.set_object_array_element(array, i as i32, to_java_file_meta(env, file_meta)?)?; 376 | } 377 | 378 | Ok(array) 379 | } 380 | 381 | match inner(env, graph_uuid, base_path) { 382 | Ok(array) => array, 383 | Err(err) => { 384 | unsafe { 385 | LAST_ERROR = Some(err.into()); 386 | } 387 | JObject::null().into_raw() 388 | } 389 | } 390 | } 391 | 392 | #[no_mangle] 393 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_renameLocalFile( 394 | env: JNIEnv, 395 | _class: JClass, 396 | _graph_uuid: JString, 397 | base_path: JString, 398 | old_file_path: JString, 399 | new_file_path: JString, 400 | ) -> jlong { 401 | use std::fs; 402 | 403 | let base_path = uri_to_full_path(env, base_path).unwrap(); 404 | let from: String = env.get_string(old_file_path).unwrap().into(); 405 | let to: String = env.get_string(new_file_path).unwrap().into(); 406 | 407 | match fs::rename(base_path.join(&from), base_path.join(&to)) { 408 | Ok(()) => 0, 409 | Err(err) => { 410 | debug_log(format!("cannot rename: {:?}", err)); 411 | -1 412 | } 413 | } 414 | } 415 | 416 | #[no_mangle] 417 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_deleteLocalFiles( 418 | env: JNIEnv, 419 | _class: JClass, 420 | _graph_uuid: JString, 421 | base_path: JString, 422 | file_paths: JObject, // List 423 | ) { 424 | use std::fs; 425 | 426 | let base_path = uri_to_full_path(env, base_path).unwrap(); 427 | let file_paths = jlist_to_string_vec(env, file_paths).unwrap(); 428 | for file_path in file_paths { 429 | let full_path = base_path.join(file_path); 430 | debug_log(format!("delete file {:?}", full_path)); 431 | let _ = fs::remove_file(full_path); // ignore any errors 432 | } 433 | } 434 | 435 | // returns String[] 436 | #[no_mangle] 437 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_fetchRemoteFiles( 438 | env: JNIEnv, 439 | _class: JClass, 440 | graph_uuid: JString, 441 | base_path: JString, 442 | file_paths: JObject, // List 443 | token: JString, 444 | ) -> jobjectArray { 445 | fn inner( 446 | env: JNIEnv, 447 | graph_uuid: JString, 448 | base_path: JString, 449 | file_paths: JObject, // List 450 | token: JString, 451 | ) -> Result { 452 | let base_path = uri_to_full_path(env, base_path)?; 453 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 454 | let token: String = env.get_string(token)?.into(); 455 | let file_paths = jlist_to_string_vec(env, file_paths)?; 456 | 457 | let graph = implementation::get_graph(&graph_uuid)?; 458 | 459 | let files_to_be_merged = 460 | runtime().block_on(graph.fetch_remote_files(base_path, file_paths, &token))?; 461 | let array = env.new_object_array( 462 | files_to_be_merged.len() as i32, 463 | "java/lang/String", 464 | JObject::null(), 465 | )?; 466 | for (i, fname) in files_to_be_merged.iter().enumerate() { 467 | env.set_object_array_element(array, i as i32, env.new_string(fname)?)?; 468 | } 469 | Ok(array) 470 | } 471 | 472 | match inner(env, graph_uuid, base_path, file_paths, token) { 473 | Ok(array) => array, 474 | Err(err) => { 475 | unsafe { 476 | LAST_ERROR = Some(err.into()); 477 | } 478 | JObject::null().into_raw() 479 | } 480 | } 481 | } 482 | 483 | #[no_mangle] 484 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_updateLocalFiles( 485 | env: JNIEnv, 486 | _class: JClass, 487 | graph_uuid: JString, 488 | base_path: JString, 489 | file_paths: JObject, // List 490 | token: JString, 491 | ) -> jlong { 492 | fn inner( 493 | env: JNIEnv, 494 | graph_uuid: JString, 495 | base_path: JString, 496 | file_paths: JObject, // List 497 | token: JString, 498 | ) -> Result<()> { 499 | let base_path = uri_to_full_path(env, base_path)?; 500 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 501 | let token: String = env.get_string(token)?.into(); 502 | let file_paths = jlist_to_string_vec(env, file_paths)?; 503 | 504 | let graph = implementation::get_graph(&graph_uuid)?; 505 | 506 | runtime().block_on(graph.update_local_files(base_path, file_paths, &token))?; 507 | 508 | Ok(()) 509 | } 510 | 511 | match inner(env, graph_uuid, base_path, file_paths, token) { 512 | Ok(_) => 0, 513 | Err(err) => { 514 | unsafe { 515 | LAST_ERROR = Some(err.into()); 516 | } 517 | -1 518 | } 519 | } 520 | } 521 | 522 | #[no_mangle] 523 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_updateLocalVersionFiles( 524 | env: JNIEnv, 525 | _class: JClass, 526 | graph_uuid: JString, 527 | base_path: JString, 528 | file_paths: JObject, // List 529 | token: JString, 530 | ) -> jlong { 531 | fn inner( 532 | env: JNIEnv, 533 | graph_uuid: JString, 534 | base_path: JString, 535 | file_paths: JObject, 536 | token: JString, 537 | ) -> Result<()> { 538 | let base_path = uri_to_full_path(env, base_path)?; 539 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 540 | let token: String = env.get_string(token)?.into(); 541 | let file_paths = jlist_to_string_vec(env, file_paths)?; 542 | 543 | let graph = implementation::get_graph(&graph_uuid)?; 544 | 545 | runtime().block_on(graph.update_local_version_files(base_path, file_paths, &token))?; 546 | 547 | Ok(()) 548 | } 549 | 550 | match inner(env, graph_uuid, base_path, file_paths, token) { 551 | Ok(_) => 0, 552 | Err(err) => { 553 | unsafe { LAST_ERROR = Some(err) }; 554 | return -1; 555 | } 556 | } 557 | } 558 | 559 | #[no_mangle] 560 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_deleteRemoteFiles( 561 | env: JNIEnv, 562 | _class: JClass, 563 | graph_uuid: JString, 564 | base_path: JString, 565 | file_paths: JObject, // List 566 | token: JString, 567 | txid: jlong, 568 | ) -> jlong { 569 | fn inner( 570 | env: JNIEnv, 571 | graph_uuid: JString, 572 | base_path: JString, 573 | file_paths: JObject, // List 574 | token: JString, 575 | txid: jlong, 576 | ) -> Result { 577 | let base_path = uri_to_full_path(env, base_path)?; 578 | let file_paths = jlist_to_string_vec(env, file_paths)?; 579 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 580 | let token: String = env.get_string(token)?.into(); 581 | 582 | let graph = implementation::get_graph(&graph_uuid)?; 583 | 584 | let txid = 585 | runtime().block_on(graph.delete_remote_files(base_path, file_paths, txid, &token))?; 586 | 587 | Ok(txid) 588 | } 589 | 590 | match inner(env, graph_uuid, base_path, file_paths, token, txid) { 591 | Ok(txid) => txid, 592 | Err(err) => { 593 | unsafe { LAST_ERROR = Some(err) }; 594 | return -1; 595 | } 596 | } 597 | } 598 | 599 | #[no_mangle] 600 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_updateRemoteFiles( 601 | env: JNIEnv, 602 | _class: JClass, 603 | graph_uuid: JString, 604 | base_path: JString, 605 | file_paths: JObject, // List 606 | token: JString, 607 | txid: jlong, 608 | ) -> jlong { 609 | fn inner( 610 | env: JNIEnv, 611 | graph_uuid: JString, 612 | base_path: JString, 613 | file_paths: JObject, // List 614 | token: JString, 615 | txid: jlong, 616 | ) -> Result { 617 | let base_path = uri_to_full_path(env, base_path)?; 618 | let graph_uuid: String = env.get_string(graph_uuid)?.into(); 619 | let token: String = env.get_string(token)?.into(); 620 | let file_paths = jlist_to_string_vec(env, file_paths)?; 621 | 622 | let graph = implementation::get_graph(&graph_uuid)?; 623 | 624 | let txid = runtime() 625 | .block_on(graph.update_remote_files(base_path, file_paths, txid, &token, None))?; 626 | Ok(txid) 627 | } 628 | 629 | match inner(env, graph_uuid, base_path, file_paths, token, txid) { 630 | Ok(txid) => txid, 631 | Err(err) => { 632 | unsafe { LAST_ERROR = Some(err) }; 633 | return -1; 634 | } 635 | } 636 | } 637 | 638 | #[no_mangle] 639 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_ageEncryptWithPassphrase( 640 | env: JNIEnv, 641 | _class: JClass, 642 | passphrase: JString, 643 | buf: jbyteArray, 644 | ) -> jbyteArray { 645 | let pass: String = env.get_string(passphrase).unwrap().into(); 646 | let buf = env.convert_byte_array(buf).unwrap(); 647 | 648 | match lsq_encryption::encrypt_with_user_passphrase(&pass, &buf, true) { 649 | Ok(ret) => env.byte_array_from_slice(&ret).unwrap(), 650 | Err(e) => { 651 | unsafe { LAST_ERROR = Some(e.into()) }; 652 | JObject::null().into_raw() 653 | } 654 | } 655 | } 656 | 657 | #[no_mangle] 658 | pub extern "system" fn Java_com_logseq_sync_RSFileSync_ageDecryptWithPassphrase( 659 | env: JNIEnv, 660 | _class: JClass, 661 | passphrase: JString, 662 | buf: jbyteArray, 663 | ) -> jbyteArray { 664 | let pass: String = env.get_string(passphrase).unwrap().into(); 665 | let buf = env.convert_byte_array(buf).unwrap(); 666 | 667 | match lsq_encryption::decrypt_with_user_passphrase(&pass, &buf) { 668 | Ok(ret) => env.byte_array_from_slice(&ret).unwrap(), 669 | Err(e) => { 670 | unsafe { LAST_ERROR = Some(e.into()) }; 671 | JObject::null().into_raw() 672 | } 673 | } 674 | } 675 | 676 | // MARK: Debug logging 677 | #[cfg(not(target_os = "android"))] 678 | pub fn debug_log>(message: T) { 679 | println!("{}", message.as_ref()); 680 | } 681 | 682 | #[cfg(target_os = "android")] 683 | pub fn debug_log>(message: T) { 684 | use android_log_sys::{LogPriority, __android_log_print}; 685 | use std::ffi::CString; 686 | 687 | match CString::new(message.as_ref()) { 688 | Ok(message) => { 689 | let priority = LogPriority::DEBUG; 690 | let tag = "rsapi-jni\0"; 691 | 692 | unsafe { 693 | __android_log_print(priority as _, tag.as_ptr() as *const _, message.as_ptr()); 694 | } 695 | } 696 | Err(_) => { 697 | panic!("cannot convert log message"); 698 | } 699 | } 700 | } 701 | 702 | // MARK: misc helpers 703 | /// convert java:List to rust:Vec 704 | fn jlist_to_string_vec(env: JNIEnv, list: JObject) -> jni::errors::Result> { 705 | let list = env.get_list(list)?; 706 | 707 | list.iter()? 708 | .map(|pat| env.get_string(pat.into()).map(String::from)) 709 | .collect() 710 | } 711 | 712 | /// convert Uri to path 713 | fn uri_to_full_path<'a>(env: JNIEnv<'a>, path: JString) -> jni::errors::Result { 714 | let uri_class = env.find_class("android/net/Uri").unwrap(); 715 | let uri = env 716 | .call_static_method( 717 | uri_class, 718 | "parse", 719 | "(Ljava/lang/String;)Landroid/net/Uri;", 720 | &[JValue::Object(path.into())], 721 | )? 722 | .l()?; 723 | let path: JString = env 724 | .call_method(uri, "getPath", "()Ljava/lang/String;", &[])? 725 | .l()? 726 | .into(); 727 | let path: String = env.get_string(path)?.into(); 728 | Ok(PathBuf::from(path)) 729 | } 730 | 731 | fn to_java_file_meta<'a>(env: JNIEnv<'a>, metadata: &FileMeta) -> Result> { 732 | // construct com.logseq.sync.FileMeta 733 | let class = env.find_class("com/logseq/sync/FileMeta").unwrap(); 734 | let obj = env.new_object( 735 | class, 736 | "(Ljava/lang/String;JJJLjava/lang/String;)V", 737 | &[ 738 | JValue::Object(env.new_string(&metadata.fname)?.into()), 739 | JValue::Long(metadata.size), 740 | JValue::Long(metadata.mtime), 741 | JValue::Long(metadata.ctime), 742 | JValue::Object(env.new_string(&metadata.md5)?.into()), 743 | ], 744 | )?; 745 | env.set_field( 746 | obj, 747 | "encryptedFilename", 748 | "Ljava/lang/String;", 749 | JValue::Object(env.new_string(&metadata.encrypted_fname).unwrap().into()), 750 | )?; 751 | env.set_field( 752 | obj, 753 | "incomingFilename", 754 | "Ljava/lang/String;", 755 | JValue::Object(env.new_string(&metadata.incoming_fname).unwrap().into()), 756 | )?; 757 | 758 | Ok(obj) 759 | } 760 | -------------------------------------------------------------------------------- /rsapi-impl/src/graph.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | borrow::Cow, 3 | collections::HashMap, 4 | path::Path, 5 | sync::Arc, 6 | time::{Duration, SystemTime}, 7 | }; 8 | 9 | #[cfg(feature = "napi")] 10 | use napi_derive::napi; 11 | use once_cell::sync::Lazy; 12 | use tokio::fs; 13 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; 14 | use tokio::sync::watch; 15 | 16 | use futures::prelude::*; 17 | use lsq_encryption::md5_hexdigest; 18 | use sync::SyncClient; 19 | use unicode_normalization::UnicodeNormalization; 20 | 21 | use crate::error::{Error, Result}; 22 | use crate::{Progress, PROGRESS_CALLBACK}; 23 | 24 | pub static mut CANCELLACTION_TX: Option> = None; 25 | pub static mut CANCELLACTION_RX: Option> = None; 26 | 27 | pub static mut GRAPHS: Lazy = Lazy::new(|| { 28 | let (cancel_tx, cancel_rx) = watch::channel(()); 29 | 30 | unsafe { 31 | CANCELLACTION_TX = Some(cancel_tx); 32 | CANCELLACTION_RX = Some(cancel_rx); 33 | } 34 | GraphCatalog::default() 35 | }); 36 | 37 | // Public API implementation 38 | 39 | #[derive(Default)] 40 | pub struct GraphCatalog(HashMap); 41 | 42 | impl GraphCatalog { 43 | pub fn new() -> Self { 44 | Self::default() 45 | } 46 | 47 | pub fn add_graph(&mut self, graph: Graph) { 48 | self.0.insert(graph.uuid.clone(), graph); 49 | } 50 | 51 | pub fn get_graph(&self, graph_uuid: &str) -> Result<&Graph> { 52 | self.0.get(graph_uuid).ok_or(Error::GraphNotSet) 53 | } 54 | } 55 | 56 | #[derive(Debug)] 57 | pub struct Graph { 58 | pub uuid: String, 59 | // TODO: base_bash should be bonded to the graph 60 | // pub base_path: PathBuf, 61 | pub age_public_key: String, 62 | pub age_secret_key: String, 63 | pub fname_encryption_key: [u8; 32], 64 | } 65 | 66 | pub fn cancel_all_requests() -> Result<()> { 67 | unsafe { CANCELLACTION_TX.as_ref() }.map(|tx| tx.send(())); 68 | log::debug!("cancelling all request"); 69 | Ok(()) 70 | } 71 | 72 | // Set proxy for all sync requests, convert error to impl::Error 73 | pub fn set_proxy(proxy: Option<&str>) -> Result<()> { 74 | if proxy.is_some() { 75 | log::info!("setting proxy: {:?}", proxy); 76 | } 77 | sync::set_proxy(proxy)?; 78 | Ok(()) 79 | } 80 | 81 | pub fn set_env(graph_uuid: &str, env: &str, secret_key: &str, public_key: &str) -> Result<()> { 82 | log::info!("set sync env {:?} for {}", env, graph_uuid); 83 | // clean temp credential cache 84 | sync::reset_user(); 85 | // also cancel any pending requests 86 | unsafe { CANCELLACTION_TX.as_ref() }.map(|tx| tx.send(())); 87 | 88 | match env { 89 | "production" | "product" | "prod" => { 90 | sync::set_prod(); 91 | } 92 | "development" | "develop" | "dev" => { 93 | sync::set_dev(); 94 | } 95 | _ => return Err(Error::InvalidArg), 96 | } 97 | 98 | let g = Graph { 99 | uuid: graph_uuid.into(), 100 | age_public_key: public_key.into(), 101 | age_secret_key: secret_key.into(), 102 | fname_encryption_key: lsq_encryption::to_raw_x25519_key(secret_key)?, 103 | }; 104 | 105 | unsafe { 106 | GRAPHS.add_graph(g); 107 | } 108 | 109 | Ok(()) 110 | } 111 | 112 | impl Graph { 113 | pub fn encrypt_filename(&self, fname: &str) -> Result { 114 | Ok(lsq_encryption::encrypt_filename( 115 | &fname, 116 | &self.fname_encryption_key, 117 | )?) 118 | } 119 | 120 | pub fn decrypt_filename(&self, fname: &str) -> Result { 121 | Ok(lsq_encryption::decrypt_filename( 122 | &fname, 123 | &self.fname_encryption_key, 124 | )?) 125 | } 126 | 127 | pub fn encrypt_content<'a, 'b>(&'a self, data: &'b [u8]) -> Result> { 128 | if data.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----") 129 | || data.starts_with(b"age-encryption.org/v1\n") 130 | { 131 | return Ok(data.into()); 132 | } 133 | 134 | let encrypted = lsq_encryption::encrypt_with_x25519(&self.age_public_key, data, false)?; 135 | Ok(encrypted.to_vec().into()) 136 | } 137 | 138 | pub fn decrypt_content<'a, 'b>(&'a self, data: &'b [u8]) -> Result> { 139 | if data.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----") 140 | || data.starts_with(b"age-encryption.org/v1\n") 141 | { 142 | if let Ok(decrypted) = lsq_encryption::decrypt_with_x25519(&self.age_secret_key, data) { 143 | Ok(decrypted.to_vec().into()) 144 | } else { 145 | Ok(data.into()) 146 | } 147 | } else { 148 | Ok(data.into()) 149 | } 150 | } 151 | 152 | pub async fn get_files_meta, P1: AsRef, PS>( 153 | &self, 154 | base_path: P0, 155 | file_paths: PS, 156 | ) -> Result> 157 | where 158 | PS: IntoIterator, 159 | { 160 | let base_path = dunce::canonicalize(base_path.as_ref())?; 161 | 162 | let futs = file_paths.into_iter().map(|p| { 163 | let path: String = p.as_ref().to_string(); 164 | 165 | let meta = { 166 | let p = path.clone(); 167 | self.get_file_meta(&base_path, p) 168 | }; 169 | meta.map(move |meta| (path, meta)) 170 | }); 171 | 172 | Ok(future::join_all(futs) 173 | .await 174 | .into_iter() 175 | .filter(|(_, m)| m.is_ok()) 176 | .map(|(p, m)| (p, m.unwrap())) 177 | .collect()) 178 | } 179 | 180 | pub async fn get_all_files_meta>( 181 | &self, 182 | base_path: P, 183 | ) -> Result> { 184 | let base_path = dunce::canonicalize(base_path.as_ref())?; 185 | let base_path_ref = base_path.clone(); 186 | 187 | let futs = { 188 | walkdir::WalkDir::new(&base_path) 189 | .into_iter() 190 | .filter_map(|e| e.ok()) 191 | .filter_map(move |e| { 192 | e.path() 193 | .strip_prefix(&base_path) 194 | .ok() 195 | .and_then(|p| p.to_str()) 196 | .map(|p| p.replace("\\", "/").trim_start_matches('/').to_string()) 197 | }) 198 | .filter(|p| { 199 | !(p.starts_with('.') 200 | || p.contains("/.") 201 | || p.starts_with("logseq/bak/") 202 | || p.starts_with("logseq/version-files/")) 203 | }) 204 | .map(|p| self.get_file_meta(&base_path_ref, p)) 205 | }; 206 | Ok(future::join_all(futs) 207 | .await 208 | .into_iter() 209 | .filter(Result::is_ok) 210 | .map(Result::unwrap)) 211 | } 212 | 213 | pub async fn rename_local_file, S0: AsRef, S1: AsRef>( 214 | &self, 215 | base_path: P, 216 | from: S0, 217 | to: S1, 218 | ) -> Result<()> { 219 | let base_path = base_path.as_ref(); 220 | fs::rename(base_path.join(from.as_ref()), base_path.join(to.as_ref())).await?; 221 | Ok(()) 222 | } 223 | 224 | // delete local file 225 | pub async fn delete_local_files, S: AsRef>( 226 | &self, 227 | base_path: P, 228 | file_paths: impl IntoIterator, 229 | ) -> Result<()> { 230 | let base_path = base_path.as_ref(); 231 | let futs = file_paths 232 | .into_iter() 233 | .map(async move |p| fs::remove_file(base_path.join(p.as_ref())).await); 234 | future::join_all(futs) 235 | .await 236 | .into_iter() 237 | .collect::, _>>() 238 | .map_err(Error::from) 239 | .map(|_| ()) 240 | } 241 | 242 | // Delete remote file, and local base version, return txid 243 | pub async fn delete_remote_files, S: AsRef>( 244 | &self, 245 | base_path: P, 246 | file_paths: impl IntoIterator, 247 | txid: i64, 248 | token: &str, 249 | ) -> Result { 250 | let base_path = base_path.as_ref(); 251 | let mut client = SyncClient::new(&token); 252 | client.set_graph(&self.uuid, txid); 253 | 254 | let file_paths = file_paths 255 | .into_iter() 256 | .map(|s| s.as_ref().to_string()) 257 | .collect::>(); 258 | 259 | let encrypted_file_paths = file_paths 260 | .iter() 261 | .map(|p| self.encrypt_filename(&p)) 262 | .collect::>>()?; 263 | 264 | let ret = client.delete_files(encrypted_file_paths).await?; 265 | 266 | for file_rpath in &file_paths { 267 | let _ = 268 | fs::remove_file(base_path.join("logseq/version-files/base").join(file_rpath)).await; 269 | } 270 | 271 | Ok(ret.txid) 272 | } 273 | 274 | /// Logseq Sync v2: Fetch remote files to local version DB. 275 | /// To replace `update_local_files`. 276 | /// 277 | /// Return list of local downloaded files, ready to be merged. 278 | pub async fn fetch_remote_files, S: AsRef>( 279 | &self, 280 | base_path: P, 281 | file_paths: impl IntoIterator, 282 | token: &str, 283 | ) -> Result> { 284 | let mut cancel_notification = unsafe { CANCELLACTION_RX.as_ref().unwrap().clone() }; 285 | let _ = cancel_notification.borrow_and_update(); 286 | 287 | let base_path = base_path.as_ref(); 288 | let mut client = SyncClient::new(&token); 289 | client.set_graph(&self.uuid, 0); 290 | let client = Arc::new(client); 291 | 292 | // Vec<(encrypted_file_path, file_path)> 293 | let encrypted_paths = file_paths 294 | .into_iter() 295 | .map(|p| { 296 | self.encrypt_filename(p.as_ref()) 297 | .map(|ep| (ep, p.as_ref().to_string())) 298 | }) 299 | .collect::>>()?; 300 | 301 | // encrypted_file_path => remote_url 302 | let remote_files = client.get_files(encrypted_paths.keys()).await?; 303 | log::debug!("get {} remote files", remote_files.len()); 304 | 305 | let mut tasks = vec![]; 306 | for (encrypted_file_path, remote_url) in remote_files { 307 | let file_path = match encrypted_paths.get(&encrypted_file_path) { 308 | Some(p) => p.to_owned(), 309 | None => continue, 310 | }; 311 | 312 | let client = client.clone(); 313 | let graph_uuid = self.uuid.clone(); 314 | 315 | let target_file_path = if is_page_file(&file_path) { 316 | base_path 317 | .join("logseq/version-files/incoming") 318 | .join(&file_path) 319 | } else { 320 | base_path.join(&file_path) 321 | }; 322 | 323 | // avoid use of moved value 324 | let file_path1 = file_path.clone(); 325 | 326 | let progress_callback = move |bytes, total| { 327 | static mut LAST: usize = 0; 328 | let progress = bytes * 100 / total; 329 | unsafe { 330 | // reduce callback calling frequency 331 | if LAST / 10 != progress / 10 || bytes == total { 332 | LAST = progress; 333 | if let Some(callback) = &PROGRESS_CALLBACK { 334 | let progress = 335 | Progress::download(&graph_uuid, &file_path, bytes as _, total as _); 336 | callback(progress); 337 | } 338 | log::debug!( 339 | "download progress: {}% {}/{} {:?}", 340 | progress, 341 | bytes, 342 | total, 343 | file_path 344 | ); 345 | } 346 | } 347 | }; 348 | 349 | tasks.push(async move { 350 | let buf = client.download_file(&remote_url, progress_callback).await?; 351 | let decrypted = self.decrypt_content(&buf)?; 352 | 353 | if let Some(dir) = target_file_path.parent() { 354 | fs::create_dir_all(dir).await?; 355 | } 356 | let mut file = fs::File::create(&target_file_path).await?; 357 | file.write_all(&decrypted).await?; 358 | file.flush().await?; 359 | log::debug!("write to file: {:?}", target_file_path); 360 | 361 | if is_page_file_path(&file_path1) { 362 | Ok::<_, Error>(Some(file_path1.clone())) 363 | } else { 364 | Ok::<_, Error>(None) 365 | } 366 | }); 367 | } 368 | 369 | tokio::select! { 370 | ret = future::join_all(tasks) => { 371 | ret.into_iter().filter_map(|f| f.transpose()).collect() 372 | } 373 | _ = cancel_notification.changed() => { 374 | log::warn!("downloading remote cancelled"); 375 | Err(Error::Cancelled) 376 | } 377 | } 378 | } 379 | 380 | /// Download files from remote, and update local files. 381 | pub async fn update_local_files, S: AsRef>( 382 | &self, 383 | base_path: P, 384 | file_paths: impl IntoIterator, 385 | token: &str, 386 | ) -> Result<()> { 387 | let mut cancel_notification = unsafe { CANCELLACTION_RX.as_ref().unwrap().clone() }; 388 | let _ = cancel_notification.borrow_and_update(); 389 | 390 | let mut client = SyncClient::new(&token); 391 | client.set_graph(&self.uuid, 0); 392 | let client = Arc::new(client); 393 | 394 | let base_path = base_path.as_ref(); 395 | // Vec<(encrypted_file_path, file_path)> 396 | let encrypted_paths = file_paths 397 | .into_iter() 398 | .map(|p| { 399 | self.encrypt_filename(p.as_ref()) 400 | .map(|ep| (ep, p.as_ref().to_string())) 401 | }) 402 | .collect::>>()?; 403 | 404 | // encrypted_file_path => remote_url 405 | let remote_files = client.get_files(encrypted_paths.keys()).await?; 406 | log::debug!("get {} remote files", remote_files.len()); 407 | 408 | let mut tasks = vec![]; 409 | for (encrypted_file_path, remote_url) in remote_files { 410 | let file_path = match encrypted_paths.get(&encrypted_file_path) { 411 | Some(p) => p.to_owned(), 412 | None => continue, 413 | }; 414 | 415 | let absolute_file_path = base_path.join(&file_path); 416 | let client = client.clone(); 417 | let graph_uuid = self.uuid.clone(); 418 | 419 | let progress_callback = move |bytes, total| { 420 | static mut LAST: usize = 0; 421 | let progress = bytes * 100 / total; 422 | unsafe { 423 | // reduce callback calling frequency 424 | if LAST / 10 != progress / 10 || bytes == total { 425 | LAST = progress; 426 | if let Some(callback) = &PROGRESS_CALLBACK { 427 | let progress = 428 | Progress::download(&graph_uuid, &file_path, bytes as _, total as _); 429 | callback(progress); 430 | } 431 | log::debug!( 432 | "download progress: {}% {}/{} {:?}", 433 | progress, 434 | bytes, 435 | total, 436 | file_path 437 | ); 438 | } 439 | } 440 | }; 441 | tasks.push(async move { 442 | let buf = client.download_file(&remote_url, progress_callback).await?; 443 | let decrypted = self.decrypt_content(&buf)?; 444 | 445 | if let Some(dir) = absolute_file_path.parent() { 446 | fs::create_dir_all(dir).await?; 447 | } 448 | let mut file = fs::File::create(absolute_file_path).await?; 449 | file.write_all(&decrypted).await?; 450 | file.flush().await?; 451 | Ok::<_, Error>(()) 452 | }); 453 | } 454 | 455 | tokio::select! { 456 | ret = future::join_all(tasks) => { 457 | ret.into_iter().collect::>>().map(|_| ()) 458 | } 459 | _ = cancel_notification.changed() => { 460 | log::warn!("downloading remote cancelled"); 461 | Err(Error::Cancelled) 462 | } 463 | } 464 | } 465 | 466 | /// Logseq Sync v2, update remote files and save to local version-db. 467 | pub async fn update_remote_files, S: AsRef>( 468 | &self, 469 | base_path: P, 470 | file_paths: impl IntoIterator, 471 | txid: i64, 472 | token: &str, 473 | _metadata: Option, // TODO 474 | ) -> Result { 475 | let mut cancel_notification = unsafe { CANCELLACTION_RX.as_ref().unwrap().clone() }; 476 | let _ = cancel_notification.borrow_and_update(); 477 | 478 | let mut client = SyncClient::new(&token); 479 | client.set_graph(&self.uuid, txid); 480 | client.refresh_temp_credential().await?; 481 | 482 | let base_path = base_path.as_ref(); 483 | let client = Arc::new(client); 484 | 485 | // ensure folder and write permission 486 | fs::create_dir_all(base_path.join("logseq/version-files/base")).await?; 487 | 488 | let mut tasks = vec![]; 489 | let mut page_files = vec![]; 490 | for file_path in file_paths { 491 | // move in variables 492 | let client = client.clone(); 493 | let file_path = file_path.as_ref().to_string(); 494 | if is_page_file_path(&file_path) { 495 | page_files.push(file_path.clone()); 496 | } 497 | 498 | let full_file_path = base_path.join(&file_path); 499 | 500 | let progress_callback = { 501 | let file_path = file_path.clone(); 502 | let graph_uuid = self.uuid.clone(); 503 | 504 | move |bytes, total| { 505 | static mut LAST: usize = 0; 506 | let progress = bytes * 100 / total; 507 | unsafe { 508 | // reduce notifications 509 | if LAST / 10 != progress / 10 || bytes == total { 510 | if let Some(callback) = &PROGRESS_CALLBACK { 511 | let progress = Progress::upload( 512 | &graph_uuid, 513 | &file_path, 514 | bytes as _, 515 | total as _, 516 | ); 517 | callback(progress); 518 | } 519 | LAST = progress; 520 | log::debug!( 521 | "upload progress: {}% {}/{} {}", 522 | progress, 523 | bytes, 524 | total, 525 | file_path 526 | ); 527 | } 528 | } 529 | } 530 | }; 531 | tasks.push(async move { 532 | let content = fs::read(full_file_path).await?; 533 | // stage 1.1: md5 metadata 534 | let md5checksum = md5_hexdigest(&content); 535 | // stage 1.2: encryption 536 | let encrypted = self.encrypt_content(&content)?; 537 | if encrypted.len() > 10 * 1024 * 1024 { 538 | log::warn!( 539 | "large file {:?} size: {:.2}MiB encrypted: {:.2}MiB", 540 | file_path, 541 | content.len() as f64 / (1024.0 * 1024.0), 542 | encrypted.len() as f64 / (1024.0 * 1024.0) 543 | ); 544 | } 545 | let remote_temp_url = client.upload_tempfile(encrypted, progress_callback).await?; 546 | let encrypted_file_path = self.encrypt_filename(&file_path)?; 547 | Result::Ok((encrypted_file_path, remote_temp_url, md5checksum)) 548 | }); 549 | } 550 | 551 | tokio::select! { 552 | task_results = future::join_all(tasks) => { 553 | let temp_remote_files = task_results.into_iter().collect::>>()?; 554 | let update = client.update_files(temp_remote_files).await?; 555 | for path in page_files { 556 | let target_path = base_path.join("logseq/version-files/base").join(&path); 557 | if let Some(dir) = target_path.parent() { 558 | fs::create_dir_all(dir).await?; 559 | } 560 | fs::copy(base_path.join(&path),target_path ).await?; 561 | log::debug!("copy page file to version-files: {:?}", path); 562 | } 563 | Ok(update.txid) 564 | } 565 | _ = cancel_notification.changed() => { 566 | log::warn!("update remote file cancelled"); 567 | Err(Error::Cancelled) 568 | } 569 | } 570 | } 571 | 572 | pub async fn update_local_version_files, S: AsRef>( 573 | &self, 574 | base_path: P, 575 | file_ids: impl IntoIterator, 576 | token: &str, 577 | ) -> Result<()> { 578 | let base_path = base_path.as_ref(); 579 | let mut client = SyncClient::new(&token); 580 | client.set_graph(&self.uuid, 0); 581 | 582 | let files = client.get_version_files(file_ids).await?; 583 | for (file_id, file_url) in files { 584 | let full_file_path = base_path.join("logseq/version-files").join(&file_id); 585 | 586 | let buf = client.download_file(&file_url, |_, _| {}).await?; 587 | let decrypted = self.decrypt_content(&buf)?; 588 | 589 | if let Some(file_dir) = full_file_path.parent() { 590 | fs::create_dir_all(file_dir).await?; 591 | } 592 | let mut file = fs::File::create(full_file_path).await?; 593 | file.write_all(&decrypted).await?; 594 | file.flush().await?; 595 | } 596 | Ok(()) 597 | } 598 | 599 | async fn get_file_meta, S: AsRef>( 600 | &self, 601 | base_path: P, 602 | file_path: S, 603 | ) -> Result { 604 | use md5::{Digest, Md5}; 605 | let base_path = dunce::canonicalize(base_path.as_ref())?; 606 | let full_file_path = dunce::canonicalize(base_path.join(file_path.as_ref()))?; 607 | 608 | let canonicalized_file_path = full_file_path 609 | .strip_prefix(&base_path) 610 | .ok() 611 | .and_then(|p| p.to_str()) 612 | .map(|p| p.replace("\\", "/").trim_start_matches('/').to_string()) 613 | .ok_or(Error::InvalidArg)?; 614 | let normalized_file_path = canonicalized_file_path.nfc().collect::(); 615 | 616 | let mut file = fs::File::open(&full_file_path).await?; 617 | 618 | let mut nread = 0; 619 | let mut buf = Vec::with_capacity(1024 * 1024); 620 | let mut hasher = Md5::new(); 621 | loop { 622 | let n = file.read_buf(&mut buf).await?; 623 | if n == 0 { 624 | break; 625 | } 626 | nread += n; 627 | hasher.update(&buf[..n]); 628 | unsafe { 629 | buf.set_len(0); 630 | } 631 | } 632 | let digest = hasher.finalize(); 633 | 634 | let metadata = file.metadata().await?; 635 | Ok(FileMeta { 636 | size: nread as _, 637 | mtime: metadata 638 | .modified() 639 | .ok() 640 | .and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok()) 641 | .unwrap_or(Duration::default()) 642 | .as_millis() as _, 643 | ctime: metadata 644 | .created() 645 | .ok() 646 | .and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok()) 647 | .unwrap_or(Duration::default()) 648 | .as_millis() as _, 649 | md5: format!("{:x}", digest), 650 | fname: canonicalized_file_path.to_owned(), 651 | incoming_fname: file_path.as_ref().to_string(), 652 | normalized_fname: normalized_file_path, 653 | encrypted_fname: self.encrypt_filename(&canonicalized_file_path)?, 654 | }) 655 | } 656 | } 657 | 658 | unsafe impl Send for Graph {} 659 | unsafe impl Sync for Graph {} 660 | 661 | #[cfg_attr(feature = "napi", napi(object))] 662 | #[derive(Debug)] 663 | pub struct FileMeta { 664 | pub size: i64, 665 | /// modified time, in milliseconds 666 | pub mtime: i64, 667 | /// creation time, in milliseconds 668 | pub ctime: i64, 669 | pub md5: String, 670 | // legacy field 671 | pub fname: String, 672 | pub incoming_fname: String, 673 | // NFC normalized file name 674 | pub normalized_fname: String, 675 | // encrypted file name 676 | pub encrypted_fname: String, 677 | } 678 | 679 | /// Metadata for batch remote update 680 | #[cfg_attr(feature = "napi", napi(object))] 681 | #[derive(Debug)] 682 | pub struct Metadata { 683 | pub fs_case_sensitive: bool, 684 | pub version: String, 685 | pub revision: String, 686 | pub platform: String, 687 | } 688 | 689 | fn is_page_file(file_path: &str) -> bool { 690 | let t = file_path.to_lowercase(); 691 | t.ends_with(".md") || t.ends_with(".org") || t.ends_with(".markdown") 692 | } 693 | 694 | fn is_page_file_path>(file_path: P) -> bool { 695 | let t = file_path 696 | .as_ref() 697 | .file_name() 698 | .unwrap() 699 | .to_str() 700 | .unwrap() 701 | .to_lowercase(); 702 | t.ends_with(".md") || t.ends_with(".org") || t.ends_with(".markdown") 703 | } 704 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | Additional permission under GNU GPL version 3 section 7 664 | 665 | If you modify this Program, or any covered work, by linking or combining it with any of the below libraries (or a modified version of that library), containing parts covered by the terms of any of the below libraries, the licensors of this Program grant you additional permission to convey the resulting work. 666 | 667 | * cider/cider-nrepl 668 | * clojure-complete 669 | * com.cemerick/friend 670 | * compojure 671 | * environ 672 | * hiccup 673 | * medley 674 | * org.clojure/clojure 675 | * org.clojure/clojurescript 676 | * org.clojure/core.async 677 | * org.clojure/core.cache 678 | * org.clojure/core.incubator 679 | * org.clojure/core.logic 680 | * org.clojure/core.match 681 | * org.clojure/core.memoize 682 | * org.clojure/data.csv 683 | * org.clojure/data.json 684 | * org.clojure/data.priority-map 685 | * org.clojure/java.classpath 686 | * org.clojure/java.jdbc 687 | * org.clojure/math.numeric-tower 688 | * org.clojure/tools.analyzer 689 | * org.clojure/tools.analyzer.jvm 690 | * org.clojure/tools.logging 691 | * org.clojure/tools.macro 692 | * org.clojure/tools.namespace 693 | * org.clojure/tools.nrepl 694 | * org.clojure/tools.reader 695 | * org.tcrawley/dynapath 696 | * refactor-nrepl 697 | * slingshot 698 | --------------------------------------------------------------------------------