Setup ts compilation

- import frontend code from mCaptcha/benchs
- setup TS compilation workflow
- import vendor code from mCaptcha/mCaptcha/browser
- rewrite bench.js import in bundle.js to include file's hash
This commit is contained in:
Aravinth Manivannan 2021-10-12 14:02:34 +05:30
parent 377b825fe4
commit 2609ade2a5
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88
22 changed files with 6419 additions and 4 deletions

View file

@ -52,7 +52,7 @@ jobs:
profile: minimal
override: true
- name: build sass
- name: build frtontend assets
run: make frontend
- name: Run migrations

View file

@ -54,7 +54,7 @@ jobs:
profile: minimal
override: true
- name: build sass
- name: build frtontend assets
run: make frontend
- name: Run migrations

View file

@ -30,6 +30,8 @@ frontend: ## Build frontend assets
@yarn install
@-rm -rf ./static/cache/bundle/
@-mkdir ./static/cache/bundle/css/
@yarn build
@./scripts/bundle.sh
#@yarn run dart-sass -s compressed templates/main.scss ./static/cache/bundle/css/main.css
lint: ## Lint codebase

View file

@ -3,11 +3,31 @@
"main": "index.js",
"version": "1.0.0",
"scripts": {
"prod": "yarn run dart-sass",
"build": "webpack --mode production",
"sass": "yarn run dart-sass",
"start": "webpack-dev-server --mode development --progress --color",
"test": "jest"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/jsdom": "^16.2.10",
"@types/node": "^15.0.2",
"@types/sinon": "^10.0.0",
"@wasm-tool/wasm-pack-plugin": "^1.4.0",
"jest": "^26.6.3",
"jest-fetch-mock": "^3.0.3",
"jsdom": "^16.5.3",
"sinon": "^10.0.0",
"ts-jest": "^26.5.6",
"ts-loader": "^8.0.0",
"ts-node": "^9.1.1",
"typescript": "^4.1.0",
"webpack": "^5.0.0",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.1.14",
"dart-sass": "^1.25.0"
},
"dependencies": {
"mcaptcha-browser": "./vendor/pow/"
}
}

7
scripts/bundle.sh Executable file
View file

@ -0,0 +1,7 @@
#!/bin/bash
bench_hash=$(sha256sum ./static/cache/bundle/bench.js \
| cut -d " " -f 1 \
| tr "[:lower:]" "[:upper:]")
sed -i "s/bench.js/bench.$bench_hash.js/" ./static/cache/bundle/bundle.js

View file

