💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Generate typed Contacts WASM outputs
Manav Rathi0a9e6a260964
diff --git a/mobile/packages/sharing/lib/extensions/user_extension.dart b/mobile/packages/sharing/lib/extensions/user_extension.dartindex ec4bed45b4..f1b10c5758 100644--- a/mobile/packages/sharing/lib/extensions/user_extension.dart+++ b/mobile/packages/sharing/lib/extensions/user_extension.dart@@ -25,7 +25,7 @@ ResolvedUserIdentity resolveUserIdentity(int? userID, String email) {);final resolvedEmail = _trimToNull(contact?.email) ?? email;return (- displayName: _trimToNull(contact?.data?.name) ?? resolvedEmail,+ displayName: _trimToNull(contact?.name) ?? resolvedEmail,email: resolvedEmail,);}diff --git a/mobile/packages/sharing/test/user_avator_widget_test.dart b/mobile/packages/sharing/test/user_avator_widget_test.dartindex d7d6cbb6b8..344e853fdb 100644--- a/mobile/packages/sharing/test/user_avator_widget_test.dart+++ b/mobile/packages/sharing/test/user_avator_widget_test.dart@@ -29,7 +29,7 @@ void main() {id: 'ct_1',contactUserId: 7,email: '[email protected]',- data: ContactData(contactUserId: 7, name: 'Alice'),+ name: 'Alice',profilePictureAttachmentId: 'att_1',isDeleted: false,createdAt: 1,@@ -78,7 +78,7 @@ void main() {id: 'ct_1',contactUserId: 7,email: '[email protected]',- data: ContactData(contactUserId: 7, name: 'Alice'),+ name: 'Alice',profilePictureAttachmentId: null,isDeleted: false,createdAt: 1,diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 362f000ca3..b9b8d6d7bb 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2854,6 +2854,7 @@ dependencies = ["serde","serde-wasm-bindgen","thiserror 2.0.18",+ "tsify","wasm-bindgen","wasm-bindgen-futures",]@@ -9937,6 +9938,30 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "tsify"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea3af6b48c5c5624f7eb3c2f578d1335fadac433321980cae0063e8eb0acaa44"+dependencies = [+ "serde",+ "serde-wasm-bindgen",+ "tsify-macros",+ "wasm-bindgen",+]++[[package]]+name = "tsify-macros"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef1e2e93369379d0a527c7d6632b58c55d52db7a106d8afbde3b354f3a57a9f1"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.117",+]+[[package]]name = "ttf-parser"version = "0.25.1"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 190f843138..d87ecee7db 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -75,6 +75,7 @@ serde_json = "1.0.149"serde-wasm-bindgen = "0.6.5"sha2 = "0.11.0"thiserror = "2.0.18"+tsify = { version = "0.5.8", default-features = false, features = ["js"] }uniffi = { version = "=0.31.0" }uniffi_bindgen = { version = "=0.31.0", default-features = false, features = ["cargo-metadata"] }url = "2.5.8"diff --git a/rust/bindings/wasm/lib/Cargo.toml b/rust/bindings/wasm/lib/Cargo.tomlindex ddefe87a5d..28d0217b48 100644--- a/rust/bindings/wasm/lib/Cargo.toml+++ b/rust/bindings/wasm/lib/Cargo.toml@@ -7,6 +7,7 @@ contacts = ["dep:ente-contacts","dep:serde","dep:serde-wasm-bindgen",+ "dep:tsify","dep:wasm-bindgen-futures",]@@ -17,5 +18,6 @@ js-sys.workspace = trueserde = { workspace = true, optional = true }serde-wasm-bindgen = { workspace = true, optional = true }thiserror.workspace = true+tsify = { workspace = true, optional = true }wasm-bindgen.workspace = truewasm-bindgen-futures = { workspace = true, optional = true }diff --git a/rust/bindings/wasm/lib/src/contacts.rs b/rust/bindings/wasm/lib/src/contacts.rsindex b70b9ae721..b21bae257d 100644--- a/rust/bindings/wasm/lib/src/contacts.rs+++ b/rust/bindings/wasm/lib/src/contacts.rs@@ -1,6 +1,6 @@-use ente_contacts::WrappedRootContactKey;use serde::{Serialize, Serializer};use serde_wasm_bindgen as swb;+use tsify::Tsify;use wasm_bindgen::prelude::*;use crate::session::Session;@@ -33,9 +33,9 @@ impl From<Error> for JsValue {}}-#[derive(Serialize)]+#[derive(Serialize, Tsify)]#[serde(rename_all = "camelCase")]-struct ContactRecordJs {+struct ContactRecord {id: String,contact_user_id: i64,email: Option<String>,@@ -46,7 +46,7 @@ struct ContactRecordJs {updated_at: i64,}-impl From<ente_contacts::ContactRecord> for ContactRecordJs {+impl From<ente_contacts::ContactRecord> for ContactRecord {fn from(value: ente_contacts::ContactRecord) -> Self {Self {id: value.id,@@ -60,21 +60,38 @@ impl From<ente_contacts::ContactRecord> for ContactRecordJs {}}-#[derive(Serialize)]+#[derive(Serialize, Tsify)]#[serde(rename_all = "camelCase")]-struct ContactsDiffJs {- records: Vec<ContactRecordJs>,+pub struct ContactsDiffOutput {+ records: Vec<ContactRecord>,wrapped_root_contact_key: Option<WrappedRootContactKey>,}-#[derive(Serialize)]+#[derive(Serialize, Tsify)]#[serde(rename_all = "camelCase")]-struct ProfilePictureJs {+pub struct ProfilePictureOutput {#[serde(serialize_with = "serialize_bytes")]+ #[tsify(type = "Uint8Array")]bytes: Vec<u8>,wrapped_root_contact_key: Option<WrappedRootContactKey>,}+#[derive(Serialize, Tsify)]+#[serde(rename_all = "camelCase")]+struct WrappedRootContactKey {+ encrypted_key: String,+ header: String,+}++impl From<ente_contacts::WrappedRootContactKey> for WrappedRootContactKey {+ fn from(value: ente_contacts::WrappedRootContactKey) -> Self {+ Self {+ encrypted_key: value.encrypted_key,+ header: value.header,+ }+ }+}+#[wasm_bindgen(js_name = contactsGetDiff)]pub async fn contacts_get_diff(session: &Session,@@ -82,15 +99,15 @@ pub async fn contacts_get_diff(cached_header: Option<String>,since_time: i64,limit: u16,-) -> Result<JsValue, Error> {+) -> Result<<ContactsDiffOutput as Tsify>::JsType, Error> {let cached = wrapped_root_contact_key(cached_encrypted_key, cached_header);let output =ente_contacts::get_diff(session.inner(), cached.as_ref(), since_time, limit).await?;- let output = ContactsDiffJs {+ let output = ContactsDiffOutput {records: output.value.into_iter().map(Into::into).collect(),- wrapped_root_contact_key: output.wrapped_root_contact_key,+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),};- swb::to_value(&output).map_err(Into::into)+ output.into_js().map_err(Into::into)}#[wasm_bindgen(js_name = contactsGetProfilePicture)]@@ -99,27 +116,28 @@ pub async fn contacts_get_profile_picture(cached_encrypted_key: Option<String>,cached_header: Option<String>,contact_id: &str,-) -> Result<JsValue, Error> {+) -> Result<<ProfilePictureOutput as Tsify>::JsType, Error> {let cached = wrapped_root_contact_key(cached_encrypted_key, cached_header);let output =ente_contacts::get_profile_picture(session.inner(), cached.as_ref(), contact_id).await?;- swb::to_value(&ProfilePictureJs {+ ProfilePictureOutput {bytes: output.value,- wrapped_root_contact_key: output.wrapped_root_contact_key,- })+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),+ }+ .into_js().map_err(Into::into)}fn wrapped_root_contact_key(encrypted_key: Option<String>,header: Option<String>,-) -> Option<WrappedRootContactKey> {- encrypted_key- .zip(header)- .map(|(encrypted_key, header)| WrappedRootContactKey {+) -> Option<ente_contacts::WrappedRootContactKey> {+ encrypted_key.zip(header).map(+ |(encrypted_key, header)| ente_contacts::WrappedRootContactKey {encrypted_key,header,- })+ },+ )}fn serialize_bytes<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>diff --git a/web/package-lock.json b/web/package-lock.jsonindex ef53c80b32..0650406fb9 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -11262,6 +11262,10 @@"devDependencies": {"@types/react": "19.2.17","ente-build-config": "*",+ "ente-core-wasm": "*",+ "ente-locker-wasm": "*",+ "ente-photos-wasm": "*",+ "vite-plugin-wasm": "3.6.0","vitest": "4.1.8"}},diff --git a/web/packages/contacts/package.json b/web/packages/contacts/package.jsonindex 54b5870104..a2cd38801d 100644--- a/web/packages/contacts/package.json+++ b/web/packages/contacts/package.json@@ -19,6 +19,10 @@"devDependencies": {"@types/react": "19.2.17","ente-build-config": "*",+ "ente-core-wasm": "*",+ "ente-locker-wasm": "*",+ "ente-photos-wasm": "*",+ "vite-plugin-wasm": "3.6.0","vitest": "4.1.8"}}diff --git a/web/packages/contacts/vitest.config.ts b/web/packages/contacts/vitest.config.tsnew file mode 100644index 0000000000..0b2f1a1c24--- /dev/null+++ b/web/packages/contacts/vitest.config.ts@@ -0,0 +1,5 @@+import type { PluginOption } from "vite";+import wasm from "vite-plugin-wasm";+import { defineConfig } from "vitest/config";++export default defineConfig({ plugins: [wasm() as PluginOption] });diff --git a/web/packages/contacts/wasm.test.ts b/web/packages/contacts/wasm.test.tsnew file mode 100644index 0000000000..d12d97dc7e--- /dev/null+++ b/web/packages/contacts/wasm.test.ts@@ -0,0 +1,195 @@+import {+ crypto_encrypt_blob,+ crypto_encrypt_box,+ crypto_generate_key,+} from "ente-core-wasm";+import * as locker from "ente-locker-wasm";+import * as photos from "ente-photos-wasm";+import { afterEach, describe, expect, test, vi } from "vitest";++afterEach(() => vi.unstubAllGlobals());++for (const [name, api] of [+ ["Photos", photos],+ ["Locker", locker],+] as const) {+ describe(name, () => {+ test("returns decrypted contacts and picture bytes as plain values", async () => {+ const fixture = encryptedContact();+ mockFetch((request) => {+ switch (new URL(request.url).pathname) {+ case "/contacts/diff":+ return Response.json({+ diff: Array.from({ length: 1000 }, (_, i) => ({+ ...fixture.contact,+ id: `ct_${i}`,+ })),+ });+ case "/contacts/ct_test":+ return Response.json(fixture.contact);+ case "/attachments/profile_picture/att_test":+ return Response.json({+ url: "http://localhost/picture",+ });+ case "/picture":+ return new Response(fixture.encryptedPicture);+ default:+ throw new Error(`Unexpected request: ${request.url}`);+ }+ });++ const session = await api.openSession({+ baseUrl: "http://localhost",+ authToken: "test-token",+ masterKeyB64: fixture.masterKey,+ });+ try {+ const diff = await api.contactsGetDiff(+ session,+ fixture.wrappedRootContactKey,+ 0,+ 1000,+ );+ expect(diff).toStrictEqual({+ records: Array.from({ length: 1000 }, (_, i) => ({+ id: `ct_${i}`,+ contactUserId: 42,+ email: "[email protected]",+ name: "Zoë 🦋",+ profilePictureAttachmentID: "att_test",+ isDeleted: false,+ updatedAt: 1725000000000000,+ })),+ wrappedRootContactKey: fixture.wrappedRootContactKey,+ });++ const picture = await api.contactsGetProfilePicture(+ session,+ fixture.wrappedRootContactKey,+ "ct_test",+ );+ expect(picture.bytes).toBeInstanceOf(Uint8Array);+ expect(picture).toStrictEqual({+ bytes: fixture.picture,+ wrappedRootContactKey: fixture.wrappedRootContactKey,+ });+ } finally {+ session.free();+ }+ });++ test("preserves tombstone optionals and rejects failures as Errors", async () => {+ const contact = {+ id: "ct_deleted",+ contactUserID: 42,+ isDeleted: true,+ createdAt: 100,+ updatedAt: 200,+ };+ mockFetch(() => Response.json({ diff: [contact] }));++ const session = await api.openSession({+ baseUrl: "http://localhost",+ authToken: "test-token",+ masterKeyB64: crypto_generate_key(),+ });+ try {+ expect(+ await api.contactsGetDiff(session, undefined, 0, 1000),+ ).toStrictEqual({+ records: [+ {+ id: "ct_deleted",+ contactUserId: 42,+ email: undefined,+ name: undefined,+ profilePictureAttachmentID: undefined,+ isDeleted: true,+ updatedAt: 200,+ },+ ],+ wrappedRootContactKey: undefined,+ });++ contact.updatedAt = Number.MAX_SAFE_INTEGER + 1;+ await expect(+ api.contactsGetDiff(session, undefined, 0, 1000),+ ).rejects.toBeInstanceOf(Error);++ mockFetch(() => new Response(null, { status: 500 }));+ await expect(+ api.contactsGetDiff(session, undefined, 0, 1000),+ ).rejects.toBeInstanceOf(Error);+ } finally {+ session.free();+ }+ });+ });+}++const mockFetch = (respond: (request: Request) => Response) =>+ vi.stubGlobal("fetch", (request: Request) => {+ const response = respond(request);+ // reqwest reads the response URL, which constructed Responses omit.+ Object.defineProperty(response, "url", { value: request.url });+ return Promise.resolve(response);+ });++const encryptedContact = () => {+ const masterKey = crypto_generate_key();+ const rootKey = crypto_generate_key();+ const contactKey = crypto_generate_key();+ const wrappedRootKey = crypto_encrypt_box(rootKey, masterKey);+ const wrappedContactKey = crypto_encrypt_box(contactKey, rootKey);+ const data = crypto_encrypt_blob(+ Buffer.from(+ JSON.stringify({ contactUserId: 42, name: "Zoë 🦋" }),+ ).toString("base64"),+ contactKey,+ );+ const picture = Uint8Array.from({ length: 4096 }, (_, i) => i % 256);+ const encryptedPicture = crypto_encrypt_blob(+ Buffer.from(picture).toString("base64"),+ contactKey,+ );+ const fixture = {+ masterKey,+ wrappedRootContactKey: {+ encryptedKey: wrappedRootKey.encrypted_data,+ header: wrappedRootKey.nonce,+ },+ contact: {+ id: "ct_test",+ contactUserID: 42,+ email: "[email protected]",+ profilePictureAttachmentID: "att_test",+ encryptedKey: combined(+ wrappedContactKey.nonce,+ wrappedContactKey.encrypted_data,+ ).toString("base64"),+ encryptedData: combined(+ data.decryption_header,+ data.encrypted_data,+ ).toString("base64"),+ isDeleted: false,+ createdAt: 100,+ updatedAt: 1725000000000000,+ },+ picture,+ encryptedPicture: combined(+ encryptedPicture.decryption_header,+ encryptedPicture.encrypted_data,+ ),+ };+ wrappedRootKey.free();+ wrappedContactKey.free();+ data.free();+ encryptedPicture.free();+ return fixture;+};++const combined = (header: string, ciphertext: string) =>+ Buffer.concat([+ Buffer.from(header, "base64"),+ Buffer.from(ciphertext, "base64"),+ ]);diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.tsindex 666245655f..b109905b5e 100644--- a/web/packages/wasm/locker/index.ts+++ b/web/packages/wasm/locker/index.ts@@ -1,7 +1,4 @@-interface WrappedRootContactKey {- encryptedKey: string;- header: string;-}+import type { WrappedRootContactKey } from "./pkg/ente_locker_wasm";interface OpenSessionInput {baseUrl: string;@@ -11,26 +8,6 @@ interface OpenSessionInput {clientVersion?: string;}-interface ContactRecord {- id: string;- contactUserId: number;- email?: string;- name?: string;- profilePictureAttachmentID?: string;- isDeleted: boolean;- updatedAt: number;-}--interface ContactsDiffOutput {- records: ContactRecord[];- wrappedRootContactKey?: WrappedRootContactKey;-}--interface ProfilePictureOutput {- bytes: Uint8Array;- wrappedRootContactKey?: WrappedRootContactKey;-}-const wasm = () => import("./pkg/ente_locker_wasm");export type Session = import("./pkg/ente_locker_wasm").Session;@@ -55,7 +32,7 @@ export const contactsGetDiff = async (wrappedRootContactKey: WrappedRootContactKey | undefined,sinceTime: number,limit: number,-): Promise<ContactsDiffOutput> =>+) =>(await wasm()).contactsGetDiff(session,wrappedRootContactKey?.encryptedKey,@@ -68,7 +45,7 @@ export const contactsGetProfilePicture = async (session: Session,wrappedRootContactKey: WrappedRootContactKey | undefined,contactID: string,-): Promise<ProfilePictureOutput> =>+) =>(await wasm()).contactsGetProfilePicture(session,wrappedRootContactKey?.encryptedKey,diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.tsindex 4cc6843bf0..cef4de7950 100644--- a/web/packages/wasm/photos/index.ts+++ b/web/packages/wasm/photos/index.ts@@ -1,7 +1,4 @@-interface WrappedRootContactKey {- encryptedKey: string;- header: string;-}+import type { WrappedRootContactKey } from "./pkg/ente_photos_wasm";interface OpenSessionInput {baseUrl: string;@@ -11,26 +8,6 @@ interface OpenSessionInput {clientVersion?: string;}-interface ContactRecord {- id: string;- contactUserId: number;- email?: string;- name?: string;- profilePictureAttachmentID?: string;- isDeleted: boolean;- updatedAt: number;-}--interface ContactsDiffOutput {- records: ContactRecord[];- wrappedRootContactKey?: WrappedRootContactKey;-}--interface ProfilePictureOutput {- bytes: Uint8Array;- wrappedRootContactKey?: WrappedRootContactKey;-}-const wasm = () => import("./pkg/ente_photos_wasm");export type Session = import("./pkg/ente_photos_wasm").Session;@@ -55,7 +32,7 @@ export const contactsGetDiff = async (wrappedRootContactKey: WrappedRootContactKey | undefined,sinceTime: number,limit: number,-): Promise<ContactsDiffOutput> =>+) =>(await wasm()).contactsGetDiff(session,wrappedRootContactKey?.encryptedKey,@@ -68,7 +45,7 @@ export const contactsGetProfilePicture = async (session: Session,wrappedRootContactKey: WrappedRootContactKey | undefined,contactID: string,-): Promise<ProfilePictureOutput> =>+) =>(await wasm()).contactsGetProfilePicture(session,wrappedRootContactKey?.encryptedKey,