Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: expose a JS api through WASM. #17

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ucan-key-support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ license = "Apache-2.0"
readme = "README.md"
version = "0.4.0-alpha.1"

[lib]
crate-type = ["cdylib", "rlib"]

[features]
default = []
web = ["wasm-bindgen", "wasm-bindgen-futures", "js-sys", "web-sys", "ucan/web", "getrandom/js"]
Expand Down Expand Up @@ -44,6 +47,7 @@ tokio = { version = "^1", features = ["macros", "rt"] }
wasm-bindgen = { version = "0.2", optional = true }
wasm-bindgen-futures = { version = "0.4", optional = true }
js-sys = { version = "0.3", optional = true }
wee_alloc = {version = "0.4"}

[target.'cfg(target_arch="wasm32")'.dependencies.web-sys]
version = "0.3"
Expand Down
1 change: 1 addition & 0 deletions ucan-key-support/demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
static/
8 changes: 8 additions & 0 deletions ucan-key-support/demo/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/bash

cargo build --release --target="wasm32-unknown-unknown" --features=web

wasm-bindgen \
--target web \
--out-dir static \
../../target/wasm32-unknown-unknown/release/ucan_key_support.wasm
63 changes: 63 additions & 0 deletions ucan-key-support/demo/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html>
<head>
<title>UCANs on the Web - Powered by rs-ucan</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<script type="module">
import {
WebCryptoRsaKeyMaterial,
default as ucanInit,
} from "../static/ucan_key_support.js";

function log_(msg, kind) {
let container = document.getElementById("log");
let node = document.createElement("div");
node.classList.add(kind);
node.textContent = msg;
container.append(node);
}

function log(msg) {
log_(msg, "log");
}

function error(msg) {
log_(msg, "error");
}

async function runTest() {
document.getElementById("log").innerHTML = "";
let keyMaterial = await WebCryptoRsaKeyMaterial.generate(2048);
let did = await keyMaterial.getDid();
log(`DID url: ${did}`);
log(`JWT algorithm: ${keyMaterial.jwtAlgorithm()}`);

let data = new TextEncoder().encode("Hello World!");
let signature = await keyMaterial.sign(data);
try {
await keyMaterial.verify(data, signature);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

log(`Signature successfully verified`);
} catch (e) {
error(`Signature verification failed: ${e}`);
}
}

document.addEventListener("DOMContentLoaded", async () => {
document
.getElementById("run-test")
.addEventListener("click", runTest);

await ucanInit();
});
</script>
<style>
div.error {
color: red;
}
</style>
</head>
<body>
<button id="run-test">Run Test</button>
<pre id="log"></pre>
</body>
</html>
4 changes: 4 additions & 0 deletions ucan-key-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@ extern crate log;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
pub mod web_crypto;

#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

pub mod ed25519;
pub mod rsa;
6 changes: 2 additions & 4 deletions ucan-key-support/src/rsa.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use anyhow::{anyhow, Result};
use async_trait::async_trait;

use rsa::{
Hash, PaddingScheme, PublicKey, RsaPrivateKey, RsaPublicKey,
};
use rsa::pkcs1::{DecodeRsaPublicKey, EncodeRsaPublicKey};
use rsa::pkcs1::der::{Document, Encodable};
use rsa::pkcs1::{DecodeRsaPublicKey, EncodeRsaPublicKey};
use rsa::{Hash, PaddingScheme, PublicKey, RsaPrivateKey, RsaPublicKey};

use sha2::{Digest, Sha256};
use ucan::crypto::KeyMaterial;
Expand Down
92 changes: 81 additions & 11 deletions ucan-key-support/src/web_crypto.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use crate::rsa::{RsaKeyMaterial, RSA_ALGORITHM};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use js_sys::{Array, ArrayBuffer, Boolean, Object, Reflect, Uint8Array};
use rsa::RsaPublicKey;
use rsa::pkcs1::DecodeRsaPublicKey;
use js_sys::{Array, ArrayBuffer, Boolean, Object, Promise, Reflect, Uint8Array};
use rsa::pkcs1::der::Encodable;
use rsa::pkcs1::DecodeRsaPublicKey;
use rsa::RsaPublicKey;
use ucan::crypto::KeyMaterial;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsError, JsValue};
use wasm_bindgen_futures::{future_to_promise, JsFuture};
use web_sys::{Crypto, CryptoKey, CryptoKeyPair, SubtleCrypto};

