💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Move Legacy sheet encoding and validation into Rust
Manav Rathid1b02ee148e6
diff --git a/mobile/packages/legacy/lib/models/legacy_kit_models.dart b/mobile/packages/legacy/lib/models/legacy_kit_models.dartindex 7a1076c5de..5d7a423241 100644--- a/mobile/packages/legacy/lib/models/legacy_kit_models.dart+++ b/mobile/packages/legacy/lib/models/legacy_kit_models.dart@@ -1,5 +1,3 @@-import "dart:convert";-import "package:ente_frb/legacy.dart";export "package:ente_frb/legacy.dart";@@ -9,25 +7,3 @@ extension LegacyKitDisplay on LegacyKit {bool get hasActiveRecoverySession => activeRecoverySession != null;}--extension LegacyKitShareEncoding on LegacyKitShare {- String toQrPayload() {- return jsonEncode({- "pv": payloadVersion,- "kv": variant,- "k": _withoutWhitespace(kitId),- "i": shareIndex,- "s": _withoutWhitespace(share),- "c": _withoutWhitespace(checksum),- "n": partName,- });- }-- String toCopyCode() {- return base64Url.encode(utf8.encode(toQrPayload())).replaceAll("=", "");- }-- String _withoutWhitespace(String value) {- return value.replaceAll(RegExp(r"\s+"), "");- }-}diff --git a/mobile/packages/legacy/lib/services/legacy_kit_pdf_service.dart b/mobile/packages/legacy/lib/services/legacy_kit_pdf_service.dartindex b149d57aba..58cbb39660 100644--- a/mobile/packages/legacy/lib/services/legacy_kit_pdf_service.dart+++ b/mobile/packages/legacy/lib/services/legacy_kit_pdf_service.dart@@ -150,7 +150,7 @@ class LegacyKitPdfService {required _SheetAssets assets,required StringsLocalizations strings,}) {- final qrPayload = share.toQrPayload();+ final qrPayload = share.qrPayload;return pw.SizedBox(width: _sheetPageFormat.width,height: _sheetPageFormat.height,@@ -255,7 +255,7 @@ class LegacyKitPdfService {pw.Positioned(left: 360,top: 533,- child: _recoveryKeyCard(share.toCopyCode(), assets),+ child: _recoveryKeyCard(share.copyCode, assets),),pw.Positioned(left: 0,diff --git a/mobile/packages/legacy/test/legacy_kit_pdf_service_test.dart b/mobile/packages/legacy/test/legacy_kit_pdf_service_test.dartindex d9e5d88669..d883b1b2d4 100644--- a/mobile/packages/legacy/test/legacy_kit_pdf_service_test.dart+++ b/mobile/packages/legacy/test/legacy_kit_pdf_service_test.dart@@ -13,37 +13,6 @@ final _strings = lookupStringsLocalizations(const Locale("en"));void main() {TestWidgetsFlutterBinding.ensureInitialized();- test("normalizes compact legacy kit payload fields", () {- final payload =- jsonDecode(- const LegacyKitShare(- payloadVersion: 1,- variant: 1,- kitId: " e04efa62-2607-4c8b-b4c7-6c84f08fe162 ",- shareIndex: 2,- share: "USpH7sFwOXQ/TeSu1BeAJqfeVxwlKXZLnlCZ mOfmQiY=",- checksum: " c1T4uxBh7ws= ",- partName: "Amit, Brother, 98",- ).toQrPayload(),- )- as Map<String, dynamic>;-- expect(payload["k"], "e04efa62-2607-4c8b-b4c7-6c84f08fe162");- expect(payload["s"], "USpH7sFwOXQ/TeSu1BeAJqfeVxwlKXZLnlCZmOfmQiY=");- expect(payload["c"], "c1T4uxBh7ws=");- expect(payload["n"], "Amit, Brother, 98");- });-- test("keeps the complete display name in the QR payload", () {- const partName = "Mother 👩👩👧👦 Very Long Name";-- expect(- (jsonDecode(_share(1, partName).toQrPayload())- as Map<String, dynamic>)["n"],- partName,- );- });-test("formats recovery URL for recovery sheet instructions", () {expect(LegacyKitPdfService.displayRecoveryUrl("https://legacy.ente.com/"),@@ -60,7 +29,7 @@ void main() {});test("builds individual legacy kit recovery sheet PDFs", () async {- final shares = [_share(1, "Mom"), _share(2, "Alex"), _share(3, "Lawyer")];+ final shares = [_share(1), _share(2), _share(3)];const service = LegacyKitPdfService();final sheets = await Future.wait(@@ -84,7 +53,7 @@ void main() {test("embeds the sheet fonts instead of falling back to a base font",() async {- final shares = [_share(1, "Mom"), _share(2, "Alex")];+ final shares = [_share(1), _share(2)];const service = LegacyKitPdfService();final sheet = await service.buildRecoverySheet(accountEmail: "[email protected]",@@ -118,7 +87,7 @@ void main() {test("renders Cyrillic holder names without missing glyphs", () async {final printedMessages = <String>[];- final shares = [_share(1, "Мама"), _share(2, "Alex")];+ final shares = [_share(1), _share(2)];final sheet = await runZoned(() => const LegacyKitPdfService().buildRecoverySheet(@@ -147,11 +116,7 @@ void main() {() async {final outputDir = Directory(Platform.environment["LEGACY_PDF_OUT"]!)..createSync(recursive: true);- final shares = [- _share(1, "Мама"),- _share(2, "Alex"),- _share(3, "Lawyer"),- ];+ final shares = [_share(1), _share(2), _share(3)];const service = LegacyKitPdfService();for (final share in shares) {final sheet = await service.buildRecoverySheet(@@ -180,14 +145,21 @@ Set<String> _embeddedFonts(List<int> pdf) {.toSet();}-LegacyKitShare _share(int index, String partName) {+LegacyKitShare _share(int index) {+ final fixtures =+ jsonDecode(+ File(+ "../../../rust/crates/legacy/tests/fixtures/mobile-sheets.json",+ ).readAsStringSync(),+ )+ as List;+ final fixture = fixtures[index - 1] as Map<String, dynamic>;+ final qrPayload = fixture["qr_payload"] as String;+ final payload = jsonDecode(qrPayload) as Map<String, dynamic>;return LegacyKitShare(- payloadVersion: 1,- variant: 1,- kitId: "kit-id",shareIndex: index,- share: "AQEgx7Kp2mNfR4wBzH8vTjYdLnUcXsS6aWe3qFh9iDlOkPr0tMbJ4vG$index",- checksum: "checksum",- partName: partName,+ partName: payload["n"] as String,+ qrPayload: qrPayload,+ copyCode: fixture["copy_code"] as String,);}diff --git a/rust/bindings/frb/lib/src/legacy.rs b/rust/bindings/frb/lib/src/legacy.rsindex 7e748abff1..e860aea575 100644--- a/rust/bindings/frb/lib/src/legacy.rs+++ b/rust/bindings/frb/lib/src/legacy.rs@@ -49,38 +49,40 @@ pub struct LegacyKitCreateResult {pub shares: Vec<LegacyKitShare>,}-impl From<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {- fn from(value: ente_legacy::LegacyKitCreateResult) -> Self {- Self {+impl TryFrom<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {+ type Error = LegacyError;++ fn try_from(value: ente_legacy::LegacyKitCreateResult) -> Result<Self, Self::Error> {+ Ok(Self {kit: value.kit.into(),- shares: value.shares.into_iter().map(Into::into).collect(),- }+ shares: value+ .shares+ .into_iter()+ .map(TryInto::try_into)+ .collect::<Result<_, _>>()?,+ })}}#[frb(unignore)]#[derive(Clone)]pub struct LegacyKitShare {- pub payload_version: u8,- pub variant: u8,- pub kit_id: String,pub share_index: u8,- pub share: String,- pub checksum: String,pub part_name: String,+ pub qr_payload: String,+ pub copy_code: String,}-impl From<ente_legacy::LegacyKitShare> for LegacyKitShare {- fn from(value: ente_legacy::LegacyKitShare) -> Self {- Self {- payload_version: value.payload_version,- variant: value.variant.code(),- kit_id: value.kit_id,+impl TryFrom<ente_legacy::LegacyKitShare> for LegacyKitShare {+ type Error = LegacyError;++ fn try_from(value: ente_legacy::LegacyKitShare) -> Result<Self, Self::Error> {+ Ok(Self {+ qr_payload: value.to_qr_payload()?,+ copy_code: value.to_copy_code()?,share_index: value.share_index,- share: value.share,- checksum: value.checksum,part_name: value.part_name,- }+ })}}diff --git a/rust/bindings/frb/locker/src/api/legacy.rs b/rust/bindings/frb/locker/src/api/legacy.rsindex 503a75f2f0..be93833928 100644--- a/rust/bindings/frb/locker/src/api/legacy.rs+++ b/rust/bindings/frb/locker/src/api/legacy.rs@@ -62,9 +62,8 @@ pub async fn create_kit(part_names,notice_period_in_hours,)- .await- .map(Into::into)- .map_err(Into::into)+ .await?+ .try_into()}pub async fn download_kit_shares(@@ -72,9 +71,10 @@ pub async fn download_kit_shares(kit_id: String,) -> Result<Vec<LegacyKitShare>, LegacyError> {ente_legacy::download_kit_shares(session.as_ref(), &kit_id)- .await- .map(|shares| shares.into_iter().map(Into::into).collect())- .map_err(Into::into)+ .await?+ .into_iter()+ .map(TryInto::try_into)+ .collect()}pub async fn update_kit_recovery_notice(diff --git a/rust/bindings/wasm/legacy/src/lib.rs b/rust/bindings/wasm/legacy/src/lib.rsindex 52ba7fda57..0180c3dde1 100644--- a/rust/bindings/wasm/legacy/src/lib.rs+++ b/rust/bindings/wasm/legacy/src/lib.rs@@ -6,7 +6,8 @@ use ente_wasm_lib::session::Session;use serde_wasm_bindgen as swb;use tsify::Tsify;use types::{- KeyAttributes, LegacyContactState, LegacyInfo, LegacyKitRecoverySession, OpenKitRecoveryInput,+ KeyAttributes, LegacyContactState, LegacyInfo, LegacyKitRecoverySession, LegacyKitShare,+ OpenKitRecoveryInput,};use wasm_bindgen::prelude::*;@@ -23,6 +24,10 @@ pub enum Error {impl Error {fn name(&self) -> Option<&'static str> {match self {+ Self::Legacy(ente_legacy::Error::DifferentLegacyKits) => Some("different_legacy_kits"),+ Self::Legacy(ente_legacy::Error::DuplicateLegacyKitShare) => {+ Some("duplicate_legacy_kit_share")+ }Self::Legacy(ente_legacy::Error::LegacyKitInactive) => Some("legacy_kit_inactive"),Self::Legacy(ente_legacy::Error::ContactNotOnEnte) => Some("contact_not_on_ente"),Self::Legacy(ente_legacy::Error::ActiveRecoverySession) => {@@ -158,6 +163,25 @@ pub async fn legacy_change_password(.map_err(Into::into)}+#[wasm_bindgen(js_name = parseLegacyKitShare)]+pub fn parse_legacy_kit_share(input: &str) -> Result<<LegacyKitShare as Tsify>::JsType, Error> {+ LegacyKitShare::from(ente_legacy::LegacyKitShare::parse(input)?)+ .into_js()+ .map_err(Into::into)+}++#[wasm_bindgen(js_name = validateLegacyKitSharePair)]+pub fn validate_legacy_kit_share_pair(+ first: <LegacyKitShare as Tsify>::JsType,+ second: <LegacyKitShare as Tsify>::JsType,+) -> Result<(), Error> {+ ente_legacy::validate_share_pair(+ &LegacyKitShare::from_js(first)?.into(),+ &LegacyKitShare::from_js(second)?.into(),+ )+ .map_err(Into::into)+}+#[wasm_bindgen(js_name = openKitRecovery)]pub async fn open_kit_recovery(input: <OpenKitRecoveryInput as Tsify>::JsType,diff --git a/rust/bindings/wasm/legacy/src/types.rs b/rust/bindings/wasm/legacy/src/types.rsindex 33a1c8fb96..48cdde3071 100644--- a/rust/bindings/wasm/legacy/src/types.rs+++ b/rust/bindings/wasm/legacy/src/types.rs@@ -202,7 +202,7 @@ pub struct OpenKitRecoveryInput {pub client_version: Option<String>,}-#[derive(Deserialize, Tsify)]+#[derive(Serialize, Deserialize, Tsify)]pub struct LegacyKitShare {#[serde(rename = "pv")]payload_version: u8,@@ -221,6 +221,20 @@ pub struct LegacyKitShare {part_name: String,}+impl From<ente_legacy::LegacyKitShare> for LegacyKitShare {+ fn from(value: ente_legacy::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,+ }+ }+}+impl From<LegacyKitShare> for ente_legacy::LegacyKitShare {fn from(value: LegacyKitShare) -> Self {Self {diff --git a/rust/crates/core/src/b64.rs b/rust/crates/core/src/b64.rsindex 34a51889c1..a62d317e1e 100644--- a/rust/crates/core/src/b64.rs+++ b/rust/crates/core/src/b64.rs@@ -1,6 +1,8 @@use base64::{- Engine,- engine::general_purpose::{STANDARD, URL_SAFE, URL_SAFE_NO_PAD},+ Engine, alphabet,+ engine::general_purpose::{+ GeneralPurpose, GeneralPurposeConfig, STANDARD, URL_SAFE, URL_SAFE_NO_PAD,+ },};pub use base64::DecodeError;@@ -9,6 +11,15 @@ pub fn decode(input: &str) -> Result<Vec<u8>, DecodeError> {STANDARD.decode(input)}+// Browser atob ignores unused trailing bits in otherwise valid base64.+pub fn decode_allow_trailing_bits(input: &str) -> Result<Vec<u8>, DecodeError> {+ GeneralPurpose::new(+ &alphabet::STANDARD,+ GeneralPurposeConfig::new().with_decode_allow_trailing_bits(true),+ )+ .decode(input)+}+// Standard base64 (RFC 4648), matching libsodium's// `sodium_base64_VARIANT_ORIGINAL`.pub fn encode(input: &[u8]) -> String {diff --git a/rust/crates/legacy/src/error.rs b/rust/crates/legacy/src/error.rsindex a57ef727ff..7c4618c5d3 100644--- a/rust/crates/legacy/src/error.rs+++ b/rust/crates/legacy/src/error.rs@@ -18,6 +18,12 @@ pub enum Error {#[error("invalid input: {0}")]InvalidInput(String),+ #[error("invalid input: legacy kit shares must belong to the same kit")]+ DifferentLegacyKits,++ #[error("invalid input: legacy kit shares must use different indices")]+ DuplicateLegacyKitShare,+#[error("legacy contact is not on Ente")]ContactNotOnEnte,diff --git a/rust/crates/legacy/src/kit/mod.rs b/rust/crates/legacy/src/kit/mod.rsindex 17194da356..1911bb8b95 100644--- a/rust/crates/legacy/src/kit/mod.rs+++ b/rust/crates/legacy/src/kit/mod.rs@@ -9,6 +9,7 @@ pub use models::{LegacyKitVariant,};pub use recovery::{LegacyKitRecoveryClient, LegacyKitRecoveryHandle};+pub use shares::validate_share_pair;use ente_core::crypto::{self, SecretVec, kdf};diff --git a/rust/crates/legacy/src/kit/shares.rs b/rust/crates/legacy/src/kit/shares.rsindex c0c4dd7db7..d0dec2206e 100644--- a/rust/crates/legacy/src/kit/shares.rs+++ b/rust/crates/legacy/src/kit/shares.rs@@ -6,6 +6,93 @@ use crate::{Error, Result};use super::models::{LEGACY_KIT_PAYLOAD_VERSION, LegacyKitShare, LegacyKitVariant};+impl LegacyKitShare {+ pub fn parse(input: &str) -> Result<Self> {+ let input = input.trim_matches(sheet_whitespace);+ let json = if input.starts_with('{') {+ input.to_owned()+ } else {+ let mut encoded = compact(input).replace('-', "+").replace('_', "/");+ while !encoded.len().is_multiple_of(4) {+ encoded.push('=');+ }+ let bytes = b64::decode_allow_trailing_bits(&encoded)?;+ let decoded = String::from_utf8_lossy(&bytes);+ decoded+ .strip_prefix('\u{feff}')+ .unwrap_or(&decoded)+ .to_owned()+ };+ // JSON.parse accepts duplicate keys and integer-valued floats.+ let mut value: serde_json::Value =+ serde_json::from_str(&json).map_err(|error| Error::InvalidInput(error.to_string()))?;+ for field in ["pv", "kv", "i"] {+ if let Some(number) = value.get(field).and_then(serde_json::Value::as_f64)+ && number.fract() == 0.0+ && (0.0..=255.0).contains(&number)+ {+ value[field] = serde_json::Value::from(number as u8);+ }+ }+ let mut share: Self = serde_json::from_value(value)+ .map_err(|error| Error::InvalidInput(error.to_string()))?;+ share.compact_fields();+ validate_share_header(&share)?;+ if share.kit_id.is_empty() || share.part_name.is_empty() {+ return Err(Error::InvalidInput(+ "legacy kit ID and part name must be non-empty".into(),+ ));+ }+ if b64::decode_allow_trailing_bits(&share.share)?.len() != 32+ || b64::decode_allow_trailing_bits(&share.checksum)?.len() != 8+ {+ return Err(Error::InvalidInput(+ "invalid legacy kit share or checksum length".into(),+ ));+ }+ Ok(share)+ }++ pub fn to_qr_payload(&self) -> Result<String> {+ let mut share = self.clone();+ share.compact_fields();+ serde_json::to_string(&share).map_err(|error| Error::InvalidInput(error.to_string()))+ }++ pub fn to_copy_code(&self) -> Result<String> {+ Ok(b64::encode_url_safe_no_padding(+ self.to_qr_payload()?.as_bytes(),+ ))+ }++ fn compact_fields(&mut self) {+ self.kit_id = compact(&self.kit_id);+ self.share = compact(&self.share);+ self.checksum = compact(&self.checksum);+ }+}++fn compact(value: &str) -> String {+ value+ .chars()+ .filter(|character| !sheet_whitespace(*character))+ .collect()+}++fn sheet_whitespace(character: char) -> bool {+ (character.is_whitespace() && character != '\u{0085}') || character == '\u{feff}'+}++pub fn validate_share_pair(first: &LegacyKitShare, second: &LegacyKitShare) -> Result<()> {+ if first.kit_id != second.kit_id {+ return Err(Error::DifferentLegacyKits);+ }+ if first.share_index == second.share_index {+ return Err(Error::DuplicateLegacyKitShare);+ }+ Ok(())+}+pub(crate) fn checksum(payload_version: u8,variant: LegacyKitVariant,@@ -61,9 +148,7 @@ pub(crate) fn reconstruct_secret_2_of_3(shares: &[LegacyKitShare]) -> Result<Sec));}if first.kit_id != second.kit_id {- return Err(Error::InvalidInput(- "legacy kit shares must belong to the same kit".into(),- ));+ return Err(Error::DifferentLegacyKits);}if first.checksum != second.checksum {return Err(Error::InvalidInput(@@ -71,9 +156,7 @@ pub(crate) fn reconstruct_secret_2_of_3(shares: &[LegacyKitShare]) -> Result<Sec));}if first.share_index == second.share_index {- return Err(Error::InvalidInput(- "legacy kit shares must use different indices".into(),- ));+ return Err(Error::DuplicateLegacyKitShare);}let y1 = b64::decode(&first.share)?;diff --git a/rust/crates/legacy/src/lib.rs b/rust/crates/legacy/src/lib.rsindex ed37af1b76..498489b4a9 100644--- a/rust/crates/legacy/src/lib.rs+++ b/rust/crates/legacy/src/lib.rs@@ -15,5 +15,5 @@ pub use kit::{LEGACY_KIT_PAYLOAD_VERSION, LegacyKit, LegacyKitCreateResult, LegacyKitMetadata,LegacyKitOwnerRecoverySession, LegacyKitPart, LegacyKitRecoveryBundle, LegacyKitRecoveryClient,LegacyKitRecoveryHandle, LegacyKitRecoveryInitiator, LegacyKitRecoverySession,- LegacyKitRecoveryStatus, LegacyKitShare, LegacyKitVariant,+ LegacyKitRecoveryStatus, LegacyKitShare, LegacyKitVariant, validate_share_pair,};diff --git a/rust/crates/legacy/tests/fixtures/mobile-sheets.json b/rust/crates/legacy/tests/fixtures/mobile-sheets.jsonnew file mode 100644index 0000000000..1e0827f002--- /dev/null+++ b/rust/crates/legacy/tests/fixtures/mobile-sheets.json@@ -0,0 +1,18 @@+[+ {+ "qr_payload": "{\"pv\":1,\"kv\":1,\"k\":\"e04efa62-2607-4c8b-b4c7-6c84f08fe162\",\"i\":1,\"s\":\"AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=\",\"c\":\"GuFHh4Zu4GA=\",\"n\":\"Мама\"}",+ "copy_code": "eyJwdiI6MSwia3YiOjEsImsiOiJlMDRlZmE2Mi0yNjA3LTRjOGItYjRjNy02Yzg0ZjA4ZmUxNjIiLCJpIjoxLCJzIjoiQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnST0iLCJjIjoiR3VGSGg0WnU0R0E9IiwibiI6ItCc0LDQvNCwIn0"+ },+ {+ "qr_payload": "{\"pv\":1,\"kv\":1,\"k\":\"e04efa62-2607-4c8b-b4c7-6c84f08fe162\",\"i\":2,\"s\":\"DQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0=\",\"c\":\"GuFHh4Zu4GA=\",\"n\":\"Alex\"}",+ "copy_code": "eyJwdiI6MSwia3YiOjEsImsiOiJlMDRlZmE2Mi0yNjA3LTRjOGItYjRjNy02Yzg0ZjA4ZmUxNjIiLCJpIjoyLCJzIjoiRFEwTkRRME5EUTBORFEwTkRRME5EUTBORFEwTkRRME5EUTBORFEwTkRRMD0iLCJjIjoiR3VGSGg0WnU0R0E9IiwibiI6IkFsZXgifQ"+ },+ {+ "qr_payload": "{\"pv\":1,\"kv\":1,\"k\":\"e04efa62-2607-4c8b-b4c7-6c84f08fe162\",\"i\":3,\"s\":\"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg=\",\"c\":\"GuFHh4Zu4GA=\",\"n\":\"Lawyer\"}",+ "copy_code": "eyJwdiI6MSwia3YiOjEsImsiOiJlMDRlZmE2Mi0yNjA3LTRjOGItYjRjNy02Yzg0ZjA4ZmUxNjIiLCJpIjozLCJzIjoiQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZz0iLCJjIjoiR3VGSGg0WnU0R0E9IiwibiI6Ikxhd3llciJ9"+ },+ {+ "qr_payload": "{\"pv\":1,\"kv\":1,\"k\":\"e04efa62-2607-4c8b-b4c7-6c84f08fe162\",\"i\":1,\"s\":\"AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=\",\"c\":\"GuFHh4Zu4GA=\",\"n\":\"Mother 👩👩👧👦 \\\"North\\\"\\nVery Long Name\"}",+ "copy_code": "eyJwdiI6MSwia3YiOjEsImsiOiJlMDRlZmE2Mi0yNjA3LTRjOGItYjRjNy02Yzg0ZjA4ZmUxNjIiLCJpIjoxLCJzIjoiQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnSUNBZ0lDQWdJQ0FnST0iLCJjIjoiR3VGSGg0WnU0R0E9IiwibiI6Ik1vdGhlciDwn5Gp4oCN8J-RqeKAjfCfkafigI3wn5GmIFwiTm9ydGhcIlxuVmVyeSBMb25nIE5hbWUifQ"+ }+]diff --git a/rust/crates/legacy/tests/sheet_format.rs b/rust/crates/legacy/tests/sheet_format.rsnew file mode 100644index 0000000000..9fa0cb7de6--- /dev/null+++ b/rust/crates/legacy/tests/sheet_format.rs@@ -0,0 +1,124 @@+use ente_core::b64;+use ente_legacy::{Error, LegacyKitRecoveryClient, LegacyKitShare, validate_share_pair};+use serde::Deserialize;+use serde_json::json;++#[derive(Deserialize)]+struct MobileSheet {+ qr_payload: String,+ copy_code: String,+}++fn mobile_sheets() -> Vec<MobileSheet> {+ serde_json::from_str(include_str!("fixtures/mobile-sheets.json")).unwrap()+}++#[test]+fn reads_and_reproduces_existing_mobile_sheets() {+ let sheets = mobile_sheets();+ for sheet in &sheets {+ let share = LegacyKitShare::parse(&sheet.qr_payload).unwrap();+ assert_eq!(LegacyKitShare::parse(&sheet.copy_code).unwrap(), share);+ assert_eq!(share.to_qr_payload().unwrap(), sheet.qr_payload);+ assert_eq!(share.to_copy_code().unwrap(), sheet.copy_code);+ }+ for pair in [[0, 1], [0, 2], [1, 2]] {+ let shares = pair.map(|index| LegacyKitShare::parse(&sheets[index].copy_code).unwrap());+ validate_share_pair(&shares[0], &shares[1]).unwrap();+ assert_eq!(+ LegacyKitRecoveryClient::reconstruct_secret(&shares)+ .unwrap()+ .as_ref(),+ &[7; 32],+ );+ }+}++#[test]+fn preserves_copying_and_json_variations() {+ let sheet = &mobile_sheets()[3];+ let share = LegacyKitShare::parse(&sheet.qr_payload).unwrap();+ for encoded in [+ b64::encode(sheet.qr_payload.as_bytes()),+ b64::encode_url_safe(sheet.qr_payload.as_bytes()),+ sheet.copy_code.clone(),+ ] {+ let wrapped = encoded+ .chars()+ .map(|c| format!("{c}\n\u{feff}"))+ .collect::<String>();+ assert_eq!(LegacyKitShare::parse(&wrapped).unwrap(), share);+ }++ let mut spaced = share.clone();+ spaced.kit_id = format!(" \u{feff}{}\t", share.kit_id);+ spaced.share = share.share.chars().map(|c| format!("{c}\n")).collect();+ spaced.checksum = format!("\u{a0}{}\r", share.checksum);+ assert_eq!(spaced.to_qr_payload().unwrap(), sheet.qr_payload);+ assert_eq!(+ LegacyKitShare::parse(&serde_json::to_string(&spaced).unwrap()).unwrap(),+ share,+ );+ let json = sheet+ .qr_payload+ .replace("\"pv\":1", "\"pv\":9,\"pv\":1.0")+ .replace("\"kv\":1", "\"kv\":1e0");+ assert_eq!(LegacyKitShare::parse(&json).unwrap(), share);+ let encoded = b64::encode(format!("\u{feff}{}", sheet.qr_payload).as_bytes());+ assert_eq!(LegacyKitShare::parse(&encoded).unwrap(), share);+ let encoded = b64::encode(format!("\u{feff}\u{feff}{}", sheet.qr_payload).as_bytes());+ assert!(LegacyKitShare::parse(&encoded).is_err());+}++#[test]+fn rejects_invalid_sheet_fields() {+ let payload: serde_json::Value = serde_json::from_str(&mobile_sheets()[0].qr_payload).unwrap();+ for (field, value) in [+ ("pv", json!(2)),+ ("kv", json!(2)),+ ("i", json!(0)),+ ("i", json!(4)),+ ("i", json!(1.5)),+ ("k", json!(" \n")),+ ("n", json!("")),+ ("s", json!(b64::encode(&[0; 31]))),+ ("c", json!(b64::encode(&[0; 7]))),+ ("s", json!("A".repeat(43))),+ ("c", json!("!!!!!!!!!!!=")),+ ] {+ let mut invalid = payload.clone();+ invalid[field] = value;+ assert!(+ LegacyKitShare::parse(&invalid.to_string()).is_err(),+ "{field}"+ );+ }+ for field in ["pv", "kv", "k", "i", "s", "c", "n"] {+ let mut invalid = payload.clone();+ invalid.as_object_mut().unwrap().remove(field);+ assert!(+ LegacyKitShare::parse(&invalid.to_string()).is_err(),+ "missing {field}"+ );+ }+}++#[test]+fn pair_errors_remain_distinct_from_checksum_verification() {+ let sheets = mobile_sheets();+ let first = LegacyKitShare::parse(&sheets[0].copy_code).unwrap();+ let mut second = LegacyKitShare::parse(&sheets[1].copy_code).unwrap();+ assert!(matches!(+ validate_share_pair(&first, &first),+ Err(Error::DuplicateLegacyKitShare)+ ));+ second.kit_id = "another-kit".into();+ assert!(matches!(+ validate_share_pair(&first, &second),+ Err(Error::DifferentLegacyKits)+ ));+ second.kit_id = first.kit_id.clone();+ second.checksum = b64::encode(&[0; 8]);+ validate_share_pair(&first, &second).unwrap();+ assert!(LegacyKitRecoveryClient::reconstruct_secret(&[first, second]).is_err());+}diff --git a/web/apps/legacy/package.json b/web/apps/legacy/package.jsonindex 6a9e84c847..1ffce7779a 100644--- a/web/apps/legacy/package.json+++ b/web/apps/legacy/package.json@@ -8,8 +8,7 @@"ente-base": "*","ente-legacy-wasm": "*","pdfjs-dist": "6.2.108",- "qr": "0.6.0",- "zod": "4.4.3"+ "qr": "0.6.0"},"devDependencies": {"ente-build-config": "*"diff --git a/web/apps/legacy/src/features/legacy-kit/share.ts b/web/apps/legacy/src/features/legacy-kit/share.tsdeleted file mode 100644index 19e15a05f5..0000000000--- a/web/apps/legacy/src/features/legacy-kit/share.ts+++ /dev/null@@ -1,81 +0,0 @@-import { z } from "zod";--const compactString = (value: unknown) =>- typeof value === "string" ? value.replaceAll(/\s/g, "") : value;--const decodeBase64URLUTF8 = (value: string) => {- const base64 = value- .replaceAll("-", "+")- .replaceAll("_", "/")- .padEnd(Math.ceil(value.length / 4) * 4, "=");- const binary = atob(base64);- const bytes = new Uint8Array(binary.length);- for (let index = 0; index < binary.length; index++) {- bytes[index] = binary.charCodeAt(index);- }- return new TextDecoder().decode(bytes);-};--const base64ByteLength = (value: string) => {- if (- !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(- value,- )- ) {- return undefined;- }-- try {- return atob(value).length;- } catch {- return undefined;- }-};--export const LegacyKitShareSchema = z.object({- pv: z.literal(1),- kv: z.literal(1),- k: z.preprocess(compactString, z.string().min(1)),- i: z.number().int().min(1).max(3),- s: z.preprocess(- compactString,- z- .string()- .min(1)- .refine((value) => base64ByteLength(value) === 32),- ),- c: z.preprocess(- compactString,- z- .string()- .min(1)- .refine((value) => base64ByteLength(value) === 8),- ),- n: z.string().min(1),-});--export type LegacyKitShare = z.infer<typeof LegacyKitShareSchema>;--export const parseLegacyKitShare = (value: string): LegacyKitShare => {- const trimmed = value.trim();- const json = trimmed.startsWith("{")- ? trimmed- : decodeBase64URLUTF8(compactString(trimmed) as string);- const parsed: unknown = JSON.parse(json);- return LegacyKitShareSchema.parse(parsed);-};--export const describeShare = (share: LegacyKitShare) =>- `${share.n} · part ${share.i}`;--export const validateLegacyKitSharePair = (- first: LegacyKitShare,- second: LegacyKitShare,-) => {- if (first.k !== second.k) {- throw new Error("These sheets are from different Legacy Kits.");- }- if (first.i === second.i) {- throw new Error("Use two different sheets from the same Legacy Kit.");- }-};diff --git a/web/apps/legacy/src/pages/index.tsx b/web/apps/legacy/src/pages/index.tsxindex 3c780416b5..95b472768b 100644--- a/web/apps/legacy/src/pages/index.tsx+++ b/web/apps/legacy/src/pages/index.tsx@@ -7,7 +7,6 @@ import type { SxProps, Theme } from "@mui/material";import {Alert,Box,- Button,CircularProgress,Snackbar,Stack,@@ -24,20 +23,18 @@ import { isNamedError } from "ente-base/error";import log from "ente-base/log";import { apiOrigin } from "ente-base/origins";import {+ loadLegacyKitParser,openKitRecovery,+ type LegacyKitParser,type LegacyKitRecoveryHandle,type LegacyKitRecoverySession,+ type LegacyKitShare,} from "ente-legacy-wasm";import React, { useCallback, useEffect, useMemo, useState } from "react";import {LegacyKitQRDecodeError,readLegacyKitCodeFromFile,} from "../features/legacy-kit/scan";-import {- parseLegacyKitShare,- validateLegacyKitSharePair,- type LegacyKitShare,-} from "../features/legacy-kit/share";type SlotID = "first" | "second";@@ -68,13 +65,16 @@ const getErrorMessage = (error: unknown) =>const isInactiveLegacyKitError = (error: unknown) =>isNamedError(error, "legacy_kit_inactive");-const parseSlotCode = (rawCode: string): Pick<SheetSlot, "error" | "share"> => {+const parseSlotCode = (+ rawCode: string,+ parser: LegacyKitParser,+): Pick<SheetSlot, "error" | "share"> => {if (!rawCode.trim()) {return {};}try {- return { share: parseLegacyKitShare(rawCode) };+ return { share: parser.parseLegacyKitShare(rawCode) };} catch {return { error: "Invalid sheet." };}@@ -136,7 +136,44 @@ const buttonSx = {};const Page: React.FC = () => {- const [hasStarted, setHasStarted] = useState(false);+ const [parser, setParser] = useState<LegacyKitParser>();+ const [isStarting, setIsStarting] = useState(false);+ const [startError, setStartError] = useState<string>();++ const start = async () => {+ if (startError) {+ window.location.reload();+ return;+ }+ setIsStarting(true);+ try {+ setParser(await loadLegacyKitParser());+ } catch (error) {+ log.error("Could not load Legacy Kit recovery", error);+ setStartError(+ "Could not load recovery. Please reload the page to try again.",+ );+ } finally {+ setIsStarting(false);+ }+ };++ return (+ <LegacyShell>+ {parser ? (+ <RecoveryFlow parser={parser} />+ ) : (+ <LandingStep+ onStart={() => void start()}+ isStarting={isStarting}+ error={startError}+ />+ )}+ </LegacyShell>+ );+};++const RecoveryFlow: React.FC<{ parser: LegacyKitParser }> = ({ parser }) => {const [slots, setSlots] = useState<Record<SlotID, SheetSlot>>({first: emptySlot(),second: emptySlot(),@@ -162,12 +199,18 @@ const Page: React.FC = () => {return undefined;}try {- validateLegacyKitSharePair(shares[0], shares[1]);+ parser.validateLegacyKitSharePair(shares[0], shares[1]);return undefined;} catch (error) {+ if (isNamedError(error, "different_legacy_kits")) {+ return "These sheets are from different Legacy Kits.";+ }+ if (isNamedError(error, "duplicate_legacy_kit_share")) {+ return "Use two different sheets from the same Legacy Kit.";+ }return getErrorMessage(error);}- }, [shares]);+ }, [parser, shares]);const canOpen = !!shares && !pairError && !isOpening;@@ -183,7 +226,7 @@ const Page: React.FC = () => {const handleCodeChange = useCallback((slotID: SlotID, rawCode: string) => {- const parsed = parseSlotCode(rawCode);+ const parsed = parseSlotCode(rawCode, parser);setOpenError(undefined);updateSlot(slotID, {error: parsed.error,@@ -192,7 +235,7 @@ const Page: React.FC = () => {share: parsed.share,});},- [updateSlot],+ [parser, updateSlot],);const handleFile = useCallback(@@ -212,7 +255,7 @@ const Page: React.FC = () => {void readLegacyKitCodeFromFile(file).then((rawCode) => {- const parsed = parseSlotCode(rawCode);+ const parsed = parseSlotCode(rawCode, parser);updateSlot(slotID, {error: parsed.error,fileName: file.name,@@ -234,7 +277,7 @@ const Page: React.FC = () => {});});},- [updateSlot],+ [parser, updateSlot],);const openRecovery = useCallback(async () => {@@ -321,15 +364,8 @@ const Page: React.FC = () => {);return (- <LegacyShell>- {!hasStarted ? (- <LandingStep- onStart={() => {- setIsKitInactive(false);- setHasStarted(true);- }}- />- ) : isKitInactive ? (+ <>+ {isKitInactive ? (<InactiveLegacyKitStep />) : !session ? (<UploadStep@@ -361,7 +397,7 @@ const Page: React.FC = () => {onClose={() => setShowQRDecodeWarning(false)}/>)}- </LegacyShell>+ </>);};@@ -417,9 +453,15 @@ const LegacyShell: React.FC<LegacyShellProps> = ({ children }) => (interface LandingStepProps {onStart: () => void;+ isStarting: boolean;+ error: string | undefined;}-const LandingStep: React.FC<LandingStepProps> = ({ onStart }) => (+const LandingStep: React.FC<LandingStepProps> = ({+ onStart,+ isStarting,+ error,+}) => (<Stackdirection={{ xs: "column", lg: "row" }}sx={{@@ -520,9 +562,11 @@ const LandingStep: React.FC<LandingStepProps> = ({ onStart }) => ())}</Stack>- <Button+ {error && <Alert severity="error">{error}</Alert>}+ <LoadingButtoncolor="accent"onClick={onStart}+ loading={isStarting}sx={{...buttonSx,borderRadius: { xs: "20px", md: "25px" },@@ -532,8 +576,8 @@ const LandingStep: React.FC<LandingStepProps> = ({ onStart }) => (width: "100%",}}>- Start recovery- </Button>+ {error ? "Reload page" : "Start recovery"}+ </LoadingButton></Stack></Stack>);diff --git a/web/package-lock.json b/web/package-lock.jsonindex f6c9730bc6..4517c2d9c3 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -216,8 +216,7 @@"ente-base": "*","ente-legacy-wasm": "*","pdfjs-dist": "6.2.108",- "qr": "0.6.0",- "zod": "4.4.3"+ "qr": "0.6.0"},"devDependencies": {"ente-build-config": "*"diff --git a/web/packages/wasm/legacy/index.ts b/web/packages/wasm/legacy/index.tsindex 34e854033f..5ca979eccf 100644--- a/web/packages/wasm/legacy/index.ts+++ b/web/packages/wasm/legacy/index.ts@@ -3,9 +3,17 @@ import type { OpenKitRecoveryInput } from "./pkg/ente_legacy_wasm";export type {LegacyKitRecoveryHandle,LegacyKitRecoverySession,+ LegacyKitShare,} from "./pkg/ente_legacy_wasm";const wasm = () => import("./pkg/ente_legacy_wasm");+export const loadLegacyKitParser = async () => {+ const { parseLegacyKitShare, validateLegacyKitSharePair } = await wasm();+ return { parseLegacyKitShare, validateLegacyKitSharePair };+};++export type LegacyKitParser = Awaited<ReturnType<typeof loadLegacyKitParser>>;+export const openKitRecovery = async (input: OpenKitRecoveryInput) =>(await wasm()).openKitRecovery(input);