diff options
Diffstat (limited to 'testing/xpcshell/odoh-wasm')
-rw-r--r-- | testing/xpcshell/odoh-wasm/Cargo.toml | 42 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/LICENSE_APACHE | 176 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/LICENSE_MIT | 25 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/README.md | 75 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/README.md | 69 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/odoh_wasm.d.ts | 16 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/odoh_wasm.js | 132 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm | bin | 0 -> 165175 bytes | |||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm.d.ts | 7 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/pkg/package.json | 15 | ||||
-rw-r--r-- | testing/xpcshell/odoh-wasm/src/lib.rs | 158 |
11 files changed, 715 insertions, 0 deletions
diff --git a/testing/xpcshell/odoh-wasm/Cargo.toml b/testing/xpcshell/odoh-wasm/Cargo.toml new file mode 100644 index 0000000000..f709e66139 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/Cargo.toml @@ -0,0 +1,42 @@ +[workspace] + +[package] +name = "odoh-wasm" +version = "0.1.0" +authors = ["Kershaw Chang <kershaw@mozilla.com>"] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["console_error_panic_hook"] + +[dependencies] +wasm-bindgen = "0.2.63" +odoh-rs = "=0.1.10" +hpke = "=0.5.0" +js-sys = "0.3" +hex = "0.4" +futures = "0.3.1" +rand = "=0.7" + +# The `console_error_panic_hook` crate provides better debugging of panics by +# logging them with `console.error`. This is great for development, but requires +# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for +# code size when deploying. +console_error_panic_hook = { version = "0.1.6", optional = true } + +# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size +# compared to the default allocator's ~10K. It is slower than the default +# allocator, however. +# +# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. +wee_alloc = { version = "0.4.5", optional = true } + +[dev-dependencies] +wasm-bindgen-test = "0.3.13" + +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = "s" diff --git a/testing/xpcshell/odoh-wasm/LICENSE_APACHE b/testing/xpcshell/odoh-wasm/LICENSE_APACHE new file mode 100644 index 0000000000..1b5ec8b78e --- /dev/null +++ b/testing/xpcshell/odoh-wasm/LICENSE_APACHE @@ -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 diff --git a/testing/xpcshell/odoh-wasm/LICENSE_MIT b/testing/xpcshell/odoh-wasm/LICENSE_MIT new file mode 100644 index 0000000000..681a58f76e --- /dev/null +++ b/testing/xpcshell/odoh-wasm/LICENSE_MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Kershaw Chang <kershaw@mozilla.com> + +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. diff --git a/testing/xpcshell/odoh-wasm/README.md b/testing/xpcshell/odoh-wasm/README.md new file mode 100644 index 0000000000..d3e413bfec --- /dev/null +++ b/testing/xpcshell/odoh-wasm/README.md @@ -0,0 +1,75 @@ +<div align="center"> + + <h1><code>wasm-pack-template</code></h1> + + <strong>A template for kick starting a Rust and WebAssembly project using <a href="https://github.com/rustwasm/wasm-pack">wasm-pack</a>.</strong> + + <p> + <a href="https://travis-ci.org/rustwasm/wasm-pack-template"><img src="https://img.shields.io/travis/rustwasm/wasm-pack-template.svg?style=flat-square" alt="Build Status" /></a> + </p> + + <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 +``` + +### 🛠️ Build a module that can be used for nodejs + +``` +wasm-pack build --target nodejs +``` + +### 🔬 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. diff --git a/testing/xpcshell/odoh-wasm/pkg/README.md b/testing/xpcshell/odoh-wasm/pkg/README.md new file mode 100644 index 0000000000..1e4617a6d2 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/README.md @@ -0,0 +1,69 @@ +<div align="center"> + + <h1><code>wasm-pack-template</code></h1> + + <strong>A template for kick starting a Rust and WebAssembly project using <a href="https://github.com/rustwasm/wasm-pack">wasm-pack</a>.</strong> + + <p> + <a href="https://travis-ci.org/rustwasm/wasm-pack-template"><img src="https://img.shields.io/travis/rustwasm/wasm-pack-template.svg?style=flat-square" alt="Build Status" /></a> + </p> + + <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. diff --git a/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.d.ts b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.d.ts new file mode 100644 index 0000000000..1f90ef6591 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.d.ts @@ -0,0 +1,16 @@ +/* tslint:disable */ +/* eslint-disable */ +/** +* @returns {Uint8Array} +*/ +export function get_odoh_config(): Uint8Array; +/** +* @param {Uint8Array} odoh_encrypted_query_msg +* @returns {Uint8Array} +*/ +export function decrypt_query(odoh_encrypted_query_msg: Uint8Array): Uint8Array; +/** +* @param {Uint8Array} response +* @returns {Uint8Array} +*/ +export function create_response(response: Uint8Array): Uint8Array; diff --git a/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.js b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.js new file mode 100644 index 0000000000..14b97d7436 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm.js @@ -0,0 +1,132 @@ +let imports = {}; +imports['__wbindgen_placeholder__'] = module.exports; +let wasm; +const { TextDecoder } = require(`util`); + +const heap = new Array(32).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { return heap[idx]; } + +let heap_next = heap.length; + +function dropObject(idx) { + if (idx < 36) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +let cachegetUint8Memory0 = null; +function getUint8Memory0() { + if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) { + cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachegetUint8Memory0; +} + +function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} +/** +* @returns {Uint8Array} +*/ +module.exports.get_odoh_config = function() { + var ret = wasm.get_odoh_config(); + return takeObject(ret); +}; + +let WASM_VECTOR_LEN = 0; + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1); + getUint8Memory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} +/** +* @param {Uint8Array} odoh_encrypted_query_msg +* @returns {Uint8Array} +*/ +module.exports.decrypt_query = function(odoh_encrypted_query_msg) { + var ptr0 = passArray8ToWasm0(odoh_encrypted_query_msg, wasm.__wbindgen_malloc); + var len0 = WASM_VECTOR_LEN; + var ret = wasm.decrypt_query(ptr0, len0); + return takeObject(ret); +}; + +/** +* @param {Uint8Array} response +* @returns {Uint8Array} +*/ +module.exports.create_response = function(response) { + var ptr0 = passArray8ToWasm0(response, wasm.__wbindgen_malloc); + var len0 = WASM_VECTOR_LEN; + var ret = wasm.create_response(ptr0, len0); + return takeObject(ret); +}; + +module.exports.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); +}; + +module.exports.__wbg_log_b3f203d9e6882397 = function(arg0, arg1) { + console.log(getStringFromWasm0(arg0, arg1)); +}; + +module.exports.__wbg_buffer_eb2155f17856c20b = function(arg0) { + var ret = getObject(arg0).buffer; + return addHeapObject(ret); +}; + +module.exports.__wbg_newwithbyteoffsetandlength_7d07f77c6d0d8e26 = function(arg0, arg1, arg2) { + var ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0); + return addHeapObject(ret); +}; + +module.exports.__wbg_new_ff8b26f7b2d7e2fb = function(arg0) { + var ret = new Uint8Array(getObject(arg0)); + return addHeapObject(ret); +}; + +module.exports.__wbg_newwithlength_a49b32b2030b93c3 = function(arg0) { + var ret = new Uint8Array(arg0 >>> 0); + return addHeapObject(ret); +}; + +module.exports.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); +}; + +module.exports.__wbindgen_memory = function() { + var ret = wasm.memory; + return addHeapObject(ret); +}; + +const path = require('path').join(__dirname, 'odoh_wasm_bg.wasm'); +const bytes = require('fs').readFileSync(path); + +const wasmModule = new WebAssembly.Module(bytes); +const wasmInstance = new WebAssembly.Instance(wasmModule, imports); +wasm = wasmInstance.exports; +module.exports.__wasm = wasm; + diff --git a/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm Binary files differnew file mode 100644 index 0000000000..ddca009ed4 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm diff --git a/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm.d.ts b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm.d.ts new file mode 100644 index 0000000000..e3a939f2e0 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/odoh_wasm_bg.wasm.d.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export function get_odoh_config(): number; +export function decrypt_query(a: number, b: number): number; +export function create_response(a: number, b: number): number; +export function __wbindgen_malloc(a: number): number; diff --git a/testing/xpcshell/odoh-wasm/pkg/package.json b/testing/xpcshell/odoh-wasm/pkg/package.json new file mode 100644 index 0000000000..e6db000676 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/pkg/package.json @@ -0,0 +1,15 @@ +{ + "name": "odoh-wasm", + "collaborators": [ + "Kershaw Chang <kershaw@mozilla.com>" + ], + "version": "0.1.0", + "files": [ + "odoh_wasm_bg.wasm", + "odoh_wasm.js", + "odoh_wasm_bg.js", + "odoh_wasm.d.ts" + ], + "main": "odoh_wasm.js", + "types": "odoh_wasm.d.ts" +}
\ No newline at end of file diff --git a/testing/xpcshell/odoh-wasm/src/lib.rs b/testing/xpcshell/odoh-wasm/src/lib.rs new file mode 100644 index 0000000000..8f94d2b567 --- /dev/null +++ b/testing/xpcshell/odoh-wasm/src/lib.rs @@ -0,0 +1,158 @@ +use hpke::{ + kem::X25519HkdfSha256, + Kem as KemTrait, Serializable, +}; + +use odoh_rs::protocol::{ + create_response_msg, parse_received_query, + ObliviousDoHConfigContents, ObliviousDoHKeyPair, + ObliviousDoHQueryBody, +}; + +use futures::executor; +use hex; +use wasm_bindgen::prelude::*; + +pub type Kem = X25519HkdfSha256; + +// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global +// allocator. +#[cfg(feature = "wee_alloc")] +#[global_allocator] +static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; + +pub const ODOH_VERSION: u16 = 0x0001; +const KEM_ID: u16 = 0x0020; +const KDF_ID: u16 = 0x0001; +const AEAD_ID: u16 = 0x0001; + +// random bytes, should be 32 bytes for X25519 keys +pub const IKM: &str = "871389a8727130974e3eb3ee528d440a871389a8727130974e3eb3ee528d440a"; + +#[wasm_bindgen] +extern "C" { + // Use `js_namespace` here to bind `console.log(..)` instead of just + // `log(..)` + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); + + // The `console.log` is quite polymorphic, so we can bind it with multiple + // signatures. Note that we need to use `js_name` to ensure we always call + // `log` in JS. + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn log_u32(a: u32); + + // Multiple arguments too! + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn log_many(a: &str, b: &str); +} + +macro_rules! console_log { + // Note that this is using the `log` function imported above during + // `bare_bones` + ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) +} + +fn generate_key_pair() -> ObliviousDoHKeyPair { + let ikm_bytes = hex::decode(IKM).unwrap(); + let (secret_key, public_key) = Kem::derive_keypair(&ikm_bytes); + let public_key_bytes = public_key.to_bytes().to_vec(); + let odoh_public_key = ObliviousDoHConfigContents { + kem_id: KEM_ID, + kdf_id: KDF_ID, + aead_id: AEAD_ID, + public_key: public_key_bytes, + }; + ObliviousDoHKeyPair { + private_key: secret_key, + public_key: odoh_public_key, + } +} + +#[wasm_bindgen] +pub fn get_odoh_config() -> js_sys::Uint8Array { + let key_pair = generate_key_pair(); + let public_key_bytes = key_pair.public_key.public_key; + let length_bytes = (public_key_bytes.len() as u16).to_be_bytes(); + let odoh_config_length = 12 + public_key_bytes.len(); + let version = ODOH_VERSION; + let odoh_contents_length = 8 + public_key_bytes.len(); + let kem_id = KEM_ID; // DHKEM(X25519, HKDF-SHA256) + let kdf_id = KDF_ID; // KDF(SHA-256) + let aead_id = AEAD_ID; // AEAD(AES-GCM-128) + let mut result = vec![]; + result.extend(&((odoh_config_length as u16).to_be_bytes())); + result.extend(&((version as u16).to_be_bytes())); + result.extend(&((odoh_contents_length as u16).to_be_bytes())); + result.extend(&((kem_id as u16).to_be_bytes())); + result.extend(&((kdf_id as u16).to_be_bytes())); + result.extend(&((aead_id as u16).to_be_bytes())); + result.extend(&length_bytes); + result.extend(&public_key_bytes); + return js_sys::Uint8Array::from(&result[..]); +} + +static mut QUERY_BODY: Option<ObliviousDoHQueryBody> = None; +static mut SERVER_SECRET: Option<Vec<u8>> = None; + +#[wasm_bindgen] +pub fn decrypt_query( + odoh_encrypted_query_msg: &[u8], +) -> js_sys::Uint8Array { + let mut result = vec![]; + unsafe { + let key_pair = generate_key_pair(); + let parsed_res = + executor::block_on(parse_received_query(&key_pair, &odoh_encrypted_query_msg)); + let (parsed_query, secret) = match parsed_res { + Ok(t) => (t.0, t.1), + Err(_) => { + console_log!("parse_received_query failed!"); + return js_sys::Uint8Array::new_with_length(0) + }, + }; + + result.extend(&parsed_query.dns_msg); + + QUERY_BODY = Some(parsed_query); + SERVER_SECRET = Some(secret); + } + + return js_sys::Uint8Array::from(&result[..]); +} + +#[wasm_bindgen] +pub fn create_response( + response: &[u8], +) -> js_sys::Uint8Array { + unsafe { + if let Some(body) = &QUERY_BODY { + if let Some(secret) = &SERVER_SECRET { + // random bytes + let nonce = vec![0x1b, 0xff, 0xfd, 0xff, 0x1a, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xe]; + let result = executor::block_on(create_response_msg( + &secret, + &response, + None, + Some(nonce), + &body, + )); + let generated_response = match result { + Ok(r) => r, + Err(_) => { + console_log!("create_response_msg failed!"); + return js_sys::Uint8Array::new_with_length(0); + } + }; + + QUERY_BODY = None; + SERVER_SECRET = None; + return js_sys::Uint8Array::from(&generated_response[..]); + } + } + } + + console_log!("create_response_msg failed!"); + return js_sys::Uint8Array::new_with_length(0); +} |