pub fn convert_spki_to_rsa_public_key(spki_bytes: &[u8]) -> Result<Vec<u8>> {
Expand All @@ -18,8 +19,30 @@ pub fn convert_spki_to_rsa_public_key(spki_bytes: &[u8]) -> Result<Vec<u8>> {
}

#[derive(Debug)]
pub struct WebCryptoRsaKeyMaterial(pub CryptoKey, pub Option<CryptoKey>);
pub struct WasmError(anyhow::Error);

impl From<WasmError> for JsValue {
fn from(err: WasmError) -> JsValue {
JsError::new(&format!("{:?}", err)).into()
}
}

impl From<anyhow::Error> for WasmError {
fn from(err: anyhow::Error) -> Self {
Self(err)
}
}

type WasmResult<T> = std::result::Result<T, WasmError>;

#[derive(Clone)]
#[wasm_bindgen]
pub struct WebCryptoRsaKeyMaterial {
public_key: CryptoKey,
private_key: Option<CryptoKey>,
}

#[wasm_bindgen]
impl WebCryptoRsaKeyMaterial {
fn get_subtle_crypto() -> Result<SubtleCrypto> {
// NOTE: Accessing either `Window` or `DedicatedWorkerGlobalScope` in
Expand All @@ -33,13 +56,14 @@ impl WebCryptoRsaKeyMaterial {
}

fn private_key(&self) -> Result<&CryptoKey> {
match &self.1 {
match &self.private_key {
Some(key) => Ok(key),
None => Err(anyhow!("No private key configured")),
}
}

pub async fn generate(key_size: Option<u32>) -> Result<WebCryptoRsaKeyMaterial> {
#[wasm_bindgen]
pub async fn generate(key_size: Option<u32>) -> WasmResult<WebCryptoRsaKeyMaterial> {
let subtle_crypto = Self::get_subtle_crypto()?;
let algorithm = Object::new();

Expand Down Expand Up @@ -98,7 +122,53 @@ impl WebCryptoRsaKeyMaterial {
.map_err(|error| anyhow!("{:?}", error))?,
);

Ok(WebCryptoRsaKeyMaterial(public_key, Some(private_key)))
Ok(WebCryptoRsaKeyMaterial {
public_key,
private_key: Some(private_key),
})
}

#[wasm_bindgen(js_name = "getDid")]
pub fn wasm_get_did(&self) -> WasmResult<Promise> {
let me = self.clone();

Ok(future_to_promise(async move {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💖 future_to_promise

let did = me.get_did().await.map_err(|err| WasmError::from(err))?;
Ok(JsValue::from_str(&did))
}))
}

#[wasm_bindgen(js_name = "sign")]
pub fn wasm_sign(&self, payload: &[u8]) -> WasmResult<Promise> {
let me = self.clone();
let payload = payload.to_vec();

Ok(future_to_promise(async move {
let res = me
.sign(&payload)
.await
.map_err(|err| WasmError::from(err))?;
Ok(JsValue::from(Uint8Array::from(res.as_slice())))
}))
}

#[wasm_bindgen(js_name = "verify")]
pub fn wasm_verify(&self, payload: &[u8], signature: &[u8]) -> WasmResult<Promise> {
let me = self.clone();
let payload = payload.to_vec();
let signature = signature.to_vec();

Ok(future_to_promise(async move {
me.verify(&payload, &signature)
.await
.map_err(|err| WasmError::from(err))?;
Ok(JsValue::UNDEFINED)
}))
}

#[wasm_bindgen(js_name = "jwtAlgorithm")]
pub fn wasm_jwt_algorithm(&self) -> String {
self.get_jwt_algorithm_name()
}
}

Expand All @@ -109,7 +179,7 @@ impl KeyMaterial for WebCryptoRsaKeyMaterial {
}

async fn get_did(&self) -> Result<String> {
let public_key = &self.0;
let public_key = &self.public_key;
let subtle_crypto = Self::get_subtle_crypto()?;

let public_key_bytes = Uint8Array::new(
Expand Down Expand Up @@ -168,7 +238,7 @@ impl KeyMaterial for WebCryptoRsaKeyMaterial {
}

async fn verify(&self, payload: &[u8], signature: &[u8]) -> Result<()> {
let key = &self.0;
let key = &self.public_key;
let subtle_crypto = Self::get_subtle_crypto()?;
let algorithm = Object::new();

Expand Down