@ -51,6 +51,9 @@ lazy_static! {
//
// pub static ref CSS: &'static str =
// FILES.get("./static/cache/bundle/css/main.css").unwrap();
pub static ref JS: &'static str =
FILES.get("./static/cache/bundle/bundle.js").unwrap();
/// points to source files matching build commit
pub static ref SOURCE_FILES_OF_INSTANCE: String = {
let mut url = SETTINGS.source_code.clone();

View file

@ -119,7 +119,7 @@ mod tests {
async fn static_assets_work() {
let app = get_app!().await;
for file in [assets::LOGO.path].iter() {
for file in [assets::LOGO.path, &*crate::JS].iter() {
let resp = test::call_service(
&app,
test::TestRequest::get().uri(file).to_request(),

46
templates/bench.ts Normal file
View file

@ -0,0 +1,46 @@
/*
* mCaptcha is a PoW based DoS protection software.
* This is the frontend web component of the mCaptcha system
* Copyright © 2021 Aravinth Manivnanan <realaravinth@batsense.net>.
*
* Use of this source code is governed by Apache 2.0 or MIT license.
* You shoud have received a copy of MIT and Apache 2.0 along with
* this program. If not, see <https://spdx.org/licenses/MIT.html> for
* MIT or <http://www.apache.org/licenses/LICENSE-2.0> for Apache.
*/
import {gen_pow} from 'mcaptcha-browser';
import {Perf} from './types';
type PoWConfig = {
string: string;
difficulty_factor: number;
salt: string;
};
const SALT = '674243647f1c355da8607a8cdda05120d79ca5d1af8b3b49359d056a0a82';
const PHRASE = '6e2a53dbc7d307970d7ba3c0000221722cb74f1c325137251ce8fa5c2240';
const config: PoWConfig = {
string: PHRASE,
difficulty_factor: 1,
salt: SALT,
};
console.debug('worker registered');
onmessage = function(event) {
console.debug('message received at worker');
let difficulty_factor = parseInt(event.data);
config.difficulty_factor = difficulty_factor;
const t0 = performance.now();
gen_pow(config.salt, config.string, config.difficulty_factor);
const t1 = performance.now();
const time = t1 - t0;
let msg: Perf = {
difficulty: difficulty_factor,
time: time,
};
postMessage(msg);
};

95
templates/index.ts Normal file
View file

@ -0,0 +1,95 @@
/*
* mCaptcha is a PoW based DoS protection software.
* This is the frontend web component of the mCaptcha system
* Copyright © 2021 Aravinth Manivnanan <realaravinth@batsense.net>.
*
* Use of this source code is governed by Apache 2.0 or MIT license.
* You shoud have received a copy of MIT and Apache 2.0 along with
* this program. If not, see <https://spdx.org/licenses/MIT.html> for
* MIT or <http://www.apache.org/licenses/LICENSE-2.0> for Apache.
*/
import {Perf} from './types';
const FACTOR = 500000;
const worker = new Worker('bench.js');
const res: Array<Perf> = [];
const stats = document.getElementById('stats');
const addResult = (perf: Perf) => {
const row = document.createElement('tr');
row.className = 'data';
const diff = document.createElement('td');
diff.innerHTML = perf.difficulty.toString();
const duration = document.createElement('td');
duration.innerHTML = perf.time.toString();
row.appendChild(diff);
row.appendChild(duration);
stats.appendChild(row);
res.push(perf);
};
const addDeviceInfo = () => {
const INFO = {
threads: window.navigator.hardwareConcurrency,
oscup: window.navigator.userAgent,
};
console.log(res);
console.log(INFO);
const element = document.createElement('div');
const ua = document.createElement('b');
ua.innerText = 'User Agent: ';
const os = document.createTextNode(`${INFO.oscup}`);
const threads = document.createElement('b');
threads.innerText = 'Hardware concurrency: ';
const threadsText = document.createTextNode(`${INFO.threads}`);
element.appendChild(ua);
element.appendChild(os);
element.appendChild(document.createElement('br'));
element.appendChild(threads);
element.appendChild(threadsText);
document.getElementById('device-info').appendChild(element);
};
const finished = () => {
const s = document.getElementById('status');
s.innerHTML = 'Benchmark finished';
};
const run = (e: Event) => {
e.preventDefault();
document.getElementById('pre-bench').style.display = 'none';
document.getElementById('bench').style.display = 'flex';
const iterations = 9;
const counterElement = document.getElementById('counter');
counterElement.innerText = `${iterations} more to go`;
worker.onmessage = (event: MessageEvent) => {
let data: Perf = event.data;
addResult(data);
if (res.length == iterations) {
finished();
counterElement.innerText = `All Done!`;
} else {
counterElement.innerText = `${iterations - res.length} more to go`;
}
};
for (let i = 1; i <= iterations; i++) {
let difficulty_factor = i * FACTOR;
worker.postMessage(difficulty_factor);
}
addDeviceInfo();
};
document.getElementById('start').addEventListener('click', e => run(e));

15
templates/types.ts Normal file
View file

@ -0,0 +1,15 @@
/*
* mCaptcha is a PoW based DoS protection software.
* This is the frontend web component of the mCaptcha system
* Copyright © 2021 Aravinth Manivnanan <realaravinth@batsense.net>.
*
* Use of this source code is governed by Apache 2.0 or MIT license.
* You shoud have received a copy of MIT and Apache 2.0 along with
* this program. If not, see <https://spdx.org/licenses/MIT.html> for
* MIT or <http://www.apache.org/licenses/LICENSE-2.0> for Apache.
*/
export type Perf = {
difficulty: Number;
time: Number;
};

43
tsconfig.json Normal file
View file

@ -0,0 +1,43 @@
{
"compilerOptions": {
"incremental": true,
"target": "es5",
"module": "es6",
"allowJs": false,
"sourceMap": true,
"outDir": "./dist/",
"rootDir": "./templates/",
"removeComments": true,
"moduleResolution": "node",
//"strict": true,
"noImplicitAny": true,
//"strictNullChecks": true,
//"strictFunctionTypes": true,
//"strictBindCallApply": true,
//"strictPropertyInitialization": true,
//"noImplicitThis": true,
//"alwaysStrict": true,
//"noUnusedLocals": true,
//"noUnusedParameters": true,
//"noImplicitReturns": true,
//"noFallthroughCasesInSwitch": true,
//"noUncheckedIndexedAccess": true,
//"noPropertyAccessFromIndexSignature": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"exclude": [
"node_modules",
"static",
"docs",
"jest.config.ts",
"**/*.test.ts",
"tmp",
"dist/"
]
}

176
vendor/pow/LICENSE_APACHE vendored Normal file
View file

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

25
vendor/pow/LICENSE_MIT vendored Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2018 realaravinth <realaravinth@batsense.net>
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

92
vendor/pow/README.md vendored Normal file
View file

@ -0,0 +1,92 @@
<div align="center">
<h1>PoW JavaScript library</h1>
<strong>JavaScript library to generate PoW for mCaptcha</strong>
[![0.1.0](https://img.shields.io/badge/Rust_docs-master-dea584)](https://mcaptcha.github.io/browser/rust/mcaptcha_browser/index.html)
[![0.1.0](https://img.shields.io/badge/TypeScript_docs-master-2b7489)](https://mcaptcha.github.io/browser/ts/docs/modules.html)
![Build)](<https://github.com/mCaptcha/browser/workflows/CI%20(Linux)/badge.svg>)
[![dependency status](https://deps.rs/repo/github/mCaptcha/browser/status.svg)](https://deps.rs/repo/github/mCaptcha/browser)
<br />
[![codecov](https://codecov.io/gh/mCaptcha/browser/branch/master/graph/badge.svg)](https://codecov.io/gh/mCaptcha/browser)
</div>
**NOTE:** wasm compilation currently requires `rustc` nightly and
wasm optimization of this library will have to be done manually at the
moment. Please refer to https://github.com/rustwasm/wasm-pack/issues/886
for more information.
### Optimization:
```
$ /path/to/wasm-opt pkg/pow_bg.wasm -o pkg/pow_bg.wasm -O --enable-mutable-globals
```
My `/path/to/wasm-opt` is `~/.cache/.wasm-pack/wasm-opt-4d7a65327e9363b7/wasm-opt`
---
<h2> Default documentation provided by Rust wasm: </h2>
<h3>
<a href="https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html">Tutorial</a>
<span> | </span>
<a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
</h3>
<sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
</div>
## About
[**📚 Read this template tutorial! 📚**][template-docs]
This template is designed for compiling Rust libraries into WebAssembly and
publishing the resulting package to NPM.
Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other
templates and usages of `wasm-pack`.
[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html
[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html
## 🚴 Usage
### 🐑 Use `cargo generate` to Clone this Template
[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate)
```
cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project
cd my-project
```
### 🛠️ Build with `wasm-pack build`
```
wasm-pack build
```
### 🔬 Test in Headless Browsers with `wasm-pack test`
```
wasm-pack test --headless --firefox
```
### 🎁 Publish to NPM with `wasm-pack publish`
```
wasm-pack publish
```
## 🔋 Batteries Included
- [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating
between WebAssembly and JavaScript.
- [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook)
for logging panic messages to the developer console.
- [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized
for small code size.

41
vendor/pow/mcaptcha_browser.d.ts vendored Normal file
View file

@ -0,0 +1,41 @@
/* tslint:disable */
/* eslint-disable */
/**
* generate proof-of-work
* ```rust
* fn main() {
* use mcaptcha_browser::*;
* use pow_sha256::*;
*
*
* // salt using which PoW should be computed
* const SALT: &str = "yrandomsaltisnotlongenoug";
* // one-time phrase over which PoW should be computed
* const PHRASE: &str = "ironmansucks";
* // and the difficulty factor
* const DIFFICULTY: u32 = 1000;
*
* // currently gen_pow() returns a JSON formated string to better communicate
* // with JavaScript. See [PoW<T>][pow_sha256::PoW] for schema
* let serialised_work = gen_pow(SALT.into(), PHRASE.into(), DIFFICULTY);
*
*
* let work: Work = serde_json::from_str(&serialised_work).unwrap();
*
* let work = PoWBuilder::default()
* .result(work.result)
* .nonce(work.nonce)
* .build()
* .unwrap();
*
* let config = ConfigBuilder::default().salt(SALT.into()).build().unwrap();
* assert!(config.is_valid_proof(&work, &PHRASE.to_string()));
* assert!(config.is_sufficient_difficulty(&work, DIFFICULTY));
* }
* ```
* @param {string} salt
* @param {string} phrase
* @param {number} difficulty_factor
* @returns {string}
*/
export function gen_pow(salt: string, phrase: string, difficulty_factor: number): string;

2
vendor/pow/mcaptcha_browser.js vendored Normal file
View file

@ -0,0 +1,2 @@
import * as wasm from "./mcaptcha_browser_bg.wasm";
export * from "./mcaptcha_browser_bg.js";

139
vendor/pow/mcaptcha_browser_bg.js vendored Normal file
View file

@ -0,0 +1,139 @@
import * as wasm from './mcaptcha_browser_bg.wasm';
let WASM_VECTOR_LEN = 0;
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
const lTextEncoder = typeof TextEncoder === 'undefined' ? (0, module.require)('util').TextEncoder : TextEncoder;
let cachedTextEncoder = new lTextEncoder('utf-8');
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length);
getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;
let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
/**
* generate proof-of-work
* ```rust
* fn main() {
* use mcaptcha_browser::*;
* use pow_sha256::*;
*
*
* // salt using which PoW should be computed
* const SALT: &str = "yrandomsaltisnotlongenoug";
* // one-time phrase over which PoW should be computed
* const PHRASE: &str = "ironmansucks";
* // and the difficulty factor
* const DIFFICULTY: u32 = 1000;
*
* // currently gen_pow() returns a JSON formated string to better communicate
* // with JavaScript. See [PoW<T>][pow_sha256::PoW] for schema
* let serialised_work = gen_pow(SALT.into(), PHRASE.into(), DIFFICULTY);
*
*
* let work: Work = serde_json::from_str(&serialised_work).unwrap();
*
* let work = PoWBuilder::default()
* .result(work.result)
* .nonce(work.nonce)
* .build()
* .unwrap();
*
* let config = ConfigBuilder::default().salt(SALT.into()).build().unwrap();
* assert!(config.is_valid_proof(&work, &PHRASE.to_string()));
* assert!(config.is_sufficient_difficulty(&work, DIFFICULTY));
* }
* ```
* @param {string} salt
* @param {string} phrase
* @param {number} difficulty_factor
* @returns {string}
*/
export function gen_pow(salt, phrase, difficulty_factor) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passStringToWasm0(salt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
var ptr1 = passStringToWasm0(phrase, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
wasm.gen_pow(retptr, ptr0, len0, ptr1, len1, difficulty_factor);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(r0, r1);
}
}

BIN
vendor/pow/mcaptcha_browser_bg.wasm vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,8 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export function gen_pow(a: number, b: number, c: number, d: number, e: number, f: number): void;
export function __wbindgen_add_to_stack_pointer(a: number): number;
export function __wbindgen_malloc(a: number): number;
export function __wbindgen_realloc(a: number, b: number, c: number): number;
export function __wbindgen_free(a: number, b: number): void;

24
vendor/pow/package.json vendored Normal file
View file

@ -0,0 +1,24 @@
{
"name": "mcaptcha-browser",
"collaborators": [
"realaravinth <realaravinth@batsense.net>"
],
"description": "mCaptcha client library for the web",
"version": "0.1.0",
"license": "MIT OR Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/mCaptcha/browser"
},
"files": [
"mcaptcha_browser_bg.wasm",
"mcaptcha_browser.js",
"mcaptcha_browser_bg.js",
"mcaptcha_browser.d.ts",
"LICENSE_APACHE",
"LICENSE_MIT"
],
"module": "mcaptcha_browser.js",
"types": "mcaptcha_browser.d.ts",
"sideEffects": false
}

38
webpack.config.js Normal file
View file

@ -0,0 +1,38 @@
'use strict';
const path = require('path');
//const WasmPackPlugin = require('@wasm-tool/wasm-pack-plugin');
module.exports = {
devtool: 'inline-source-map',
mode: 'development',
//mode: 'production',
entry: {
bundle: './templates/index.ts',
bench: './templates/bench.ts',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './static/cache/bundle'),
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
},
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
experiments: {
// executeModule: true,
// outputModule: true,
//syncWebAssembly: true,
// topLevelAwait: true,
asyncWebAssembly: true,
// layers: true,
// lazyCompilation: true,
},
};

5639
yarn.lock Normal file

File diff suppressed because it is too large Load diff