Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Generate typed Legacy recovery bindings

Manav Rathi93cae0ed76c8
diff --git a/rust/bindings/wasm/legacy/src/lib.rs b/rust/bindings/wasm/legacy/src/lib.rs
index dae3cf5561..8a76daef12 100644
--- a/rust/bindings/wasm/legacy/src/lib.rs
+++ b/rust/bindings/wasm/legacy/src/lib.rs
@@ -1,12 +1,13 @@
mod types;
use ente_core::b64;
-use ente_legacy::{LegacyKitRecoveryClient, LegacyKitShare};
+use ente_legacy::LegacyKitRecoveryClient;
use ente_wasm_lib::session::Session;
-use serde::Deserialize;
use serde_wasm_bindgen as swb;
use tsify::Tsify;
-use types::{KeyAttributes, LegacyContactState, LegacyInfo};
+use types::{
+ KeyAttributes, LegacyContactState, LegacyInfo, LegacyKitRecoverySession, OpenKitRecoveryInput,
+};
use wasm_bindgen::prelude::*;
use ente_wasm_log as _;
@@ -166,27 +167,20 @@ pub async fn legacy_change_password(
.map_err(Into::into)
}
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct OpenLegacyKitRecoveryInput {
- base_url: String,
- shares: Vec<LegacyKitShare>,
- email: Option<String>,
- client_package: Option<String>,
- client_version: Option<String>,
-}
-
-#[wasm_bindgen]
-pub async fn legacy_kit_open_recovery(input: JsValue) -> Result<LegacyKitRecoveryHandle, Error> {
- let input: OpenLegacyKitRecoveryInput = swb::from_value(input)?;
+#[wasm_bindgen(js_name = openKitRecovery)]
+pub async fn open_kit_recovery(
+ input: <OpenKitRecoveryInput as Tsify>::JsType,
+) -> Result<LegacyKitRecoveryHandle, Error> {
+ let input = OpenKitRecoveryInput::from_js(input)?;
let client = LegacyKitRecoveryClient::new_with_headers(
input.base_url,
input.client_package,
input.client_version,
None,
)?;
+ let shares = input.shares.into_iter().map(Into::into).collect::<Vec<_>>();
let handle = client
- .open_from_shares(&input.shares, input.email.as_deref())
+ .open_from_shares(&shares, input.email.as_deref())
.await?;
Ok(LegacyKitRecoveryHandle { inner: handle })
}
@@ -198,15 +192,22 @@ pub struct LegacyKitRecoveryHandle {
#[wasm_bindgen]
impl LegacyKitRecoveryHandle {
- pub fn session(&self) -> Result<JsValue, Error> {
- Ok(swb::to_value(self.inner.session())?)
+ pub fn session(&self) -> Result<<LegacyKitRecoverySession as Tsify>::JsType, Error> {
+ LegacyKitRecoverySession::from(self.inner.session().clone())
+ .into_js()
+ .map_err(Into::into)
}
- pub async fn refresh_session(&self) -> Result<JsValue, Error> {
- let session = self.inner.refresh_session().await?;
- Ok(swb::to_value(&session)?)
+ #[wasm_bindgen(js_name = refreshSession)]
+ pub async fn refresh_session(
+ &self,
+ ) -> Result<<LegacyKitRecoverySession as Tsify>::JsType, Error> {
+ LegacyKitRecoverySession::from(self.inner.refresh_session().await?)
+ .into_js()
+ .map_err(Into::into)
}
+ #[wasm_bindgen(js_name = changePassword)]
pub async fn change_password(&self, new_password: String) -> Result<(), Error> {
Ok(self.inner.change_password(&new_password).await?)
}
diff --git a/rust/bindings/wasm/legacy/src/types.rs b/rust/bindings/wasm/legacy/src/types.rs
index 91d76a968e..5b3021112f 100644
--- a/rust/bindings/wasm/legacy/src/types.rs
+++ b/rust/bindings/wasm/legacy/src/types.rs
@@ -188,3 +188,95 @@ impl From<KeyAttributes> for ente_accounts::auth::KeyAttributes {
}
}
}
+
+#[derive(Deserialize, Tsify)]
+#[serde(rename_all = "camelCase")]
+pub struct OpenKitRecoveryInput {
+ pub base_url: String,
+ pub shares: Vec<LegacyKitShare>,
+ #[tsify(optional)]
+ pub email: Option<String>,
+ #[tsify(optional)]
+ pub client_package: Option<String>,
+ #[tsify(optional)]
+ pub client_version: Option<String>,
+}
+
+#[derive(Deserialize, Tsify)]
+pub struct LegacyKitShare {
+ #[serde(rename = "pv")]
+ payload_version: u8,
+ #[serde(rename = "kv")]
+ #[tsify(type = "number")]
+ variant: ente_legacy::LegacyKitVariant,
+ #[serde(rename = "k")]
+ kit_id: String,
+ #[serde(rename = "i")]
+ share_index: u8,
+ #[serde(rename = "s")]
+ share: String,
+ #[serde(rename = "c")]
+ checksum: String,
+ #[serde(rename = "n")]
+ part_name: String,
+}
+
+impl From<LegacyKitShare> for ente_legacy::LegacyKitShare {
+ fn from(value: LegacyKitShare) -> Self {
+ Self {
+ payload_version: value.payload_version,
+ variant: value.variant,
+ kit_id: value.kit_id,
+ share_index: value.share_index,
+ share: value.share,
+ checksum: value.checksum,
+ part_name: value.part_name,
+ }
+ }
+}
+
+#[derive(Serialize, Tsify)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyKitRecoverySession {
+ id: String,
+ #[serde(rename = "kitID")]
+ kit_id: String,
+ status: LegacyKitRecoveryStatus,
+ /// Remaining microseconds, not an epoch timestamp.
+ wait_till: i64,
+ created_at: i64,
+}
+
+impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
+ fn from(value: ente_legacy::LegacyKitRecoverySession) -> Self {
+ Self {
+ id: value.id,
+ kit_id: value.kit_id,
+ status: value.status.into(),
+ wait_till: value.wait_till,
+ created_at: value.created_at,
+ }
+ }
+}
+
+#[derive(Serialize, Tsify)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+enum LegacyKitRecoveryStatus {
+ Waiting,
+ Ready,
+ Blocked,
+ Cancelled,
+ Recovered,
+}
+
+impl From<ente_legacy::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
+ fn from(value: ente_legacy::LegacyKitRecoveryStatus) -> Self {
+ match value {
+ ente_legacy::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
+ ente_legacy::LegacyKitRecoveryStatus::Ready => Self::Ready,
+ ente_legacy::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
+ ente_legacy::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
+ ente_legacy::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
+ }
+ }
+}
diff --git a/web/apps/legacy/src/features/legacy-kit/recovery.ts b/web/apps/legacy/src/features/legacy-kit/recovery.ts
deleted file mode 100644
index 800f3abf16..0000000000
--- a/web/apps/legacy/src/features/legacy-kit/recovery.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
-import { apiOrigin } from "ente-base/origins";
-import type { LegacyKitRecoveryHandle } from "ente-legacy-wasm";
-import { z } from "zod";
-import type { LegacyKitShare } from "./share";
-
-export const LegacyKitRecoverySessionSchema = z.object({
- id: z.string(),
- kitID: z.string(),
- status: z.enum(["WAITING", "READY", "BLOCKED", "CANCELLED", "RECOVERED"]),
- // Despite the name, this is the remaining microseconds, not an epoch
- // timestamp.
- waitTill: z.number(),
- createdAt: z.number(),
-});
-
-export type LegacyKitRecoverySession = z.infer<
- typeof LegacyKitRecoverySessionSchema
->;
-
-export interface OpenedLegacyKitRecovery {
- handle: LegacyKitRecoveryHandle;
- session: LegacyKitRecoverySession;
-}
-
-export const openLegacyKitRecovery = async (
- shares: LegacyKitShare[],
- email?: string,
-): Promise<OpenedLegacyKitRecovery> => {
- const wasm = await import("ente-legacy-wasm");
- const handle = await wasm.legacy_kit_open_recovery({
- baseUrl: await apiOrigin(),
- shares,
- email: email?.trim() || undefined,
- clientPackage: clientPackageName,
- clientVersion: isDesktop ? desktopAppVersion : undefined,
- });
-
- return {
- handle,
- session: LegacyKitRecoverySessionSchema.parse(handle.session()),
- };
-};
-
-export const refreshLegacyKitRecoverySession = async (
- handle: LegacyKitRecoveryHandle,
-) => LegacyKitRecoverySessionSchema.parse(await handle.refresh_session());
-
-export const changeLegacyKitPassword = async (
- handle: LegacyKitRecoveryHandle,
- password: string,
-) => handle.change_password(password);
-
-export const formatRecoveryWait = (waitRemainingMicros: number) => {
- if (waitRemainingMicros <= 0) {
- return "ready now";
- }
-
- const totalMinutes = Math.ceil(waitRemainingMicros / (1000 * 1000 * 60));
- if (totalMinutes >= 60 * 24) {
- const days = Math.ceil(totalMinutes / (60 * 24));
- return `${days} day${days === 1 ? "" : "s"}`;
- }
- if (totalMinutes >= 60) {
- const hours = Math.ceil(totalMinutes / 60);
- return `${hours} hour${hours === 1 ? "" : "s"}`;
- }
- return `${totalMinutes} minute${totalMinutes === 1 ? "" : "s"}`;
-};
diff --git a/web/apps/legacy/src/pages/index.tsx b/web/apps/legacy/src/pages/index.tsx
index 872e637da5..3c780416b5 100644
--- a/web/apps/legacy/src/pages/index.tsx
+++ b/web/apps/legacy/src/pages/index.tsx
@@ -15,20 +15,20 @@ import {
Typography,
} from "@mui/material";
import { isWeakPassword } from "ente-accounts/utils/password";
+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { LoadingButton } from "ente-base/components/mui/LoadingButton";
import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
import { isDevBuild } from "ente-base/env";
import { isNamedError } from "ente-base/error";
import log from "ente-base/log";
-import type { LegacyKitRecoveryHandle } from "ente-legacy-wasm";
-import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { apiOrigin } from "ente-base/origins";
import {
- changeLegacyKitPassword,
- openLegacyKitRecovery,
- refreshLegacyKitRecoverySession,
+ openKitRecovery,
+ type LegacyKitRecoveryHandle,
type LegacyKitRecoverySession,
-} from "../features/legacy-kit/recovery";
+} from "ente-legacy-wasm";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
LegacyKitQRDecodeError,
readLegacyKitCodeFromFile,
@@ -246,9 +246,14 @@ const Page: React.FC = () => {
setOpenError(undefined);
try {
- const opened = await openLegacyKitRecovery(shares);
- setHandle(opened.handle);
- setSession(opened.session);
+ const opened = await openKitRecovery({
+ baseUrl: await apiOrigin(),
+ shares,
+ clientPackage: clientPackageName,
+ clientVersion: isDesktop ? desktopAppVersion : undefined,
+ });
+ setSession(opened.session());
+ setHandle(opened);
} catch (error) {
log.error("Legacy kit recovery open failed", error);
if (isInactiveLegacyKitError(error)) {
@@ -268,7 +273,7 @@ const Page: React.FC = () => {
setIsRefreshing(true);
setOpenError(undefined);
try {
- setSession(await refreshLegacyKitRecoverySession(handle));
+ setSession(await handle.refreshSession());
} catch (error) {
log.error("Legacy kit recovery refresh failed", error);
if (isInactiveLegacyKitError(error)) {
@@ -299,7 +304,7 @@ const Page: React.FC = () => {
return;
}
try {
- await changeLegacyKitPassword(handle, password);
+ await handle.changePassword(password);
setSession((current) =>
current ? { ...current, status: "RECOVERED" } : current,
);
diff --git a/web/packages/wasm/legacy/index.ts b/web/packages/wasm/legacy/index.ts
index d7cf9a1c1a..34e854033f 100644
--- a/web/packages/wasm/legacy/index.ts
+++ b/web/packages/wasm/legacy/index.ts
@@ -1 +1,11 @@
-export * from "./pkg/ente_legacy_wasm";
+import type { OpenKitRecoveryInput } from "./pkg/ente_legacy_wasm";
+
+export type {
+ LegacyKitRecoveryHandle,
+ LegacyKitRecoverySession,
+} from "./pkg/ente_legacy_wasm";
+
+const wasm = () => import("./pkg/ente_legacy_wasm");
+
+export const openKitRecovery = async (input: OpenKitRecoveryInput) =>
+ (await wasm()).openKitRecovery(input);