-
Notifications
You must be signed in to change notification settings - Fork 15
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
fabricedesre
wants to merge
3
commits into
ucan-wg:main
Choose a base branch
from
capyloon:wasm-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
static/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>> { | ||
|
@@ -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 | ||
|
@@ -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(); | ||
|
||
|
@@ -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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💖 |
||
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() | ||
} | ||
} | ||
|
||
|
@@ -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( | ||
|
@@ -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(); | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎉