Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
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
2 changes: 1 addition & 1 deletion .github/workflows/web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ jobs:
done

- name: Upload package
if: steps.version.outputs.version
if: steps.version.outputs.version || github.event_name == 'workflow_dispatch'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: walletkit-web-package
Expand Down
66 changes: 66 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/walletkit-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ wasm-bindgen = "=0.2.126"
wasm-bindgen-futures = "0.4.76"
walletkit-core = { workspace = true, features = ["embed-zkeys"] }
zeroize = { workspace = true }
selfie-enrollment-client = { git = "https://github.com/worldcoin/biometrics-tee", rev = "72de61bf4a62522ca3d0dd66dc920820fb6291e9", default-features = false }
selfie-enrollment-sealed-types = { git = "https://github.com/worldcoin/biometrics-tee", rev = "72de61bf4a62522ca3d0dd66dc920820fb6291e9" }
Comment thread
Copilot marked this conversation as resolved.
Outdated
serde_json.workspace = true

[lints]
workspace = true
82 changes: 82 additions & 0 deletions crates/walletkit-web/src/enrollment.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! Embedding enrollment over the dedicated browser-compatible TEE channel.
use js_sys::Promise;
use selfie_enrollment_client::{Config, Error};
use selfie_enrollment_sealed_types::{EmbeddingResult, Failure};
use wasm_bindgen::prelude::*;
use zeroize::Zeroizing;

use crate::{error::to_js, js};

#[wasm_bindgen(typescript_custom_section)]
const TS_TYPES: &str = r#"
export type SelfieEmbeddingResult =
| { status: "success"; embedding: FaceEmbedding }
| { status: "failed"; reason: "invalid_image" | "quality_rejected" | "extraction_failed" | "invalid_request" };

export interface FaceEmbedding {
embedding: string;
embeddingType: string;
embeddingVersion: string;
embeddingInferenceBackend: string;
}
"#;

/// Extracts an embedding after verifying Nitro measurements.
///
/// `configJson` is the trusted release policy from the enrollment deployment.
/// The image is sealed inside this worker before upload and is never persisted.
///
/// Calls have a bounded deadline. Terminate the `WalletKit` instance to cancel an
/// in-flight enrollment immediately. This operation does not issue a credential.
///
/// # Errors
/// Throws a `SelfieEnrollmentError` for invalid policy, rejected attestation, or
/// transport failures. Image/quality rejections return a typed failed result.
#[wasm_bindgen(js_name = extractSelfieEmbedding, unchecked_return_type = "Promise<SelfieEmbeddingResult>")]
pub fn extract_selfie_embedding(config_json: String, image: Vec<u8>) -> Promise {
let mut image = Zeroizing::new(image);
js::promise(async move {
let config: Config =
serde_json::from_str(&config_json).map_err(|_| to_js(Error::Config))?;
let result = selfie_enrollment_client::browser::extract(
config,
std::mem::take(&mut *image),
None,
)
.await
.map_err(to_js)?;
result_to_js(&result)
})
}

fn result_to_js(result: &EmbeddingResult) -> Result<JsValue, JsValue> {
match result {
EmbeddingResult::Success { embedding } => js::object(&[
("status", "success".into()),
(
"embedding",
js::object(&[
Comment thread
Copilot marked this conversation as resolved.
("embedding", embedding.embedding.as_str().into()),
("embeddingType", embedding.embedding_type.as_str().into()),
(
"embeddingVersion",
embedding.embedding_version.as_str().into(),
),
(
"embeddingInferenceBackend",
embedding.embedding_inference_backend.as_str().into(),
),
])?,
),
]),
EmbeddingResult::Failed { reason } => {
let reason = match reason {
Failure::InvalidImage => "invalid_image",
Failure::QualityRejected => "quality_rejected",
Failure::ExtractionFailed => "extraction_failed",
Failure::InvalidRequest => "invalid_request",
};
js::object(&[("status", "failed".into()), ("reason", reason.into())])
}
}
}
4 changes: 4 additions & 0 deletions crates/walletkit-web/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ impl JsReportable for WalletKitError {
const NAME: &'static str = "WalletKitError";
}

impl JsReportable for selfie_enrollment_client::Error {
const NAME: &'static str = "SelfieEnrollmentError";
}

impl JsReportable for StorageError {
const NAME: &'static str = "StorageError";
}
Expand Down
1 change: 1 addition & 0 deletions crates/walletkit-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#![cfg(all(target_arch = "wasm32", target_os = "unknown"))]

mod authenticator;
mod enrollment;
mod error;
mod js;
mod storage;
Expand Down
29 changes: 29 additions & 0 deletions web/walletkit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,35 @@ The browser API differs from the Swift and Kotlin bindings in these ways:
- Objects stay in the worker until you call `free()` or they are garbage
collected.

## Extract a Selfie Check embedding

```ts
const result = await wallet.extractSelfieEmbedding(
JSON.stringify(trustedEnrollmentRelease),
imageBytes,
);
if (result.status === "success") {
// Sensitive biometric data: keep it out of logs and persistent storage.
const embedding = result.embedding;
}
```

