core-3nweb-client-lib 0.20.0 → 0.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,16 +24,6 @@ const protobuf_loader_1 = require("../protobuf-loader");
24
24
  const processes_1 = require("../../lib-common/processes");
25
25
  const assert_1 = require("../../lib-common/assert");
26
26
  const error_1 = require("../../lib-common/exceptions/error");
27
- function inNextTick(f) {
28
- return new Promise((resolve, reject) => process.nextTick(() => {
29
- try {
30
- resolve(f());
31
- }
32
- catch (err) {
33
- reject(err);
34
- }
35
- }));
36
- }
37
27
  function wasmBytes() {
38
28
  // There is a bug with electrons 12, 13, that doesn't let
39
29
  // worker_thread read this file from asar pack, even though main thread
@@ -45,7 +35,15 @@ function wasmBytes() {
45
35
  const dirWithThis = ((asarInd < 0) ?
46
36
  __dirname : `${__dirname.substring(0, asarInd + 8)}.unpacked${__dirname.substring(asarInd + 8)}`);
47
37
  const wasmPath = path_1.join(dirWithThis, 'cryptor.wasm');
48
- return fs_1.readFileSync(wasmPath);
38
+ try {
39
+ return fs_1.readFileSync(wasmPath);
40
+ }
41
+ catch (err) {
42
+ // chances are that error is due to wasm file not being packaged, so, we
43
+ // look for module with base64 form in a module, that must've been packed
44
+ const str = require('./cryptor-wasm.js').wasm;
45
+ return Buffer.from(str, 'base64');
46
+ }
49
47
  }
50
48
  function makeProtobufType(type) {
51
49
  const protoFile = 'cryptor.proto';
@@ -57,8 +55,8 @@ function makeProtobufType(type) {
57
55
  catch (err) {
58
56
  // we won't get here if referenced module exists, but metro packager
59
57
  // in LiqudCore needs static path require
60
- require('./proto-defs');
61
- return protobuf_loader_1.ProtoType.makeFrom(__dirname, protoFile, typeName);
58
+ const fallback = require('./proto-defs');
59
+ return protobuf_loader_1.ProtoType.makeFrom(__dirname, protoFile, typeName, fallback);
62
60
  }
63
61
  }
64
62
  function toArgs(...args) {
@@ -83,9 +81,16 @@ function makeInProcessWasmCryptor() {
83
81
  const wasmInstance = wasm_mp1_modules_1.startWasmFrom(wasmBytes());
84
82
  let deferred = undefined;
85
83
  let interimSink = undefined;
86
- function call(req, interim) {
84
+ async function call(req, interim) {
85
+ // In LiquidCore on iOS call was able to get before completion of
86
+ // previous call, therefore, the following await loop is needed.
87
+ while (!!deferred) {
88
+ try {
89
+ await deferred.promise;
90
+ }
91
+ catch (err) { }
92
+ }
87
93
  deferred = processes_1.defer();
88
- const promise = deferred.promise;
89
94
  if (interim) {
90
95
  interimSink = interim;
91
96
  }
@@ -97,7 +102,7 @@ function makeInProcessWasmCryptor() {
97
102
  deferred === null || deferred === void 0 ? void 0 : deferred.reject(err);
98
103
  }
99
104
  });
100
- return promise;
105
+ return deferred.promise;
101
106
  }
102
107
  wasmInstance.setMsgListener(msg => {
103
108
  assert_1.assert(!!deferred, `Deferred is expected to be available for this output from wasm`);
@@ -2,7 +2,9 @@
2
2
  export declare class ProtoType<T extends object> {
3
3
  private type;
4
4
  private constructor();
5
- static makeFrom<T extends object>(searchDir: string, protoFile: string, typeName: string): ProtoType<T>;
5
+ static makeFrom<T extends object>(searchDir: string, protoFile: string, typeName: string, fallbackMod?: {
6
+ protos: object;
7
+ }): ProtoType<T>;
6
8
  pack(msg: T): Buffer;
7
9
  unpack(bytes: Buffer | void): T;
8
10
  packToBase64(msg: T): string;
@@ -25,8 +25,8 @@ class ProtoType {
25
25
  this.type = type;
26
26
  Object.freeze(this);
27
27
  }
28
- static makeFrom(searchDir, protoFile, typeName) {
29
- const root = loadRoot(searchDir, protoFile);
28
+ static makeFrom(searchDir, protoFile, typeName, fallbackMod) {
29
+ const root = loadRoot(searchDir, protoFile, fallbackMod);
30
30
  const type = root.lookupType(typeName);
31
31
  return new ProtoType(type);
32
32
  }
@@ -58,7 +58,7 @@ exports.ProtoType = ProtoType;
58
58
  Object.freeze(ProtoType.prototype);
59
59
  Object.freeze(ProtoType);
60
60
  const roots = new Map();
61
- function loadRoot(searchDir, fileName) {
61
+ function loadRoot(searchDir, fileName, fallbackMod) {
62
62
  const filePath = path_1.resolve(searchDir, 'protos', fileName);
63
63
  let root = roots.get(filePath);
64
64
  if (!root) {
@@ -67,9 +67,10 @@ function loadRoot(searchDir, fileName) {
67
67
  root = protobuf.loadSync(filePath);
68
68
  }
69
69
  catch (err) {
70
- // make sure to generate proto-defs with compile step (use npm script)
71
- const fallbackMod = path_1.join(path_1.relative(__dirname, searchDir), 'proto-defs');
72
- const protos = require(fallbackMod).protos;
70
+ if (!fallbackMod) {
71
+ throw err;
72
+ }
73
+ const protos = fallbackMod.protos;
73
74
  if (!protos || (typeof protos !== 'object')) {
74
75
  throw new Error(`proto-defs doesn't have expected object`);
75
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "core-3nweb-client-lib",
3
- "version": "0.20.0",
3
+ "version": "0.20.4",
4
4
  "description": "3NWeb client core library, embeddable into different environments",
5
5
  "main": "build/lib-index.js",
6
6
  "types": "build/lib-index.d.ts",
@@ -1,18 +0,0 @@
1
- [package]
2
- name = "cryptor"
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
- [lib]
9
- crate-type = ["cdylib", "rlib"]
10
-
11
- [dependencies]
12
- wasm-bindgen = "0.2.78"
13
- nacl = "0.5.3"
14
- wasm-message-passing-3nweb = "0.2.0"
15
- prost = "0.9.0"
16
-
17
- [build-dependencies]
18
- prost-build = "0.9.0"
@@ -1,29 +0,0 @@
1
- use std::io::Result;
2
- use std::fs::{read_dir};
3
-
4
- const PROTOS_DIR: &str = "./protos";
5
-
6
- fn main() -> Result<()> {
7
- let proto_file_paths: Vec<_> = read_dir(PROTOS_DIR)?
8
- .filter_map(|res| {
9
- if res.is_ok() {
10
- res.ok()
11
- } else {
12
- eprintln!("Path Listing error: {}", res.err().unwrap());
13
- None
14
- }
15
- })
16
- .filter(|entry| {
17
- let f_type_res = entry.file_type();
18
- if f_type_res.is_ok() {
19
- f_type_res.ok().unwrap().is_file()
20
- } else {
21
- eprintln!("Path Listing error: {}", f_type_res.err().unwrap());
22
- false
23
- }
24
- })
25
- .map(|file_entry| file_entry.path())
26
- .collect();
27
- prost_build::compile_protos(&proto_file_paths, &[PROTOS_DIR])?;
28
- Ok(())
29
- }
@@ -1,45 +0,0 @@
1
- syntax = "proto3";
2
-
3
- package cryptor;
4
-
5
- message Request {
6
-
7
- message ScryptArgs {
8
- bytes passwd = 1;
9
- bytes salt = 2;
10
- uint32 logN = 3;
11
- uint32 r = 4;
12
- uint32 p = 5;
13
- uint32 dkLen = 6;
14
- }
15
-
16
- uint32 func = 1;
17
- repeated BytesVal byte_args = 2;
18
- ScryptArgs scrypt_args = 3;
19
-
20
- }
21
-
22
- message BytesVal {
23
- bytes val = 1;
24
- }
25
-
26
- message Reply {
27
-
28
- message Error {
29
- string condition = 1;
30
- string message = 2;
31
- }
32
-
33
- BytesVal res = 1;
34
- BytesVal interim = 2;
35
- Error err = 3;
36
- }
37
-
38
- message BoolVal {
39
- bool val = 1;
40
- }
41
-
42
- message Keypair {
43
- bytes skey = 1;
44
- bytes pkey = 2;
45
- }
@@ -1,131 +0,0 @@
1
- // Copyright(c) 2021 3NSoft Inc.
2
- //
3
- // This program is free software: you can redistribute it and/or modify
4
- // it under the terms of the GNU Lesser General Public License as published by
5
- // the Free Software Foundation, either version 3 of the License, or
6
- // (at your option) any later version.
7
- //
8
- // This program is distributed in the hope that it will be useful,
9
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
10
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
- // GNU Lesser General Public License for more details.
12
- //
13
- // You should have received a copy of the GNU Lesser General Public License
14
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
15
-
16
- mod pb;
17
-
18
- use wasm_bindgen::prelude::*;
19
- use wasm_message_passing_3nweb::wasm_mp1::{ send_msg_out, set_msg_processor };
20
- use pb::cryptor::{ Request, Reply, Keypair, request, BytesVal, BoolVal, reply };
21
- use prost::Message;
22
- use prost::bytes::Bytes;
23
- use nacl::{ secret_box as sbox, public_box as pbox, scrypt, sign, Error, ErrorCondition };
24
-
25
- #[wasm_bindgen]
26
- pub fn _start() -> () {
27
- set_msg_processor(&process_nacl_call);
28
- }
29
-
30
- fn process_nacl_call(msg: Vec<u8>) -> () {
31
- let req = match Request::decode(Bytes::from(msg)) {
32
- Ok(r) => r,
33
- Err(err) => {
34
- send_error(reply::Error {
35
- condition: "message-passing-error".to_string(),
36
- message: format!("{}", err)
37
- });
38
- return;
39
- }
40
- };
41
-
42
- let reply = match req.func {
43
- 1 => {
44
- let request::ScryptArgs {
45
- passwd, salt, log_n, r, p, dk_len
46
- } = req.scrypt_args.unwrap();
47
- let progress_cb = |p: u32| send_msg_out(& pack_interim(vec!(p as u8)));
48
- scrypt(&passwd, &salt,
49
- log_n as u8, r as usize, p as usize, dk_len as usize, & progress_cb)
50
- },
51
- 2 => pbox::calc_dhshared_key(arg(&req, 0), arg(&req, 1)),
52
- 3 => pbox::generate_pubkey(arg(&req, 0)),
53
- 4 => sbox::open(arg(&req, 0), arg(&req, 1), arg(&req, 2)),
54
- 5 => sbox::pack(arg(&req, 0), arg(&req, 1), arg(&req, 2)),
55
- 6 => sbox::format_wn::open(arg(&req, 0), arg(&req, 1)),
56
- 7 => sbox::format_wn::pack(
57
- arg(&req, 0), arg(&req, 1), arg(&req, 2)),
58
- 8 => {
59
- let sign::Keypair{ skey, pkey } =
60
- sign::generate_keypair(arg(&req, 0));
61
- let bytes = Keypair {
62
- skey: skey.to_vec(), pkey: pkey.to_vec()
63
- }.encode_to_vec();
64
- Ok(bytes)
65
- },
66
- 9 => sign::signature(arg(&req, 0), arg(&req, 1)),
67
- 10 => match sign::verify(
68
- arg(&req, 0), arg(&req, 1), arg(&req, 2)
69
- ) {
70
- Ok(b) => Ok(BoolVal { val: b }.encode_to_vec()),
71
- Err(err) => Err(err)
72
- },
73
- fnum => {
74
- send_error(reply::Error {
75
- condition: "message-passing-error".to_string(),
76
- message: format!("Unrecognized func number {}", fnum)
77
- });
78
- return;
79
- }
80
- };
81
-
82
- let reply_msg = match reply {
83
- Ok(res) => pack_ok(res),
84
- Err(err) => pack_err(nacl_err_to_msg(err)),
85
- };
86
-
87
- send_msg_out(&reply_msg);
88
- }
89
-
90
- fn arg(req: &Request, i: usize) -> &[u8] {
91
- req.byte_args[i].val.as_slice()
92
- }
93
-
94
- fn pack_bytes(bytes: Vec<u8>) -> Option<BytesVal> {
95
- Some(BytesVal {
96
- val: bytes
97
- })
98
- }
99
-
100
- fn pack_ok(bytes: Vec<u8>) -> Vec<u8> {
101
- Reply {
102
- res: pack_bytes(bytes), interim: None, err: None
103
- }.encode_to_vec()
104
- }
105
-
106
- fn pack_interim(bytes: Vec<u8>) -> Vec<u8> {
107
- Reply {
108
- res: None, interim: pack_bytes(bytes), err: None
109
- }.encode_to_vec()
110
- }
111
-
112
- fn nacl_err_to_msg(err: Error) -> reply::Error {
113
- reply::Error {
114
- condition: match err.condition {
115
- ErrorCondition::CipherVerification => "cipher-verification",
116
- ErrorCondition::SignatureVerification => "signature-verification",
117
- ErrorCondition::Configuration => "configuration-error",
118
- }.to_string(),
119
- message: err.message,
120
- }
121
- }
122
-
123
- fn pack_err(err: reply::Error) -> Vec<u8> {
124
- Reply {
125
- res: None, interim: None, err: Some(err)
126
- }.encode_to_vec()
127
- }
128
-
129
- fn send_error(err: reply::Error) -> () {
130
- send_msg_out(& pack_err(err));
131
- }
@@ -1,27 +0,0 @@
1
- // Copyright(c) 2021 3NSoft Inc.
2
- //
3
- // This program is free software: you can redistribute it and/or modify
4
- // it under the terms of the GNU Lesser General Public License as published by
5
- // the Free Software Foundation, either version 3 of the License, or
6
- // (at your option) any later version.
7
- //
8
- // This program is distributed in the hope that it will be useful,
9
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
10
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
- // GNU Lesser General Public License for more details.
12
- //
13
- // You should have received a copy of the GNU Lesser General Public License
14
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
15
-
16
-
17
- macro_rules! modules_with_pb_objects {
18
- ( $( $mod_name: ident ), * ) => {
19
- $(pub mod $mod_name {
20
- include!(concat!(env!("OUT_DIR"), "/", stringify!($mod_name), ".rs"));
21
- })*
22
- }
23
- }
24
-
25
- modules_with_pb_objects!(
26
- cryptor
27
- );
@@ -1,49 +0,0 @@
1
-
2
- const fs = require('fs');
3
-
4
- const mod = new WebAssembly.Module(fs.readFileSync('./pkg/cryptor_bg.wasm'));
5
-
6
- function msgFromWASM(ptr, len) {
7
- console.log(`Invoked _3nweb_mp1_send_out_msg(ptr = ${ptr}, len = ${len})`);
8
- const msgInBuf = new Uint8Array(instance.exports.memory.buffer, ptr, len);
9
- replyFromWasm = new Uint8Array(msgInBuf.length);
10
- replyFromWasm.set(msgInBuf);
11
- console.log(`Reply from WASM is`, replyFromWasm);
12
- }
13
-
14
- let replyFromWasm;
15
-
16
- const imports = {
17
- env: {
18
- _3nweb_mp1_send_out_msg: msgFromWASM,
19
- }
20
- };
21
-
22
- const instance = new WebAssembly.Instance(mod, imports);
23
- console.log(`WASM instance has following exports:`, instance.exports);
24
-
25
- console.log(`\nStarting instance`);
26
- instance.exports._start();
27
-
28
- function test(msg) {
29
- console.log(`Sending message to WASM`);
30
-
31
- console.log(`Getting buffer for message length`, msg.length);
32
-
33
- let ptr = instance.exports._3nweb_mp1_get_buffer(msg.length);
34
- console.log(`Pointer is`, ptr);
35
-
36
- let buf = new Uint8Array(instance.exports.memory.buffer, ptr, msg.length);
37
- buf.set(msg);
38
- console.log(`Message is placed into buffer`, buf);
39
-
40
- console.log(`Telling WASM instance to process message`);
41
- instance.exports._3nweb_mp1_accept_msg(msg.length);
42
- }
43
-
44
- console.log(`\nTest 1`);
45
- test(new Uint8Array([1,2,3,4,5,6,7,8,9,10]));
46
- for (let i of [2,3,4]) {
47
- console.log(`\nTest ${i}`);
48
- test(replyFromWasm);
49
- }