Use the trusted `client-stage.json` generated by the enrollment release in
`worldcoin/tee-apps`. It pins the endpoint, Nitro PCR0/1/2. The client verifies these before sealing the image. A failed
attestation never causes an image upload, and no bypass option is exposed.

The client requests and verifies an enclave assignment, then sends one sealed image
and receives one sealed result over the same WebSocket. Access control belongs to
the upstream proxy; this API has no ticket issuer or admission callback.

The response is `SelfieEmbeddingResult`: a success containing `FaceEmbedding`, or
a typed image/quality failure. `FaceEmbedding` follows the existing Face PCP
contract: `embedding` (the original encoded vector), `embeddingType`,
`embeddingVersion`, and `embeddingInferenceBackend`. This operation
extracts an embedding and does not issue a credential or prove camera liveness.
The experimental staging service connects directly to the TEE host. Proxy protection
is planned separately.

## Handle errors

WalletKit reports failures in these ways:
Expand Down
2 changes: 2 additions & 0 deletions web/walletkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export type {
RecoveryUpdateSignature,
Region,
RegistrationStatus,
FaceEmbedding,
SelfieEmbeddingResult,
} from "./generated/walletkit.js";

export interface InitializeOptions {
Expand Down
36 changes: 36 additions & 0 deletions web/walletkit/tests/browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,3 +588,39 @@ test("vault backups merge additively, reject invalid data, and survive reopening

expect(result.reopenedRecords).toEqual(result.mergedRecords);
});

test("enrollment rejects invalid policy without stopping the wallet worker", async ({
page,
}) => {
const result = await page.evaluate(async () => {
const wallet = await (window as any).initializeWalletKit();
try {
const policy = await wallet
.extractSelfieEmbedding("{}", new Uint8Array([1]))
.catch((error: Error & { code?: string }) => ({
name: error.name,
code: error.code,
}));
return { policy, stopped: wallet.isStopped() };
} finally {
await wallet.close();
}
});
expect(result.policy).toEqual({
name: "SelfieEnrollmentError",
code: "Config",
});
expect(result.stopped).toBe(false);
});

test("enrollment requests an assignment and withholds the image if attestation fails", async ({
page,
}) => {
const result = await page.evaluate(() =>
(window as any).enrollmentAssignment(),
);
expect(result.sent).toEqual(["assignment_request"]);
expect(result.code).toBe("Attestation");
expect(result.closed).toBe(true);
expect(result.alive).toBe("alive");
});
68 changes: 68 additions & 0 deletions web/walletkit/tests/fixture/enrollment.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import init, {
extractSelfieEmbedding,
sanitizeHexSecrets,
} from "../../src/generated/walletkit.js";

self.onmessage = async ({ data }) => {
try {
await init({ module_or_path: new URL(data.wasmUrl) });
const sent: string[] = [];
let closed = false;
Object.assign(self, {
WebSocket: class {
static OPEN = 1;
readyState = 1;
bufferedAmount = 0;
onopen?: (event: Event) => void;
onmessage?: (event: MessageEvent) => void;
constructor() {
setTimeout(() => this.onopen?.(new Event("open")), 0);
}
send(value: unknown) {
sent.push(
typeof value === "string" ? JSON.parse(value).type : "image",
);
setTimeout(
() =>
this.onmessage?.(
new MessageEvent("message", {
data: JSON.stringify({
type: "assignment",
attestation: "AQ==",
public_key: "Ag==",
}),
}),
),
0,
);
}
close() {
this.readyState = 3;
closed = true;
}
},
});
const config = {
endpoint: "wss://enrollment.invalid/v1/embeddings",
releases: [
{
pcr0: "1".repeat(96),
pcr1: "2".repeat(96),
pcr2: "3".repeat(96),

},
],
};
let code;
try {
await extractSelfieEmbedding(JSON.stringify(config), new Uint8Array([1]));
} catch (error) {
code = (error as Error & { code?: string }).code;
}
self.postMessage({
result: { code, sent, closed, alive: sanitizeHexSecrets("alive") },
});
} catch (error) {
self.postMessage({ error: String(error) });
}
};
29 changes: 29 additions & 0 deletions web/walletkit/tests/fixture/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,32 @@ Object.assign(window, {
});
},
});

Object.assign(window, {
enrollmentAssignment() {
const worker = new Worker(
new URL("./enrollment.worker.ts", import.meta.url),
{ type: "module" },
);
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
worker.terminate();
reject(new Error("Enrollment did not reject the untrusted assignment"));
}, 5000);
worker.onmessage = ({ data }) => {
clearTimeout(timeout);
worker.terminate();
data.error ? reject(new Error(data.error)) : resolve(data.result);
};
worker.onerror = (event) => {
clearTimeout(timeout);
worker.terminate();
reject(new Error(event.message));
};
worker.postMessage({
wasmUrl: new URL("../../src/generated/walletkit.wasm", import.meta.url)
.href,
});
});
},
});
Loading
Loading