securemail: random send/receive aliases on one inbox
- Commit
5265483a11ebb39e36e11f1cc0214820a210abd2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-04 18:24 UTC (1 month ago)
- Parents
1f99c26
Settings gets an Addresses card: "New random alias" claims a readable [email protected] address with its own PGP key, so recipients cannot link aliases by fingerprint. Aliases can be labeled, copied and turned off (the relay holds their mail). Compose gets a From picker; replies and drafts default to the alias the mail arrived on. Speaks relay protocol v2: signs each SUB against the server challenge, SUBs every active identity on one socket, names the sender on PUB, and reads the delivered-to address on MSG to decrypt with that alias's key. Onboarding only persists the identity once the relay accepts the claim, so a taken address is no longer silently overwritten. Room v4->v5 adds MailIdentity plus StoredMessage.deliveredTo and OutboxMessage.fromAddress; the existing primary is backfilled from MailConfig/KeyManager on first launch. e2ee-p2p gains detached signing (pgp_sign_detached), with its JNI surface split into pgp_jni.rs to stay under the 500-line limit. Alias claiming moves to AliasController and MIME building to MimeCodec to keep MailViewModel under the lint file-length limit. Requires the matching relay deploy (location_share_server f2c14f6).
Diff
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.ktindex 585e4d2142..b87b7a13a8 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt@@ -117,4 +117,9 @@ object Pgp { fun armorMessage(raw: ByteArray): String = PgpNative.nativePgpArmorMessage(raw)?.toUtf8String() ?: error("OpenPGP armor failed")++ /** Raw binary detached signature over [data] with the Ed25519 primary. */+ fun signDetached(armoredSecret: String, passphrase: String, data: ByteArray): ByteArray =+ PgpNative.nativePgpSignDetached(armoredSecret.toUtf8(), passphrase.toUtf8(), data)+ ?: error("OpenPGP detached signing failed") }
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.ktindex d695cea83a..cf1133e630 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt@@ -33,6 +33,11 @@ internal object PgpNative { verifierPublic: ByteArray, ): Array<ByteArray>? external fun nativePgpArmorMessage(raw: ByteArray): ByteArray?+ external fun nativePgpSignDetached(+ armoredSecret: ByteArray,+ passphrase: ByteArray,+ data: ByteArray,+ ): ByteArray? init { System.loadLibrary("e2ee_pqc")
library/e2ee-p2p/src/main/rust/src/lib.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/lib.rs b/library/e2ee-p2p/src/main/rust/src/lib.rsindex 2a1208b73c..8e197aebed 100644--- a/library/e2ee-p2p/src/main/rust/src/lib.rs+++ b/library/e2ee-p2p/src/main/rust/src/lib.rs@@ -240,6 +240,7 @@ pub fn mldsa_verify_der(pub_der: &[u8], msg: &[u8], sig: &[u8]) -> bool { mod jni_bridge; mod c_bridge; pub mod pgp;+mod pgp_jni; #[cfg(test)] mod tests;
library/e2ee-p2p/src/main/rust/src/pgp.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/pgp.rs b/library/e2ee-p2p/src/main/rust/src/pgp.rsindex 63b7419daa..0f9ef5dedb 100644--- a/library/e2ee-p2p/src/main/rust/src/pgp.rs+++ b/library/e2ee-p2p/src/main/rust/src/pgp.rs@@ -179,6 +179,24 @@ pub fn pgp_decrypt_verify( Some((payload, fingerprint)) } +/// Binary detached signature over `data` with the Ed25519 primary (SHA-512).+/// Returns the raw signature packet (used for relay SUB authentication).+pub fn pgp_sign_detached(armored_secret: &str, passphrase: &str, data: &[u8]) -> Option<Vec<u8>> {+ use pgp::composed::DetachedSignature;+ use pgp::ser::Serialize;+ let (secret, _) = SignedSecretKey::from_string(armored_secret).ok()?;+ DetachedSignature::sign_binary_data(+ OsRng,+ &secret.primary_key,+ &Password::from(passphrase),+ HashAlgorithm::Sha512,+ data,+ )+ .ok()?+ .to_bytes()+ .ok()+}+ /// Armor raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation). pub fn to_armored_message(raw: &[u8]) -> Option<String> { use base64::Engine;@@ -228,262 +246,3 @@ fn hex_upper(bytes: &[u8]) -> String { } out }--// ----------------------------------------------------------------------------// JNI surface for `com.vayunmathur.e2ee.PgpNative`.-// Armor crosses as UTF-8 bytes; ciphertext crosses as raw bytes.-// -----------------------------------------------------------------------------use jni::objects::{JByteArray, JClass};-use jni::sys::{jbyteArray, jobjectArray};-use jni::{Env, EnvUnowned};--fn jbytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> {- env.convert_byte_array(arr).ok()-}--fn jbytes_out(env: &mut Env, data: &[u8]) -> jbyteArray {- match env.byte_array_from_slice(data) {- Ok(a) => a.into_raw(),- Err(_) => std::ptr::null_mut(),- }-}--fn jstring_in(env: &mut Env, arr: &JByteArray) -> Option<String> {- let bytes = jbytes_in(env, arr)?;- String::from_utf8(bytes).ok()-}--fn jstring_out(env: &mut Env, s: &str) -> jbyteArray {- jbytes_out(env, s.as_bytes())-}--/// Return a Java `byte[][]` of exactly three elements (secret, public,-/// fingerprint), or null.-fn triple_out(env: &mut Env, a: &str, b: &str, c: &str) -> jobjectArray {- let arr = match env.new_object_type_array::<JByteArray>(3, JByteArray::null()) {- Ok(a) => a,- Err(_) => return std::ptr::null_mut(),- };- let items = [a.as_bytes(), b.as_bytes(), c.as_bytes()];- for (i, data) in items.iter().enumerate() {- let element = match env.byte_array_from_slice(data) {- Ok(x) => x,- Err(_) => return std::ptr::null_mut(),- };- if arr.set_element(env, i, &element).is_err() {- return std::ptr::null_mut();- }- }- arr.into_raw()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpGenerate<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- user_id: JByteArray<'l>,- passphrase: JByteArray<'l>,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let (uid, pw) = match (jstring_in(env, &user_id), jstring_in(env, &passphrase)) {- (Some(a), Some(b)) => (a, b),- _ => return Ok(std::ptr::null_mut()),- };- match pgp_generate(&uid, &pw) {- Some((secret, public, fp)) => Ok(triple_out(env, &secret, &public, &fp)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpFingerprint<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- armored_public: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let armor = match jstring_in(env, &armored_public) {- Some(a) => a,- None => return Ok(std::ptr::null_mut()),- };- match pgp_fingerprint(&armor) {- Some(fp) => Ok(jstring_out(env, &fp)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpNormalizeKey<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- input: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let bytes = match jbytes_in(env, &input) {- Some(b) => b,- None => return Ok(std::ptr::null_mut()),- };- match pgp_normalize_key(&bytes) {- Some(armor) => Ok(jstring_out(env, &armor)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncrypt<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- armored_public: JByteArray<'l>,- plaintext: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let (armor, plain) = match (- jstring_in(env, &armored_public),- jbytes_in(env, &plaintext),- ) {- (Some(a), Some(b)) => (a, b),- _ => return Ok(std::ptr::null_mut()),- };- match pgp_encrypt(&armor, &plain) {- Some(raw) => Ok(jbytes_out(env, &raw)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecrypt<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- armored_secret: JByteArray<'l>,- passphrase: JByteArray<'l>,- ciphertext: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let (armor, pw, ct) = match (- jstring_in(env, &armored_secret),- jstring_in(env, &passphrase),- jbytes_in(env, &ciphertext),- ) {- (Some(a), Some(b), Some(c)) => (a, b, c),- _ => return Ok(std::ptr::null_mut()),- };- match pgp_decrypt(&armor, &pw, &ct) {- Some(plain) => Ok(jbytes_out(env, &plain)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpArmorMessage<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- raw: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let bytes = match jbytes_in(env, &raw) {- Some(b) => b,- None => return Ok(std::ptr::null_mut()),- };- match to_armored_message(&bytes) {- Some(armor) => Ok(jstring_out(env, &armor)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--/// Encrypt + sign: recipient armor, sender secret armor (empty string = no-/// signing), sender passphrase, plaintext → raw PGP bytes or null.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncryptSigned<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- armored_public: JByteArray<'l>,- armored_secret: JByteArray<'l>,- passphrase: JByteArray<'l>,- plaintext: JByteArray<'l>,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let (armor, secret, pw, plain) = match (- jstring_in(env, &armored_public),- jstring_in(env, &armored_secret),- jstring_in(env, &passphrase),- jbytes_in(env, &plaintext),- ) {- (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),- _ => return Ok(std::ptr::null_mut()),- };- // Empty secret = encrypt-only (same as nativePgpEncrypt).- let signer = if secret.is_empty() {- None- } else {- Some((secret.as_str(), pw.as_str()))- };- match pgp_encrypt_signed(&armor, signer, &plain) {- Some(raw) => Ok(jbytes_out(env, &raw)),- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}--/// Decrypt + verify: secret armor, passphrase, ciphertext, verifier public-/// armor (empty string = no verification) → `byte[][]` [payload, fingerprint]-/// (fingerprint empty when unsigned/unverified) or null on failure/tamper.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecryptVerify<'l>(- mut env: EnvUnowned<'l>,- _class: JClass<'l>,- armored_secret: JByteArray<'l>,- passphrase: JByteArray<'l>,- ciphertext: JByteArray<'l>,- verifier_public: JByteArray<'l>,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let (secret, pw, ct, verifier) = match (- jstring_in(env, &armored_secret),- jstring_in(env, &passphrase),- jbytes_in(env, &ciphertext),- jstring_in(env, &verifier_public),- ) {- (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),- _ => return Ok(std::ptr::null_mut()),- };- let verifier_opt = if verifier.is_empty() { None } else { Some(verifier.as_str()) };- match pgp_decrypt_verify(&secret, &pw, &ct, verifier_opt) {- Some((payload, fp)) => {- let arr = match env.new_object_type_array::<JByteArray>(2, JByteArray::null()) {- Ok(a) => a,- Err(_) => return Ok(std::ptr::null_mut()),- };- let payload_arr = match env.byte_array_from_slice(&payload) {- Ok(x) => x,- Err(_) => return Ok(std::ptr::null_mut()),- };- let fp_arr = match env.byte_array_from_slice(fp.as_bytes()) {- Ok(x) => x,- Err(_) => return Ok(std::ptr::null_mut()),- };- if arr.set_element(env, 0, &payload_arr).is_err()- || arr.set_element(env, 1, &fp_arr).is_err()- {- return Ok(std::ptr::null_mut());- }- Ok(arr.into_raw())- }- None => Ok(std::ptr::null_mut()),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}
library/e2ee-p2p/src/main/rust/src/pgp_jni.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/pgp_jni.rs b/library/e2ee-p2p/src/main/rust/src/pgp_jni.rsnew file mode 100644index 0000000000..0bed120df3--- /dev/null+++ b/library/e2ee-p2p/src/main/rust/src/pgp_jni.rs@@ -0,0 +1,284 @@+//! JNI surface for `com.vayunmathur.e2ee.PgpNative`.+//! Armor crosses as UTF-8 bytes; ciphertext crosses as raw bytes.++use crate::pgp::*;++use jni::objects::{JByteArray, JClass};+use jni::sys::{jbyteArray, jobjectArray};+use jni::{Env, EnvUnowned};++fn jbytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> {+ env.convert_byte_array(arr).ok()+}++fn jbytes_out(env: &mut Env, data: &[u8]) -> jbyteArray {+ match env.byte_array_from_slice(data) {+ Ok(a) => a.into_raw(),+ Err(_) => std::ptr::null_mut(),+ }+}++fn jstring_in(env: &mut Env, arr: &JByteArray) -> Option<String> {+ let bytes = jbytes_in(env, arr)?;+ String::from_utf8(bytes).ok()+}++fn jstring_out(env: &mut Env, s: &str) -> jbyteArray {+ jbytes_out(env, s.as_bytes())+}++/// Return a Java `byte[][]` of exactly three elements (secret, public,+/// fingerprint), or null.+fn triple_out(env: &mut Env, a: &str, b: &str, c: &str) -> jobjectArray {+ let arr = match env.new_object_type_array::<JByteArray>(3, JByteArray::null()) {+ Ok(a) => a,+ Err(_) => return std::ptr::null_mut(),+ };+ let items = [a.as_bytes(), b.as_bytes(), c.as_bytes()];+ for (i, data) in items.iter().enumerate() {+ let element = match env.byte_array_from_slice(data) {+ Ok(x) => x,+ Err(_) => return std::ptr::null_mut(),+ };+ if arr.set_element(env, i, &element).is_err() {+ return std::ptr::null_mut();+ }+ }+ arr.into_raw()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpGenerate<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ user_id: JByteArray<'l>,+ passphrase: JByteArray<'l>,+) -> jobjectArray {+ env.with_env(|env| -> jni::errors::Result<jobjectArray> {+ let (uid, pw) = match (jstring_in(env, &user_id), jstring_in(env, &passphrase)) {+ (Some(a), Some(b)) => (a, b),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_generate(&uid, &pw) {+ Some((secret, public, fp)) => Ok(triple_out(env, &secret, &public, &fp)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpFingerprint<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let armor = match jstring_in(env, &armored_public) {+ Some(a) => a,+ None => return Ok(std::ptr::null_mut()),+ };+ match pgp_fingerprint(&armor) {+ Some(fp) => Ok(jstring_out(env, &fp)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpNormalizeKey<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ input: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let bytes = match jbytes_in(env, &input) {+ Some(b) => b,+ None => return Ok(std::ptr::null_mut()),+ };+ match pgp_normalize_key(&bytes) {+ Some(armor) => Ok(jstring_out(env, &armor)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncrypt<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+ plaintext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, plain) = match (+ jstring_in(env, &armored_public),+ jbytes_in(env, &plaintext),+ ) {+ (Some(a), Some(b)) => (a, b),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_encrypt(&armor, &plain) {+ Some(raw) => Ok(jbytes_out(env, &raw)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecrypt<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ ciphertext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, pw, ct) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &ciphertext),+ ) {+ (Some(a), Some(b), Some(c)) => (a, b, c),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_decrypt(&armor, &pw, &ct) {+ Some(plain) => Ok(jbytes_out(env, &plain)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpArmorMessage<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ raw: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let bytes = match jbytes_in(env, &raw) {+ Some(b) => b,+ None => return Ok(std::ptr::null_mut()),+ };+ match to_armored_message(&bytes) {+ Some(armor) => Ok(jstring_out(env, &armor)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Encrypt + sign: recipient armor, sender secret armor (empty string = no+/// signing), sender passphrase, plaintext → raw PGP bytes or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncryptSigned<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_public: JByteArray<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ plaintext: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (armor, secret, pw, plain) = match (+ jstring_in(env, &armored_public),+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &plaintext),+ ) {+ (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),+ _ => return Ok(std::ptr::null_mut()),+ };+ // Empty secret = encrypt-only (same as nativePgpEncrypt).+ let signer = if secret.is_empty() {+ None+ } else {+ Some((secret.as_str(), pw.as_str()))+ };+ match pgp_encrypt_signed(&armor, signer, &plain) {+ Some(raw) => Ok(jbytes_out(env, &raw)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Detached sign: secret armor, passphrase, data → raw signature packet or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpSignDetached<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ data: JByteArray<'l>,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let (secret, pw, bytes) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &data),+ ) {+ (Some(a), Some(b), Some(c)) => (a, b, c),+ _ => return Ok(std::ptr::null_mut()),+ };+ match pgp_sign_detached(&secret, &pw, &bytes) {+ Some(sig) => Ok(jbytes_out(env, &sig)),+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Decrypt + verify: secret armor, passphrase, ciphertext, verifier public+/// armor (empty string = no verification) → `byte[][]` [payload, fingerprint]+/// (fingerprint empty when unsigned/unverified) or null on failure/tamper.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecryptVerify<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ armored_secret: JByteArray<'l>,+ passphrase: JByteArray<'l>,+ ciphertext: JByteArray<'l>,+ verifier_public: JByteArray<'l>,+) -> jobjectArray {+ env.with_env(|env| -> jni::errors::Result<jobjectArray> {+ let (secret, pw, ct, verifier) = match (+ jstring_in(env, &armored_secret),+ jstring_in(env, &passphrase),+ jbytes_in(env, &ciphertext),+ jstring_in(env, &verifier_public),+ ) {+ (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),+ _ => return Ok(std::ptr::null_mut()),+ };+ let verifier_opt = if verifier.is_empty() { None } else { Some(verifier.as_str()) };+ match pgp_decrypt_verify(&secret, &pw, &ct, verifier_opt) {+ Some((payload, fp)) => {+ let arr = match env.new_object_type_array::<JByteArray>(2, JByteArray::null()) {+ Ok(a) => a,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ let payload_arr = match env.byte_array_from_slice(&payload) {+ Ok(x) => x,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ let fp_arr = match env.byte_array_from_slice(fp.as_bytes()) {+ Ok(x) => x,+ Err(_) => return Ok(std::ptr::null_mut()),+ };+ if arr.set_element(env, 0, &payload_arr).is_err()+ || arr.set_element(env, 1, &fp_arr).is_err()+ {+ return Ok(std::ptr::null_mut());+ }+ Ok(arr.into_raw())+ }+ None => Ok(std::ptr::null_mut()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}
library/e2ee-p2p/src/main/rust/src/pgp_tests.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/pgp_tests.rs b/library/e2ee-p2p/src/main/rust/src/pgp_tests.rsindex efac43ed66..117cf44d59 100644--- a/library/e2ee-p2p/src/main/rust/src/pgp_tests.rs+++ b/library/e2ee-p2p/src/main/rust/src/pgp_tests.rs@@ -71,6 +71,20 @@ fn signed_encrypt_verify_roundtrip() { assert_eq!(signer_fp, alice_fp, "signer fingerprint matches Alice"); } +#[test]+fn detached_signature_verifies_and_rejects_tamper() {+ use pgp::composed::{Deserializable, DetachedSignature, SignedPublicKey};+ let (secret, public, _) =+ pgp_generate("alias <[email protected]>", "pw12345678").expect("keygen");+ let data = b"maemail-sub-v1\[email protected]";+ let sig_bytes = pgp_sign_detached(&secret, "pw12345678", data).expect("sign");+ let sig = DetachedSignature::from_bytes(&sig_bytes[..]).expect("parse sig");+ let (key, _) = SignedPublicKey::from_string(&public).expect("parse key");+ assert!(sig.verify(&key.primary_key, data).is_ok(), "verifies over exact bytes");+ assert!(sig.verify(&key.primary_key, b"other bytes").is_err(), "tamper rejected");+ assert!(pgp_sign_detached(&secret, "wrong", data).is_none(), "wrong passphrase");+}+ #[test] fn unsigned_message_verifies_empty_but_decrypts() { let (alice_secret, alice_public, _) =
securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.ktindex 256c3933e1..e12f69b02e 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt@@ -135,6 +135,7 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) { to = m.from, subject = "Re: ${m.decryptedSubject ?: ""}", inReplyTo = m.id,+ from = m.deliveredTo, ), ) },@@ -144,8 +145,12 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) { } outEntry(viewModel, backStack) entry<Route.Settings>(metadata = SiblingPage()) {+ val identities by viewModel.identities.collectAsState(emptyList()) SettingsScreen( state = state,+ identities = identities,+ onCreateAlias = viewModel::createAlias,+ onSetAliasDisabled = viewModel::setAliasDisabled, onExportPublicKey = viewModel::exportPublicKey, onForget = viewModel::forgetIdentity, onDismissMessages = viewModel::dismissMessages,@@ -167,14 +172,19 @@ private fun EntryProviderScope<Route>.composerEntry(viewModel: MailViewModel, ba to = AddressValidator.parseRecipients(route.to), cc = AddressValidator.parseRecipients(route.cc), bcc = AddressValidator.parseRecipients(route.bcc),+ from = route.from, ) } fun close() { viewModel.clearDraft() backStack.pop() }+ val identities by viewModel.identities.collectAsState(emptyList()) ComposeScreen( state = viewModel.state,+ identities = identities.filter { !it.disabled },+ draftFrom = viewModel.draftFrom,+ onSelectFrom = { viewModel.draftFrom = it }, draftTo = viewModel.draftTo, draftCc = viewModel.draftCc, draftBcc = viewModel.draftBcc,@@ -190,6 +200,7 @@ private fun EntryProviderScope<Route>.composerEntry(viewModel: MailViewModel, ba subject = subject, body = body, inReplyTo = inReplyTo,+ from = viewModel.draftFrom, onDone = { sent -> if (sent) { viewModel.drafts.delete(draftId)@@ -227,6 +238,7 @@ private fun saveOrDropDraft( subject = subject, body = body, inReplyTo = inReplyTo,+ from = viewModel.draftFrom, ) if (draft.isEmpty) { viewModel.drafts.delete(draftId)@@ -255,6 +267,7 @@ private fun EntryProviderScope<Route>.outEntry(viewModel: MailViewModel, backSta body = d.body, inReplyTo = d.inReplyTo, draftId = d.id,+ from = d.from, ), ) },
securemail/src/main/java/com/vayunmathur/securemail/Route.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt b/securemail/src/main/java/com/vayunmathur/securemail/Route.ktindex 5dfe2ef0d6..efc493ba7d 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Route.kt@@ -29,6 +29,8 @@ sealed interface Route : NavKey { val draftId: String? = null, val cc: String = "", val bcc: String = "",+ /** Own address (primary or alias) to send from; null = primary. */+ val from: String? = null, ) : Route @Serializable
securemail/src/main/java/com/vayunmathur/securemail/data/Identities.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/Identities.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/Identities.ktnew file mode 100644index 0000000000..f2ad501b92--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/Identities.kt@@ -0,0 +1,60 @@+package com.vayunmathur.securemail.data++import android.content.Context+import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import com.vayunmathur.securemail.platform.crypto.KeyManager+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/** Own-address lookups shared by the service, sync worker, inbound path and ViewModel. */+object Identities {++ private val migrateLock = Mutex()++ /**+ * Backfills the primary [MailIdentity] for installs that predate aliases+ * (identity in [MailConfig] + secret in [KeyManager]). Idempotent.+ */+ suspend fun ensureMigrated(context: Context) {+ val app = context.applicationContext+ val dao = MailRepository.get(app).identityDao()+ if (dao.count() > 0) return+ migrateLock.withLock {+ if (dao.count() > 0) return+ val settings = MailConfig(app).settings.first()+ if (!settings.isConfigured) return+ val secret = runCatching { KeyManager(app).getSecretArmor() }.getOrNull() ?: return+ dao.upsert(+ MailIdentity(+ address = settings.address,+ publicArmor = settings.publicArmor,+ fingerprintHex = settings.fingerprintHex,+ secretArmor = secret,+ isPrimary = true,+ createdMillis = 0L,+ ),+ )+ }+ }++ suspend fun active(context: Context): List<MailIdentity> {+ ensureMigrated(context)+ return MailRepository.get(context.applicationContext).identityDao().active()+ }++ /** The identity a message was delivered to, falling back to the primary. */+ suspend fun forDelivery(context: Context, deliveredTo: String?): MailIdentity? {+ ensureMigrated(context)+ val dao = MailRepository.get(context.applicationContext).identityDao()+ return deliveredTo?.let { dao.get(it.lowercase()) } ?: dao.primary()+ }++ /** Signs a relay SUB challenge payload with [address]'s key; null when unavailable. */+ suspend fun sign(context: Context, address: String, payload: ByteArray): ByteArray? {+ val app = context.applicationContext+ val identity = MailRepository.get(app).identityDao().get(address) ?: return null+ val passphrase = KeyManager(app).getKeyPassphrase() ?: return null+ return runCatching { PgpCrypto.signDetached(identity.secretArmor, passphrase, payload) }.getOrNull()+ }+}
securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.ktindex dba9840ce5..626f0c7a8d 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt@@ -6,7 +6,6 @@ import com.vayunmathur.securemail.domain.mail.MimeCodec import com.vayunmathur.securemail.domain.pgp.PgpCrypto import com.vayunmathur.securemail.network.MailSocket import com.vayunmathur.securemail.platform.crypto.KeyManager-import kotlinx.coroutines.flow.first /** * Single choke point for inbound socket frames (relay MSG + SMTP-ingested@@ -18,45 +17,42 @@ import kotlinx.coroutines.flow.first object InboundStore { /**- * Stores one inbound frame. Encrypted frames decrypt on arrival (S2K- * passphrase loads transparently from Keystore-wrapped storage);+ * Stores one inbound frame. Encrypted frames decrypt on arrival with the+ * key of the own address they were delivered to (primary or alias); * unencrypted frames parse their MIME envelope directly; undecryptable * frames persist as locked blobs for later retry. The server spam verdict * ([MailSocket.MsgFlags.spam]) routes to the Spam folder — independent of * PGP signing (unsigned mail is accepted, not spam). */- suspend fun store(- context: Context,- id: String,- flags: MailSocket.MsgFlags,- raw: ByteArray,- ) {+ suspend fun store(context: Context, msg: MailSocket.InboundMsg) { val app = context.applicationContext val repo = MailRepository.get(app)- val settings = MailConfig(app).settings.first()- val keyManager = KeyManager(app)- val folder = if (flags.spam) MailFolder.SPAM else MailFolder.INBOX- if (flags.unencrypted) {+ val identity = Identities.forDelivery(app, msg.deliveredTo)+ val deliveredTo = msg.deliveredTo.ifBlank { identity?.address.orEmpty() }+ val folder = if (msg.flags.spam) MailFolder.SPAM else MailFolder.INBOX+ val raw = msg.raw+ if (msg.flags.unencrypted) { val (subject, body, from, html) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8)) repo.messageDao().upsert( StoredMessage(- id = id,+ id = msg.id, from = from,- toJson = settings.address,+ toJson = deliveredTo, dateMillis = System.currentTimeMillis(),- messageId = id,+ messageId = msg.id, blobBase64 = "", decryptedBody = body, decryptedSubject = subject, unencrypted = true, folder = folder, decryptedHtml = html,+ deliveredTo = deliveredTo, ), ) return }- val passphrase = keyManager.getKeyPassphrase()- val stored = if (passphrase != null) {+ val passphrase = KeyManager(app).getKeyPassphrase()+ val stored = if (passphrase != null && identity != null) { runCatching { val pgpB64 = MimeCodec.extractPgpPayloadB64(raw) val pgpBytes = if (pgpB64 != null) {@@ -70,7 +66,7 @@ object InboundStore { // the verifier key is only known after decryption. val provisional = PgpCrypto.decrypt( pgpBytes,- keyManager.getSecretArmor(),+ identity.secretArmor, passphrase, ).toString(Charsets.UTF_8) val (_, _, claimedFrom) = MimeCodec.parseMime(provisional)@@ -79,7 +75,7 @@ object InboundStore { if (senderKey != null) { val checked = PgpCrypto.decryptVerify( pgpBytes,- keyManager.getSecretArmor(),+ identity.secretArmor, passphrase, senderKey, )@@ -93,11 +89,11 @@ object InboundStore { } val (subject, body, from, html) = MimeCodec.parseMime(mime) StoredMessage(- id = id,+ id = msg.id, from = from,- toJson = settings.address,+ toJson = deliveredTo, dateMillis = System.currentTimeMillis(),- messageId = id,+ messageId = msg.id, blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP), decryptedBody = body, decryptedSubject = subject,@@ -105,6 +101,7 @@ object InboundStore { unencrypted = false, folder = folder, decryptedHtml = html,+ deliveredTo = deliveredTo, ) }.getOrNull() } else {@@ -112,14 +109,15 @@ object InboundStore { } repo.messageDao().upsert( stored ?: StoredMessage(- id = id,+ id = msg.id, from = "",- toJson = settings.address,+ toJson = deliveredTo, dateMillis = System.currentTimeMillis(),- messageId = id,+ messageId = msg.id, blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP), unencrypted = false, folder = folder,+ deliveredTo = deliveredTo, ), ) }
securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.ktindex 6651110bf1..fbb58d1632 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -52,6 +52,8 @@ data class StoredMessage( val folder: MailFolder = MailFolder.INBOX, /** Sender's HTML part, when the message had one (rendered by the reader). */ val decryptedHtml: String? = null,+ /** Own address (primary or alias) the relay delivered this to; null = primary. */+ val deliveredTo: String? = null, ) /** Cached public key for a recipient (own directory, WKD, or VKS result). */@@ -75,6 +77,25 @@ data class OutboxMessage( val createdMillis: Long, val lastError: String? = null, val attemptCount: Int = 0,+ /** Own address to send from; null = primary (rows queued before aliases). */+ val fromAddress: String? = null,+)++/**+ * One own address: the primary or an alias. Each has its own PGP key so+ * correspondents cannot link aliases by fingerprint. [secretArmor] is+ * S2K-wrapped by the shared recovery passphrase (and at rest in SQLCipher).+ */+@Entity+data class MailIdentity(+ @PrimaryKey val address: String,+ val label: String = "",+ val publicArmor: String,+ val fingerprintHex: String,+ val secretArmor: String,+ val isPrimary: Boolean = false,+ val disabled: Boolean = false,+ val createdMillis: Long, ) @Dao@@ -147,15 +168,43 @@ interface OutboxDao { suspend fun noteAttempt(rowId: Long, error: String) } +@Dao+interface IdentityDao {+ @Query("SELECT * FROM MailIdentity ORDER BY isPrimary DESC, createdMillis ASC")+ fun observeAll(): Flow<List<MailIdentity>>++ @Query("SELECT * FROM MailIdentity WHERE disabled = 0 ORDER BY isPrimary DESC, createdMillis ASC")+ suspend fun active(): List<MailIdentity>++ @Query("SELECT * FROM MailIdentity WHERE address = :address LIMIT 1")+ suspend fun get(address: String): MailIdentity?++ @Query("SELECT * FROM MailIdentity WHERE isPrimary = 1 LIMIT 1")+ suspend fun primary(): MailIdentity?++ @Query("SELECT COUNT(*) FROM MailIdentity")+ suspend fun count(): Int++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(identity: MailIdentity)++ @Query("UPDATE MailIdentity SET disabled = :disabled WHERE address = :address AND isPrimary = 0")+ suspend fun setDisabled(address: String, disabled: Boolean)++ @Query("DELETE FROM MailIdentity")+ suspend fun deleteAll()+}+ @Database(- entities = [StoredMessage::class, CachedKey::class, OutboxMessage::class],- version = 4,+ entities = [StoredMessage::class, CachedKey::class, OutboxMessage::class, MailIdentity::class],+ version = 5, exportSchema = false, ) abstract class MailDatabase : RoomDatabase() { abstract fun messageDao(): MessageDao abstract fun keyDao(): KeyDao abstract fun outboxDao(): OutboxDao+ abstract fun identityDao(): IdentityDao companion object : DatabaseMigrations { /**@@ -203,6 +252,33 @@ abstract class MailDatabase : RoomDatabase() { it.execSQL("ALTER TABLE StoredMessage ADD COLUMN decryptedHtml TEXT") } - override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)+ /**+ * v4 → v5: aliases. Adds the MailIdentity table plus nullable+ * `StoredMessage.deliveredTo` and `OutboxMessage.fromAddress` (null =+ * primary). The primary row is backfilled at runtime by+ * [com.vayunmathur.securemail.data.Identities.ensureMigrated] because+ * its secret lives in Keystore-wrapped prefs, not SQL.+ */+ private val MIGRATION_4_5 = Migration(4, 5) {+ it.execSQL(+ """+ CREATE TABLE IF NOT EXISTS `MailIdentity` (+ `address` TEXT NOT NULL PRIMARY KEY,+ `label` TEXT NOT NULL,+ `publicArmor` TEXT NOT NULL,+ `fingerprintHex` TEXT NOT NULL,+ `secretArmor` TEXT NOT NULL,+ `isPrimary` INTEGER NOT NULL,+ `disabled` INTEGER NOT NULL,+ `createdMillis` INTEGER NOT NULL+ )+ """.trimIndent(),+ )+ it.execSQL("ALTER TABLE StoredMessage ADD COLUMN deliveredTo TEXT")+ it.execSQL("ALTER TABLE OutboxMessage ADD COLUMN fromAddress TEXT")+ }++ override val migrations: List<Migration> =+ listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5) } }
securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.ktindex 18601e0132..5cdfe6f64c 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt@@ -13,6 +13,7 @@ class MailRepository private constructor(context: Context) : fun messageDao(): MessageDao = db.messageDao() fun keyDao(): KeyDao = db.keyDao() fun outboxDao(): OutboxDao = db.outboxDao()+ fun identityDao(): IdentityDao = db.identityDao() companion object { @Volatile private var instance: MailRepository? = null
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/AliasGenerator.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/AliasGenerator.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/AliasGenerator.ktnew file mode 100644index 0000000000..d14ce4f285--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/AliasGenerator.kt@@ -0,0 +1,37 @@+package com.vayunmathur.securemail.domain.mail++import java.security.SecureRandom+import java.util.Random++/** Readable random alias addresses: `[email protected]`. */+object AliasGenerator {++ private val ADJECTIVES = listOf(+ "amber", "ancient", "autumn", "bold", "brave", "bright", "brisk", "calm",+ "clever", "cosmic", "crimson", "crisp", "dapper", "dawn", "deep", "eager",+ "early", "fancy", "fern", "fleet", "fresh", "gentle", "glad", "golden",+ "grand", "happy", "hidden", "humble", "icy", "jolly", "keen", "kind",+ "lively", "lucky", "lunar", "mellow", "misty", "noble", "nimble", "olive",+ "plucky", "polar", "proud", "quick", "quiet", "rapid", "rustic", "sage",+ "sandy", "shiny", "silent", "silver", "sleek", "snowy", "solar", "steady",+ "sunny", "swift", "tidy", "velvet", "vivid", "warm", "wild", "witty",+ )++ private val NOUNS = listOf(+ "acorn", "badger", "beacon", "birch", "bison", "breeze", "brook", "canyon",+ "cedar", "comet", "coral", "crane", "delta", "dune", "eagle", "ember",+ "falcon", "fjord", "fox", "glade", "grove", "harbor", "hawk", "heron",+ "island", "lagoon", "lark", "lynx", "maple", "meadow", "mesa", "moose",+ "otter", "owl", "panda", "pebble", "pine", "plover", "prairie", "quail",+ "raven", "reef", "ridge", "river", "robin", "sparrow", "spruce", "stone",+ "summit", "swan", "thicket", "tiger", "trail", "tundra", "valley", "walrus",+ "willow", "wolf", "wren", "yak", "zebra", "aspen", "basin", "cliff",+ )++ fun generate(random: Random = SecureRandom()): String {+ val adjective = ADJECTIVES[random.nextInt(ADJECTIVES.size)]+ val noun = NOUNS[random.nextInt(NOUNS.size)]+ val number = 1000 + random.nextInt(9000)+ return "$adjective-$noun-$number@${AddressValidator.OWN_DOMAIN}"+ }+}
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.ktindex 9279dfef31..0ab5af166f 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt@@ -7,6 +7,56 @@ package com.vayunmathur.securemail.domain.mail */ object MimeCodec { + fun newMessageId(): String = "${java.util.UUID.randomUUID()}@${AddressValidator.OWN_DOMAIN}"++ /**+ * Minimal text/plain body with protected headers. The sending address goes+ * in `From:` so recipients resolve the right (per-alias) key to verify.+ */+ fun buildPlainBody(from: String, subject: String, body: String, messageId: String): ByteArray {+ val safeSubject = subject.replace(Regex("[\\r\\n]"), " ")+ return (+ "From: $from\r\n" ++ "Subject: $safeSubject\r\n" ++ "Message-ID: <$messageId>\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: text/plain; charset=utf-8; protected-headers=\"v1\"\r\n" ++ "Content-Transfer-Encoding: 8bit\r\n" ++ "\r\n" ++ "$body\r\n"+ ).toByteArray(Charsets.UTF_8)+ }++ /**+ * Wraps an armored PGP MESSAGE in the RFC 3156 multipart/encrypted envelope:+ * control part (`application/pgp-encrypted`, `Version: 1`) + data part.+ * §4 requires the data part to be armored — Proton, GnuPG and Thunderbird+ * reject bare base64 there.+ */+ fun buildEncryptedEnvelope(armoredMessage: String): ByteArray {+ val boundary = "maemail-${java.util.UUID.randomUUID().toString().take(8)}"+ val armored = armoredMessage.trimEnd().lines().joinToString("\r\n")+ return (+ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/encrypted; boundary=\"$boundary\"; " ++ "protocol=\"application/pgp-encrypted\"\r\n" ++ "\r\n" ++ "--$boundary\r\n" ++ "Content-Type: application/pgp-encrypted\r\n" ++ "Content-Description: PGP/MIME version identification\r\n" ++ "\r\n" ++ "Version: 1\r\n" ++ "\r\n" ++ "--$boundary\r\n" ++ "Content-Type: application/octet-stream; name=\"encrypted.asc\"\r\n" ++ "Content-Description: OpenPGP encrypted message\r\n" ++ "Content-Disposition: inline; filename=\"encrypted.asc\"\r\n" ++ "\r\n" ++ "$armored\r\n" ++ "--$boundary--\r\n"+ ).toByteArray(Charsets.UTF_8)+ }+ /** * Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope * as base64. The data part is normally an ASCII-armored `PGP MESSAGE`
securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.ktindex 83e0982cf0..fcbc825a89 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt@@ -87,4 +87,8 @@ object PgpCrypto { /** Armors raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation). */ fun armorMessage(raw: ByteArray): String = Pgp.armorMessage(raw)++ /** Raw detached signature over [data] (relay SUB challenge). */+ fun signDetached(armoredSecret: String, passphrase: String, data: ByteArray): ByteArray =+ Pgp.signDetached(armoredSecret, passphrase, data) }
securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.ktindex b8311f1389..722a5e98cb 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt@@ -19,30 +19,30 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json /**- * Live-socket mail relay, mirroring FindFamily's binary wire design:+ * Live-socket mail relay (protocol v2), mirroring FindFamily's binary wire design: * * ```- * client→server SUB : [0x01][u16 addrLen][address UTF-8][armored public key…]- * client→server PUB : [0x02][flags][u16 rcptLen][recipient UTF-8][raw PGP/MIME…]- * client→server GETKEY : [0x04][u16 addrLen][address UTF-8]- * client→server FETCH : [0x06][u16 idLen][message id UTF-8]- * server→client MSG : [0x03][flags][u32 blobLen][message id UTF-8][raw PGP/MIME…]- * server→client KEYRESP : [0x05][status][u16 addrLen][address UTF-8][armored public key…]- * server→client FETCHED : [0x07][u16 idLen][message id UTF-8][u32 blobLen][raw PGP/MIME…]+ * server→client CHALLENGE : [0x08][32B nonce]+ * client→server SUB : [0x01][u16 addrLen][address][u16 sigLen][detached sig][armored public key…]+ * server→client SUBRESP : [0x09][status][u16 addrLen][address]+ * client→server PUB : [0x02][flags][u16 fromLen][from][u16 rcptLen][recipient][raw PGP/MIME…]+ * client→server GETKEY : [0x04][u16 addrLen][address UTF-8]+ * client→server FETCH : [0x06][u16 idLen][message id UTF-8]+ * server→client MSG : [0x03][flags][u32 idLen][id][u16 rcptLen][delivered-to][raw PGP/MIME…]+ * server→client KEYRESP : [0x05][status][u16 addrLen][address UTF-8][armored public key…]+ * server→client FETCHED : [0x07][u16 idLen][message id UTF-8][raw PGP/MIME…] * ``` * * flags bit0: 0 = encrypted PGP/MIME, 1 = unencrypted fallback (explicit opt-in only). * flags bit1: 0 = ham, 1 = spam (SPF/DKIM/DMARC failed at receipt; independent * of PGP signing — unsigned mail is accepted, not spam). * KEYRESP status: 0 = none, 1 = found (key follows).+ * SUBRESP status: see [SUB_OK]…[SUB_INVALID]. *- * SUB doubles as registration (address claim + public-key publish), exactly like- * FindFamily's SUB-carries-bundle: a socket-only client never needs separate- * HTTP register/getkey endpoints. The server fans out to live subscribers and- * durably queues for offline recipients; each SUB drains the recipient's backlog.- *- * Everything on the wire is framed binary — no JSON, no base64 — converted only- * at the HTTP-federation boundary server-side and the DB boundary client-side.+ * SUB authenticates one own address (primary or alias) by signing+ * `"maemail-sub-v1\0" || nonce || address` with that address's key; the first+ * SUB pins the key server-side. One socket SUBs every active identity, and the+ * server only accepts PUB from addresses this socket authenticated. */ object MailSocket { @@ -55,19 +55,35 @@ object MailSocket { const val OP_GETKEY_RESP: Byte = 0x05 const val OP_FETCH_REQ: Byte = 0x06 const val OP_FETCH_RESP: Byte = 0x07+ const val OP_CHALLENGE: Byte = 0x08+ const val OP_SUBRESP: Byte = 0x09 const val FLAG_PLAIN: Byte = 0x01 /** Spam flag: SPF/DKIM/DMARC verification failed at receipt (routes to Spam). */ const val FLAG_SPAM: Byte = 0x02 + const val SUB_OK = 0+ const val SUB_TAKEN = 1+ const val SUB_BAD_SIG = 2+ const val SUB_RATE_LIMITED = 3+ const val SUB_INVALID = 4++ private val SUB_CONTEXT = "maemail-sub-v1\u0000".toByteArray(Charsets.UTF_8)+ const val NONCE_LEN = 32+ /** Decoded MSG frame flags (bit0 = plaintext shape, bit1 = server spam verdict). */ data class MsgFlags(val unencrypted: Boolean, val spam: Boolean) + /** One decoded MSG frame. [deliveredTo] is the own address it was routed to. */+ class InboundMsg(val id: String, val flags: MsgFlags, val deliveredTo: String, val raw: ByteArray)+ const val KEY_NONE = 0 const val KEY_FOUND = 1 const val GETKEY_TIMEOUT_MS = 8_000L const val FETCH_TIMEOUT_MS = 15_000L+ const val SUB_TIMEOUT_MS = 10_000L+ const val CHALLENGE_TIMEOUT_MS = 10_000L const val PING_INTERVAL_MS = 30_000L const val LIVENESS_TIMEOUT_MS = 75_000L @@ -84,6 +100,12 @@ object MailSocket { /** In-flight fetches keyed by message id, completed on FETCHED. */ internal val pendingFetches = ConcurrentHashMap<String, CompletableDeferred<ByteArray?>>() + /** In-flight [claim]s keyed by lowercase address, completed on SUBRESP. */+ internal val pendingSubs = ConcurrentHashMap<String, CompletableDeferred<Int>>()++ /** This session's CHALLENGE nonce (null until received). */+ @Volatile private var nonce: ByteArray? = null+ @Volatile internal var session: WsSession? = null private set(value) { field = value@@ -99,17 +121,21 @@ object MailSocket { data class KeyResult(val address: String, val armoredPublic: String?) + data class IdentitySnapshot(val address: String, val armoredPublic: String)+ /**- * Start (no-op if running) the persistent relay loop. [identity] supplies the- * address + public key for every (re)SUB so registration self-heals.- * [onMessage] receives each inbound MSG frame's (id, flags, raw blob);+ * Start (no-op if running) the persistent relay loop. On every (re)connect+ * each of [identities] is SUBbed with a challenge signature from [sign], so+ * registration self-heals; the socket stays up with zero identities so+ * onboarding can [claim]. [onMessage] receives each inbound MSG frame; * [onBump] fires on any inbound frame to refresh UI/sync state. */ @Synchronized fun start( scope: CoroutineScope,- identity: suspend () -> IdentitySnapshot?,- onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit,+ identities: suspend () -> List<IdentitySnapshot>,+ sign: suspend (address: String, payload: ByteArray) -> ByteArray?,+ onMessage: suspend (InboundMsg) -> Unit, onBump: () -> Unit = {}, ) { if (loop?.isActive == true) return@@ -123,24 +149,26 @@ object MailSocket { // mail.maemail.org is a pinned first-party host → platform trust is // wrong here; the app inits NetworkClient with FIRST_PARTY. webSocket(WS_URL) {- session = this- val id = identity()- if (id == null) {- Log.status(TAG, "no identity; waiting for onboarding")- delay(BACKOFF_MAX_MS)- return@webSocket+ val ws = this+ supervise(conn, outer, onMessage, onBump) { challenge ->+ nonce = challenge+ for (id in identities()) {+ val sig = sign(id.address, subPayload(challenge, id.address))+ if (sig == null) {+ Log.status(TAG, "cannot sign SUB for ${id.address}")+ continue+ }+ send(subFrame(id.address, sig, id.armoredPublic))+ }+ // Publish only after the SUBs are on the wire: the server+ // processes frames in order, so any PUB lands authenticated.+ session = ws+ backoff = BACKOFF_INITIAL_MS }- send(subFrame(id.address, id.armoredPublic))- backoff = BACKOFF_INITIAL_MS- supervise(conn, outer, onMessage, onBump) } }.onFailure { Log.status(TAG, "relay loop error", it) } conn.cancel()- session = null- pendingKeys.values.forEach { it.complete(null) }- pendingKeys.clear()- pendingFetches.values.forEach { it.complete(null) }- pendingFetches.clear()+ clearSession() if (!isActive) break delay(backoff) backoff = (backoff * 2).coerceAtMost(BACKOFF_MAX_MS)@@ -150,22 +178,52 @@ object MailSocket { @Synchronized fun stop() {- loop?.cancel(); loop = null; session = null+ loop?.cancel(); loop = null+ clearSession()+ }++ private fun clearSession() {+ session = null+ nonce = null pendingKeys.values.forEach { it.complete(null) } pendingKeys.clear() pendingFetches.values.forEach { it.complete(null) } pendingFetches.clear()+ pendingSubs.values.forEach { it.cancel() }+ pendingSubs.clear() } - /** Publish an already-encrypted PGP/MIME blob to [recipient]. False when offline. */- suspend fun publish(recipient: String, raw: ByteArray, unencrypted: Boolean = false): Boolean {+ /**+ * Claims (or re-authenticates) [address] on the live session: signs this+ * session's challenge via [sign] and waits for SUBRESP. Returns the+ * [SUB_OK]…[SUB_INVALID] status, or null when offline / timed out.+ */+ suspend fun claim(address: String, armoredPublic: String, sign: suspend (ByteArray) -> ByteArray): Int? {+ val s = session ?: return null+ val n = nonce ?: return null+ val key = address.lowercase()+ val deferred = CompletableDeferred<Int>()+ pendingSubs[key] = deferred+ return try {+ s.send(subFrame(key, sign(subPayload(n, key)), armoredPublic))+ withTimeoutOrNull(SUB_TIMEOUT_MS) { deferred.await() }+ } catch (e: Exception) {+ Log.status(TAG, "claim failed for $address", e)+ null+ } finally {+ pendingSubs.remove(key)+ }+ }++ /** Publish an already-built PGP/MIME blob [from] an own address to [recipient]. False when offline. */+ suspend fun publish(from: String, recipient: String, raw: ByteArray, unencrypted: Boolean = false): Boolean { val s = session if (s == null) { lastPublishError = "no session (relay offline)" return false } return runCatching {- s.send(pubFrame(recipient, raw, unencrypted))+ s.send(pubFrame(from, recipient, raw, unencrypted)) lastPublishError = null true }.onFailure {@@ -222,27 +280,38 @@ object MailSocket { // Session internals // ------------------------------------------------------------------ - data class IdentitySnapshot(val address: String, val armoredPublic: String)- private suspend fun WsSession.supervise( conn: CoroutineScope, outer: CoroutineScope,- onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit,+ onMessage: suspend (InboundMsg) -> Unit, onBump: () -> Unit,+ onChallenge: suspend WsSession.(ByteArray) -> Unit, ) { var lastInbound = System.currentTimeMillis()+ val challenge = CompletableDeferred<ByteArray>() conn.launch { runCatching { incoming.collect { frame -> lastInbound = System.currentTimeMillis() if (frame is WebSocketClient.WsFrame.Binary) {- dispatch(frame.bytes, onMessage)+ val bytes = frame.bytes+ if (bytes.firstOrNull() == OP_CHALLENGE && bytes.size == 1 + NONCE_LEN) {+ challenge.complete(bytes.copyOfRange(1, bytes.size))+ } else {+ dispatch(bytes, onMessage)+ } } runCatching { onBump() } } } } try {+ val n = withTimeoutOrNull(CHALLENGE_TIMEOUT_MS) { challenge.await() }+ if (n == null) {+ Log.status(TAG, "no CHALLENGE from relay, reconnecting")+ return+ }+ onChallenge(n) while (outer.isActive) { conn.launch { runCatching { ping() } } delay(PING_INTERVAL_MS)@@ -257,14 +326,16 @@ object MailSocket { } } - internal suspend fun dispatch(- buf: ByteArray,- onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit,- ) {+ internal suspend fun dispatch(buf: ByteArray, onMessage: suspend (InboundMsg) -> Unit) { when (buf.firstOrNull()) {- OP_MSG -> {- val parsed = parseMsg(buf) ?: return- onMessage(parsed.first, parsed.second, parsed.third)+ OP_MSG -> parseMsg(buf)?.let { onMessage(it) }+ OP_SUBRESP -> parseSubResp(buf)?.let { (addr, status) ->+ val waiter = pendingSubs.remove(addr.lowercase())+ if (waiter != null) {+ waiter.complete(status)+ } else if (status != SUB_OK) {+ Log.status(TAG, "relay rejected SUB for $addr (status $status)")+ } } OP_GETKEY_RESP -> parseKeyResp(buf)?.let { (addr, key) -> pendingKeys.remove(addr.lowercase())?.complete(KeyResult(addr, key))@@ -280,25 +351,34 @@ object MailSocket { // Framing // ------------------------------------------------------------------ - internal fun subFrame(address: String, armoredPublic: String): ByteArray {+ /** The exact bytes a SUB signature covers (must match the server's `sub_payload`). */+ internal fun subPayload(nonce: ByteArray, address: String): ByteArray =+ SUB_CONTEXT + nonce + address.lowercase().toByteArray(Charsets.UTF_8)++ internal fun subFrame(address: String, signature: ByteArray, armoredPublic: String): ByteArray { val addr = address.lowercase().toByteArray(Charsets.UTF_8) val key = armoredPublic.toByteArray(Charsets.UTF_8)- val out = ByteArray(1 + 2 + addr.size + key.size)+ val out = ByteArray(1 + 2 + addr.size + 2 + signature.size + key.size) out[0] = OP_SUB putU16(out, 1, addr.size) addr.copyInto(out, 3)- key.copyInto(out, 3 + addr.size)+ putU16(out, 3 + addr.size, signature.size)+ signature.copyInto(out, 5 + addr.size)+ key.copyInto(out, 5 + addr.size + signature.size) return out } - internal fun pubFrame(recipient: String, raw: ByteArray, unencrypted: Boolean): ByteArray {+ internal fun pubFrame(from: String, recipient: String, raw: ByteArray, unencrypted: Boolean): ByteArray {+ val sender = from.lowercase().toByteArray(Charsets.UTF_8) val rcpt = recipient.lowercase().toByteArray(Charsets.UTF_8)- val out = ByteArray(1 + 1 + 2 + rcpt.size + raw.size)+ val out = ByteArray(1 + 1 + 2 + sender.size + 2 + rcpt.size + raw.size) out[0] = OP_PUB out[1] = if (unencrypted) FLAG_PLAIN else 0- putU16(out, 2, rcpt.size)- rcpt.copyInto(out, 4)- raw.copyInto(out, 4 + rcpt.size)+ putU16(out, 2, sender.size)+ sender.copyInto(out, 4)+ putU16(out, 4 + sender.size, rcpt.size)+ rcpt.copyInto(out, 6 + sender.size)+ raw.copyInto(out, 6 + sender.size + rcpt.size) return out } @@ -320,8 +400,8 @@ object MailSocket { return out } - /** MSG: [0x03][flags][u32 blobLen][id UTF-8][raw…] → (id, flags, raw). */- internal fun parseMsg(buf: ByteArray): Triple<String, MsgFlags, ByteArray>? {+ /** MSG: [0x03][flags][u32 idLen][id][u16 rcptLen][rcpt][raw…]. */+ internal fun parseMsg(buf: ByteArray): InboundMsg? { if (buf.size < 1 + 1 + 4 + 2) return null val flags = buf[1].toInt() and 0xFF val parsed = MsgFlags(@@ -329,10 +409,23 @@ object MailSocket { spam = (flags and FLAG_SPAM.toInt()) != 0, ) val idLen = readU32(buf, 2)- if (idLen < 0 || buf.size < 6 + idLen) return null+ if (idLen < 0 || buf.size < 6 + idLen + 2) return null val id = buf.copyOfRange(6, 6 + idLen).toString(Charsets.UTF_8)- val raw = buf.copyOfRange(6 + idLen, buf.size)- return Triple(id, parsed, raw)+ val rcptOff = 6 + idLen+ val rcptLen = readU16(buf, rcptOff)+ if (buf.size < rcptOff + 2 + rcptLen) return null+ val rcpt = buf.copyOfRange(rcptOff + 2, rcptOff + 2 + rcptLen).toString(Charsets.UTF_8)+ val raw = buf.copyOfRange(rcptOff + 2 + rcptLen, buf.size)+ return InboundMsg(id, parsed, rcpt, raw)+ }++ /** SUBRESP: [0x09][status][u16 addrLen][address] → (address, status). */+ internal fun parseSubResp(buf: ByteArray): Pair<String, Int>? {+ if (buf.size < 1 + 1 + 2) return null+ val status = buf[1].toInt() and 0xFF+ val addrLen = readU16(buf, 2)+ if (buf.size < 4 + addrLen) return null+ return buf.copyOfRange(4, 4 + addrLen).toString(Charsets.UTF_8) to status } /** KEYRESP: [0x05][status][u16 addrLen][address][key…] → (address, key?). */
securemail/src/main/java/com/vayunmathur/securemail/platform/AliasController.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/AliasController.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/AliasController.ktnew file mode 100644index 0000000000..e1baaed426--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/AliasController.kt@@ -0,0 +1,68 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.MailRepository+import com.vayunmathur.securemail.domain.mail.AliasGenerator+import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import com.vayunmathur.securemail.network.MailSocket+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withTimeoutOrNull++/**+ * Claims own addresses (the primary at onboarding, random aliases later) over+ * the relay socket. Each address gets its own keypair so correspondents cannot+ * link aliases by fingerprint; nothing is stored unless the relay accepts the+ * signed SUB. Call from Dispatchers.IO.+ */+class AliasController(private val repo: MailRepository) {++ /** Waits briefly for the relay session (CHALLENGE received + SUBs sent). */+ suspend fun awaitRelay(): Boolean? =+ withTimeoutOrNull(RELAY_WAIT_MS) { MailSocket.connectedFlow.first { it } }++ /**+ * Generates a keypair for [address], claims it and stores it. Returns null+ * when the address is taken; throws on any other relay outcome.+ */+ suspend fun claim(address: String, passphrase: String, label: String, isPrimary: Boolean): MailIdentity? {+ val key = PgpCrypto.generateIdentity("$address <$address>", passphrase)+ val status = MailSocket.claim(address, key.armoredPublic) {+ PgpCrypto.signDetached(key.armoredSecret, passphrase, it)+ }+ when (status) {+ MailSocket.SUB_OK -> Unit+ MailSocket.SUB_TAKEN -> return null+ MailSocket.SUB_RATE_LIMITED -> error("Too many new addresses from this network. Try again later.")+ null -> error("Relay did not respond — try again.")+ else -> error("Relay rejected the address (code $status).")+ }+ val identity = MailIdentity(+ address = address,+ label = label,+ publicArmor = key.armoredPublic,+ fingerprintHex = key.fingerprintHex,+ secretArmor = key.armoredSecret,+ isPrimary = isPrimary,+ createdMillis = System.currentTimeMillis(),+ )+ repo.identityDao().upsert(identity)+ return identity+ }++ /** Claims a random readable alias, retrying on collisions. Returns its address. */+ suspend fun createRandom(passphrase: String, label: String): String {+ if (!MailSocket.connected) error("Relay offline — try again when connected.")+ repeat(ALIAS_ATTEMPTS) {+ val address = AliasGenerator.generate()+ if (repo.identityDao().get(address) == null) {+ claim(address, passphrase, label.trim(), isPrimary = false)?.let { return it.address }+ }+ }+ error("Couldn't find a free alias — try again.")+ }++ private companion object {+ const val RELAY_WAIT_MS = 15_000L+ const val ALIAS_ATTEMPTS = 5+ }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.ktindex 999a96c05b..3cf32afa48 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt@@ -20,6 +20,8 @@ data class Draft( val subject: String = "", val body: String = "", val inReplyTo: String? = null,+ /** Own address to send from; null = primary. */+ val from: String? = null, ) { val isEmpty: Boolean get() = to.isEmpty() && cc.isEmpty() && bcc.isEmpty() && subject.isBlank() && body.isBlank()@@ -43,7 +45,7 @@ class DraftsController( repo.messageDao().upsert( StoredMessage( id = draft.id,- from = ownAddress(),+ from = draft.from ?: ownAddress(), toJson = json.encodeToString(Envelope(draft.to, draft.cc, draft.bcc, draft.inReplyTo)), dateMillis = System.currentTimeMillis(), messageId = draft.id,@@ -83,6 +85,7 @@ class DraftsController( subject = row.decryptedSubject.orEmpty(), body = row.decryptedBody.orEmpty(), inReplyTo = env.inReplyTo,+ from = row.from.ifBlank { null }, ) } }
securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.ktindex 27890a5f52..1997087967 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt@@ -5,6 +5,7 @@ import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.vayunmathur.library.log.Log import com.vayunmathur.library.work.startRepeatedTask+import com.vayunmathur.securemail.data.Identities import com.vayunmathur.securemail.data.InboundStore import com.vayunmathur.securemail.data.MailConfig import com.vayunmathur.securemail.network.MailSocket@@ -35,12 +36,12 @@ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWork // persists for the worker's lifetime and idles. MailSocket.start( scope = CoroutineScope(Dispatchers.IO + SupervisorJob()),- identity = {- MailSocket.IdentitySnapshot(settings.address, settings.publicArmor)- },- onMessage = { id, flags, raw ->- InboundStore.store(applicationContext, id, flags, raw)+ identities = {+ Identities.active(applicationContext)+ .map { MailSocket.IdentitySnapshot(it.address, it.publicArmor) } },+ sign = { address, payload -> Identities.sign(applicationContext, address, payload) },+ onMessage = { msg -> InboundStore.store(applicationContext, msg) }, ) // Give the SUB + backlog drain time to complete within the worker. kotlinx.coroutines.delay(20_000)
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktindex e1431e31b3..13443242c7 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -11,8 +11,10 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics import com.vayunmathur.library.log.Log import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.data.Identities import com.vayunmathur.securemail.data.MailConfig import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity import com.vayunmathur.securemail.data.MailRepository import com.vayunmathur.securemail.data.OutboxMessage import com.vayunmathur.securemail.data.SenderKeys@@ -20,6 +22,7 @@ import com.vayunmathur.securemail.data.StoredMessage import com.vayunmathur.securemail.domain.mail.AddressValidator import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy import com.vayunmathur.securemail.domain.mail.MessageEnvelope+import com.vayunmathur.securemail.domain.mail.MimeCodec import com.vayunmathur.securemail.domain.pgp.PgpCrypto import com.vayunmathur.securemail.network.KeyLookupHttp import com.vayunmathur.securemail.network.MailSocket@@ -76,7 +79,10 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { val messages = repo.messageDao().observeAll() val outboxCount = repo.outboxDao().observeCount() val outboxMessages = repo.outboxDao().observeAll()- val drafts = DraftsController(repo, viewModelScope) { state.address }+ /** Own addresses: primary first, then aliases by creation time. */+ val identities = repo.identityDao().observeAll()+ val drafts = DraftsController(repo, viewModelScope) { draftFrom ?: state.address }+ private val aliases = AliasController(repo) /** * Selected folder driving the message list (drawer selection). Outbox is@@ -111,11 +117,20 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { var draftBcc by mutableStateOf(listOf<String>()) private set - /** Seeds the draft recipients (reply prefill, share-intent entry, reopened draft). */- fun seedDraft(to: List<String> = emptyList(), cc: List<String> = emptyList(), bcc: List<String> = emptyList()) {+ /** Own address the draft sends from; null = primary. */+ var draftFrom by mutableStateOf<String?>(null)++ /** Seeds the draft recipients and sender (reply prefill, share-intent entry, reopened draft). */+ fun seedDraft(+ to: List<String> = emptyList(),+ cc: List<String> = emptyList(),+ bcc: List<String> = emptyList(),+ from: String? = null,+ ) { draftTo = to.filter { it.isNotBlank() }.distinct() draftCc = cc.filter { it.isNotBlank() }.distinct() draftBcc = bcc.filter { it.isNotBlank() }.distinct()+ draftFrom = from?.takeIf { it.isNotBlank() } } /** Clears the draft after a successful send. */@@ -123,6 +138,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { draftTo = emptyList() draftCc = emptyList() draftBcc = emptyList()+ draftFrom = null } /** Adds a recipient chip to To/Cc/Bcc (0/1/2); returns false when invalid/duplicate. */@@ -202,6 +218,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { MailSocket.connectedFlow .onEach { up -> state = state.copy(socketConnected = up) } .launchIn(viewModelScope)+ viewModelScope.launch(Dispatchers.IO) { Identities.ensureMigrated(getApplication()) } } // ------------------------------------------------------------------@@ -209,9 +226,11 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { // ------------------------------------------------------------------ /**- * Generates the PGP identity, claims the address over the socket, persists.- * On success the caller must run the biometric gate immediately ([onClaimed]- * → `unlockIfReady`): protection enrolls at setup, not on next launch.+ * Generates the PGP identity and claims the address over the relay socket+ * (signed SUB). Nothing is persisted unless the relay accepts the claim, so+ * a taken address can never be silently overwritten. On success the caller+ * must run the biometric gate immediately ([onClaimed] → `unlockIfReady`):+ * protection enrolls at setup, not on next launch. */ fun claimAddress( localPart: String,@@ -231,20 +250,17 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { viewModelScope.launch { val outcome = withContext(Dispatchers.IO) { runCatching {- val identity = PgpCrypto.generateIdentity(- "$address <$address>",- passphrase,- )- keyManager.storeSecretArmor(identity.armoredSecret)- // Seal the S2K passphrase in Keystore-wrapped storage now:- // S2K runs transparently after this and is never asked for- // again (the passphrase is still the recovery secret).+ MailSocketService.start(getApplication())+ aliases.awaitRelay() ?: error("Relay offline — check your connection and try again.")+ val created = aliases.claim(address, passphrase, label = "", isPrimary = true)+ ?: error("That address is already taken.")+ // Seal the S2K passphrase only after the claim succeeds: a+ // Keystore key without an address is the broken state that+ // must land on Onboarding. keyManager.storeKeyPassphrase(passphrase) keyManager.storeOwnAddress(address)- config.setIdentity(address, identity.armoredPublic, identity.fingerprintHex)+ config.setIdentity(address, created.publicArmor, created.fingerprintHex) passphraseCache = passphrase- // Registration rides the first SUB; the service connects now.- MailSocketService.start(getApplication()) address } }@@ -266,6 +282,33 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } } + /**+ * Creates a random readable alias (`[email protected]`) that+ * delivers to this inbox and can be sent from.+ */+ fun createAlias(label: String) {+ state = state.copy(busy = true, error = null)+ viewModelScope.launch {+ val outcome = withContext(Dispatchers.IO) {+ runCatching { aliases.createRandom(requirePassphrase(), label) }+ }+ state = outcome.fold(+ onSuccess = { state.copy(busy = false, message = "Alias $it created.") },+ onFailure = {+ Log.status(TAG, "createAlias failed", it)+ state.copy(busy = false, error = it.message ?: "Couldn't create alias.")+ },+ )+ }+ }++ /**+ * Disabled aliases drop out of the From picker and are no longer SUBbed on+ * the next reconnect; the relay holds their mail until re-enabled.+ */+ fun setAliasDisabled(address: String, disabled: Boolean) =+ io { repo.identityDao().setDisabled(address, disabled) }+ /** * First unlock attempt from MainActivity: if no identity exists there is * nothing to gate; otherwise prompt biometrics before composition starts.@@ -325,31 +368,15 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { MailSocket.stop() keyManager.clear() config.clear()+ withContext(Dispatchers.IO) { repo.identityDao().deleteAll() } state = MailUiState() } } // ------------------------------------------------------------------- // Inbound: store + decrypt+ // Inbound: decrypt (arrival is handled by InboundStore) // ------------------------------------------------------------------ - /** Called by the socket layer for every MSG frame (already in Dispatchers.IO). */- suspend fun onInboundMessage(id: String, unencrypted: Boolean, raw: ByteArray) {- // Sender/from is inside the encrypted payload; store now, label on decrypt.- repo.messageDao().upsert(- StoredMessage(- id = id,- from = "",- toJson = "[\"${state.address}\"]",- dateMillis = System.currentTimeMillis(),- messageId = id,- blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),- unencrypted = unencrypted,- ),- )- decryptStored(id)- }- /** Decrypts one stored message in memory; never writes plaintext to the server. */ fun decryptStored(id: String) { viewModelScope.launch {@@ -360,12 +387,14 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { // S2K passphrase loads transparently from Keystore-wrapped // storage (sealed at claim time) — never asked for again. val passphrase = requirePassphrase()+ val ownSecret = Identities.forDelivery(getApplication(), stored.deliveredTo)+ ?.secretArmor ?: return@runCatching val raw = Base64.decode(stored.blobBase64, Base64.NO_WRAP) val pgpBytes = extractPgpPayload(raw) ?: raw val provisional = PgpCrypto.decrypt(- pgpBytes, keyManager.getSecretArmor(), passphrase,+ pgpBytes, ownSecret, passphrase, ).toString(Charsets.UTF_8)- val (_, _, from) = parseMime(provisional)+ val (_, _, from) = MimeCodec.parseMime(provisional) // Same two-step as arrival: resolve sender key post-decrypt, // re-verify for the badge. val (mime, verified) = if (from.isNotBlank()) {@@ -373,7 +402,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { if (senderKey != null) { val checked = PgpCrypto.decryptVerify( pgpBytes,- keyManager.getSecretArmor(),+ ownSecret, passphrase, senderKey, )@@ -385,7 +414,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } else { provisional to null }- val (subject, body, resolvedFrom, html) = parseMime(mime)+ val (subject, body, resolvedFrom, html) = MimeCodec.parseMime(mime) repo.messageDao().storeDecrypted( id, body, subject, verified = verified,@@ -402,37 +431,16 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } } - /**- * Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope.- * Delegates to [com.vayunmathur.securemail.domain.mail.MimeCodec].- */+ /** Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope. */ private fun extractPgpPayload(envelope: ByteArray): ByteArray? {- val b64 = com.vayunmathur.securemail.domain.mail.MimeCodec- .extractPgpPayloadB64(envelope) ?: return null+ val b64 = MimeCodec.extractPgpPayloadB64(envelope) ?: return null return try {- android.util.Base64.decode(b64, android.util.Base64.DEFAULT)- } catch (_: Exception) {+ Base64.decode(b64, Base64.DEFAULT)+ } catch (_: IllegalArgumentException) { null } } - /** Plaintext fallback path: stores the body with the unencrypted flag set. */- suspend fun onInboundPlaintext(id: String, from: String, subject: String, body: String) {- repo.messageDao().upsert(- StoredMessage(- id = id,- from = from,- toJson = "[\"${state.address}\"]",- dateMillis = System.currentTimeMillis(),- messageId = id,- blobBase64 = "",- decryptedBody = body,- decryptedSubject = subject,- unencrypted = true,- ),- )- }- // ------------------------------------------------------------------ // Outbound: trust gate + publish // ------------------------------------------------------------------@@ -517,6 +525,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { subject: String, body: String, inReplyTo: String? = null,+ from: String? = null, onDone: (sent: Boolean) -> Unit = {}, ) { val allTo = (to + cc + bcc).distinct()@@ -524,6 +533,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { viewModelScope.launch { val outcome = withContext(Dispatchers.IO) { runCatching {+ val sender = senderIdentity(from) val trust = resolveTrust(allTo) when (val decision = KeyLookupPolicy.decide(trust)) { is KeyLookupPolicy.SendDecision.NeedsKeyChangeAck ->@@ -534,10 +544,10 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } val encryptedTo = trust.filter { it.hasKey } val plainTo = trust.filter { !it.hasKey }.map { it.address }- val mime = buildMimeBody(subject, body)- // Sign with the own identity: recipients verify against our- // public key (directory/WKD) and show verified badges.- val ownSecret = keyManager.getSecretArmor()+ val mime = buildMimeBody(sender.address, subject, body)+ // Sign with the sending identity: recipients verify against+ // that address's public key (directory/WKD).+ val ownSecret = sender.secretArmor val ownPassphrase = requirePassphrase() var queued = 0 // Per-recipient encryption: each key-known recipient gets a blob.@@ -547,9 +557,9 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { mime, cached.armoredPublic, ownSecret, ownPassphrase, ) val blob = buildEncryptedBody(raw)- val ok = MailSocket.publish(t.address, blob)+ val ok = MailSocket.publish(sender.address, t.address, blob) if (!ok) {- queueOutbox(listOf(t.address), subject, body, inReplyTo)+ queueOutbox(sender.address, listOf(t.address), subject, body, inReplyTo) queued++ } }@@ -557,15 +567,15 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { // server to federate (own-domain) or relay onward — // badged `plain` wherever they land. for (address in plainTo) {- val ok = MailSocket.publish(address, mime, unencrypted = true)+ val ok = MailSocket.publish(sender.address, address, mime, unencrypted = true) if (!ok) {- queueOutbox(listOf(address), subject, body, inReplyTo)+ queueOutbox(sender.address, listOf(address), subject, body, inReplyTo) queued++ } } // Sent-folder copy: plaintext (it is our own composition). // Any keyless recipient got plaintext, so the copy is flagged unencrypted.- storeSent(allTo, subject, body, unencrypted = plainTo.isNotEmpty())+ storeSent(sender.address, allTo, subject, body, unencrypted = plainTo.isNotEmpty()) if (queued > 0) "Queued $queued message(s) — retry from Outbox when online." else "Sent." } }@@ -583,19 +593,33 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } } + /** The own identity to send from ([from] or the primary); rejects disabled aliases. */+ private suspend fun senderIdentity(from: String?): MailIdentity {+ val identity = Identities.forDelivery(getApplication(), from)+ ?: error("Set up your address first.")+ if (identity.disabled) error("${identity.address} is disabled — enable it in Settings to send.")+ return identity+ }+ /** * Records our own composition in the Sent folder (plaintext — it is ours). * Runs inside send()'s IO context; failures are swallowed (send succeeded). */- private suspend fun storeSent(to: List<String>, subject: String, body: String, unencrypted: Boolean) {+ private suspend fun storeSent(+ from: String,+ to: List<String>,+ subject: String,+ body: String,+ unencrypted: Boolean,+ ) { runCatching { repo.messageDao().upsert( StoredMessage( id = "sent-${UUID.randomUUID()}",- from = state.address,+ from = from, toJson = to.joinToString(","), dateMillis = System.currentTimeMillis(),- messageId = newMessageId(),+ messageId = MimeCodec.newMessageId(), blobBase64 = "", decryptedBody = body, decryptedSubject = subject.ifBlank { "(no subject)" },@@ -607,6 +631,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } private suspend fun queueOutbox(+ from: String, to: List<String>, subject: String, body: String,@@ -619,6 +644,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { body = body, inReplyTo = inReplyTo, createdMillis = System.currentTimeMillis(),+ fromAddress = from, ), ) }@@ -642,13 +668,14 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { val pending = repo.outboxDao().all() var sent = 0 var failed = 0- val ownSecret = keyManager.getSecretArmor() val ownPassphrase = requirePassphrase() for (entry in pending) { var reason = "relay publish failed" val ok = runCatching {+ val sender = senderIdentity(entry.fromAddress)+ val ownSecret = sender.secretArmor val to = entry.toJson.split(",").map { it.trim() }.filter { it.isNotEmpty() }- val mime = buildMimeBody(entry.subject, entry.body)+ val mime = buildMimeBody(sender.address, entry.subject, entry.body) var entryOk = true for (address in to) { val cached = repo.keyDao().get(address)@@ -665,7 +692,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } if (raw == null) { false- } else if (MailSocket.publish(address, buildEncryptedBody(raw))) {+ } else if (MailSocket.publish(sender.address, address, buildEncryptedBody(raw))) { true } else { reason = "publish failed: " +@@ -673,7 +700,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { false } } else {- if (MailSocket.publish(address, mime, unencrypted = true)) {+ if (MailSocket.publish(sender.address, address, mime, unencrypted = true)) { true } else { reason = "publish failed: " +@@ -720,8 +747,6 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { fun markRead(id: String) = io { repo.messageDao().markRead(id) } - fun messageFlow(id: String): StoredMessage? = null- fun envelopeOf(stored: StoredMessage): MessageEnvelope = MessageEnvelope( id = stored.id, from = stored.from,@@ -737,61 +762,9 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { state = state.copy(message = null, error = null, exportArmor = null) } - /**- * Minimal parser for the MIME skeleton [buildMimeBody] emits (headers +- * trailing `--boundary--`). Returns (subject, body, from). The payload is- * already authenticated PGP plaintext at this point; this only splits it.- */- private fun parseMime(mime: String): com.vayunmathur.securemail.domain.mail.MimeCodec.MimeContent =- com.vayunmathur.securemail.domain.mail.MimeCodec.parseMime(mime)-- private fun newMessageId(): String = "${UUID.randomUUID()}@maemail.org"-- /**- * Minimal PGP/MIME body (RFC 3156 multipart/encrypted skeleton). The actual- * encryption envelopes this whole body; the server relays it opaquely.- */- private fun buildMimeBody(subject: String, body: String): ByteArray {- val safeSubject = subject.replace(Regex("[\\r\\n]"), " ")- return (- "From: ${state.address}\r\n" +- "Subject: $safeSubject\r\n" +- "Message-ID: <${newMessageId()}>\r\n" +- "MIME-Version: 1.0\r\n" +- "Content-Type: text/plain; charset=utf-8; protected-headers=\"v1\"\r\n" +- "Content-Transfer-Encoding: 8bit\r\n" +- "\r\n" +- "$body\r\n"- ).toByteArray(Charsets.UTF_8)- }+ private fun buildMimeBody(from: String, subject: String, body: String): ByteArray =+ MimeCodec.buildPlainBody(from, subject, body, MimeCodec.newMessageId()) - /**- * Wraps raw PGP bytes in the RFC 3156 multipart/encrypted envelope for- * federated transport: control part (`application/pgp-encrypted`,- * `Version: 1`) + data part (`application/octet-stream`).- */- private fun buildEncryptedBody(encrypted: ByteArray): ByteArray {- val boundary = "maemail-${UUID.randomUUID().toString().take(8)}"- // RFC 3156 §4: the second part is an ASCII-armored PGP MESSAGE. Proton,- // GnuPG and Thunderbird reject a bare base64 body here.- val armored = PgpCrypto.armorMessage(encrypted).trimEnd().lines().joinToString("\r\n")- return (- "MIME-Version: 1.0\r\n" +- "Content-Type: multipart/encrypted; boundary=\"$boundary\"; protocol=\"application/pgp-encrypted\"\r\n" +- "\r\n" +- "--$boundary\r\n" +- "Content-Type: application/pgp-encrypted\r\n" +- "Content-Description: PGP/MIME version identification\r\n" +- "\r\n" +- "Version: 1\r\n" +- "\r\n" +- "--$boundary\r\n" +- "Content-Type: application/octet-stream; name=\"encrypted.asc\"\r\n" +- "Content-Description: OpenPGP encrypted message\r\n" +- "Content-Disposition: inline; filename=\"encrypted.asc\"\r\n" +- "\r\n" +- "$armored\r\n" +- "--$boundary--\r\n"- ).toByteArray(Charsets.UTF_8)- }+ private fun buildEncryptedBody(encrypted: ByteArray): ByteArray =+ MimeCodec.buildEncryptedEnvelope(PgpCrypto.armorMessage(encrypted)) }
securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.ktindex 47da32cd5c..fda0490cf7 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -4,17 +4,14 @@ import android.app.Service import android.content.Context import android.content.Intent import android.os.IBinder-import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.ensureNotificationChannel+import com.vayunmathur.securemail.data.Identities import com.vayunmathur.securemail.data.InboundStore-import com.vayunmathur.securemail.data.MailConfig import com.vayunmathur.securemail.network.MailSocket import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.launch /** * Persistent foreground service owning the mail relay socket — the SecureMail@@ -36,28 +33,21 @@ class MailSocketService : Service() { android.app.NotificationManager.IMPORTANCE_LOW, ) startForeground(NOTIFICATION_ID, buildNotification())- scope.launch {- val settings = MailConfig(this@MailSocketService).settings.first()- if (settings.address.isBlank()) {- Log.status(TAG, "no address claimed; socket idle")- return@launch- }- MailSocket.start(- scope = scope,- identity = {- val current = MailConfig(this@MailSocketService).settings.first()- if (current.address.isBlank() || current.publicArmor.isBlank()) null- else MailSocket.IdentitySnapshot(current.address, current.publicArmor)- },- onMessage = { id, flags, raw ->- // Single choke point (decrypt-on-arrival + vault write),- // shared with the background sync worker.- InboundStore.store(this@MailSocketService, id, flags, raw)- },- ) {- // onBump: socket liveness tick — no-op here; UI polls [MailSocket.connected].- }- }+ val ctx = this+ // The socket runs even before an address is claimed: onboarding claims+ // over it, and every (re)connect SUBs all active identities.+ MailSocket.start(+ scope = scope,+ identities = {+ Identities.active(ctx).map { MailSocket.IdentitySnapshot(it.address, it.publicArmor) }+ },+ sign = { address, payload -> Identities.sign(ctx, address, payload) },+ onMessage = { msg ->+ // Single choke point (decrypt-on-arrival + vault write),+ // shared with the background sync worker.+ InboundStore.store(ctx, msg)+ },+ ) } override fun onDestroy() {@@ -76,7 +66,6 @@ class MailSocketService : Service() { } companion object {- private const val TAG = "MailSocketService" private const val CHANNEL_ID = "securemail_relay" private const val NOTIFICATION_ID = 4101
securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.ktindex ca933202b9..b3e2e287ff 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt@@ -7,6 +7,7 @@ import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize@@ -32,10 +33,14 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.securemail.data.MailIdentity import com.vayunmathur.securemail.platform.MailUiState import kotlinx.coroutines.launch @@ -48,6 +53,9 @@ import kotlinx.coroutines.launch @Composable fun ComposeScreen( state: MailUiState,+ identities: List<MailIdentity>,+ draftFrom: String?,+ onSelectFrom: (String) -> Unit, draftTo: List<String>, draftCc: List<String>, draftBcc: List<String>,@@ -108,6 +116,9 @@ fun ComposeScreen( verticalArrangement = Arrangement.spacedBy(12.dp), ) { state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }+ if (identities.size > 1) {+ FromPicker(identities, draftFrom, onSelectFrom)+ } RecipientChipField( label = "To", recipients = draftTo,@@ -171,6 +182,41 @@ fun ComposeScreen( } } +/** Chooses which own address (primary or alias) the message is sent from. */+@Composable+private fun FromPicker(identities: List<MailIdentity>, selected: String?, onSelect: (String) -> Unit) {+ var open by remember { mutableStateOf(false) }+ val current = identities.firstOrNull { it.address == selected } ?: identities.first()+ Box {+ TextButton(onClick = { open = true }) {+ Text("From: ${current.address}", style = MaterialTheme.typography.bodyMedium)+ }+ DropdownMenu(expanded = open, onDismissRequest = { open = false }) {+ identities.forEach { identity ->+ DropdownMenuItem(+ text = {+ Column {+ Text(identity.address)+ val label = if (identity.isPrimary) "Primary" else identity.label+ if (label.isNotBlank()) {+ Text(+ label,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.secondary,+ )+ }+ }+ },+ onClick = {+ onSelect(identity.address)+ open = false+ },+ )+ }+ }+ }+}+ /** Reads the email address from a contact-picker result URI (per-item grant, no permission needed). */ internal fun contactEmail(context: android.content.Context, uri: android.net.Uri): String? = runCatching {
securemail/src/main/java/com/vayunmathur/securemail/ui/SettingsScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/SettingsScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/SettingsScreen.ktindex 08fd8b0cfa..f9c4af1e56 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/SettingsScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/SettingsScreen.kt@@ -2,33 +2,51 @@ package com.vayunmathur.securemail.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCopy import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.securemail.data.MailIdentity import com.vayunmathur.securemail.platform.MailUiState -/** Settings tab: identity, relay status, public-key export, forget. */+/** Settings tab: own addresses (primary + aliases), relay status, public-key export, forget. */ @Composable fun SettingsScreen( state: MailUiState,+ identities: List<MailIdentity>,+ onCreateAlias: (label: String) -> Unit,+ onSetAliasDisabled: (address: String, disabled: Boolean) -> Unit, onExportPublicKey: () -> Unit, onForget: () -> Unit, onDismissMessages: () -> Unit = {}, ) { val messenger = rememberMessenger()+ val context = LocalContext.current ConsumeMessage(state.message, messenger, onDismissMessages)+ var newLabel by remember { mutableStateOf("") } AppScaffold(title = "Settings", scrollBehavior = appBarScrollBehavior()) { padding -> DesktopMaxWidthContainer(Modifier.padding(padding)) { Column(@@ -44,13 +62,42 @@ fun SettingsScreen( modifier = Modifier.padding(16.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp), ) {- Text("Identity", style = MaterialTheme.typography.titleMedium)- Text(state.address, style = MaterialTheme.typography.bodyMedium)+ Text("Addresses", style = MaterialTheme.typography.titleMedium) Text(- "Key: ${state.fingerprintHex.take(24)}…",- style = MaterialTheme.typography.labelSmall,+ "Mail to any address lands in this inbox, and you can send from any of them.",+ style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.secondary, )+ identities.forEach { identity ->+ AddressRow(+ identity = identity,+ onCopy = { ExternalIntents.copyToClipboard(context, identity.address, "address") },+ onSetDisabled = { onSetAliasDisabled(identity.address, it) },+ )+ }+ OutlinedTextField(+ value = newLabel,+ onValueChange = { newLabel = it },+ label = { Text("Label for new alias (optional)") },+ singleLine = true,+ modifier = Modifier.fillMaxWidth(),+ )+ Button(+ onClick = {+ onCreateAlias(newLabel)+ newLabel = ""+ },+ enabled = !state.busy && state.socketConnected,+ modifier = Modifier.fillMaxWidth(),+ ) {+ Text(+ when {+ state.busy -> "Creating…"+ !state.socketConnected -> "Relay offline"+ else -> "New random alias"+ },+ )+ } Text( if (state.socketConnected) "Relay: connected" else "Relay: offline", style = MaterialTheme.typography.labelSmall,@@ -77,3 +124,36 @@ fun SettingsScreen( } } }++@Composable+private fun AddressRow(+ identity: MailIdentity,+ onCopy: () -> Unit,+ onSetDisabled: (Boolean) -> Unit,+) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Column(Modifier.weight(1f)) {+ val title = when {+ identity.isPrimary -> "Primary"+ identity.label.isNotBlank() -> identity.label+ else -> "Alias"+ }+ Text(title, style = MaterialTheme.typography.labelMedium)+ Text(identity.address, style = MaterialTheme.typography.bodyMedium)+ Text(+ "Key: ${identity.fingerprintHex.take(16)}…" ++ if (identity.disabled) " · disabled, mail held" else "",+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.secondary,+ )+ }+ IconButton(onClick = onCopy) { IconCopy() }+ if (!identity.isPrimary) {+ Switch(checked = !identity.disabled, onCheckedChange = { onSetDisabled(!it) })+ }+ }+}
securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt
diff --git a/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.ktindex 96ebc56862..a6cb2728e9 100644--- a/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt+++ b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt@@ -107,6 +107,9 @@ class MetadataPreviews { DynamicTheme(darkTheme = true) { ComposeScreen( state = MailUiState(address = "[email protected]"),+ identities = emptyList(),+ draftFrom = null,+ onSelectFrom = {}, draftTo = listOf("[email protected]"), draftCc = emptyList(), draftBcc = emptyList(),
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/AliasGeneratorTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/AliasGeneratorTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/AliasGeneratorTest.ktnew file mode 100644index 0000000000..8374295e4e--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/AliasGeneratorTest.kt@@ -0,0 +1,28 @@+package com.vayunmathur.securemail.domain.mail++import java.util.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class AliasGeneratorTest {++ private val shape = Regex("^[a-z]+-[a-z]+-[1-9][0-9]{3}@maemail\\.org$")++ @Test+ fun generatesClaimableReadableAddresses() {+ val random = Random(42)+ repeat(500) {+ val alias = AliasGenerator.generate(random)+ assertTrue(shape.matches(alias), alias)+ val local = alias.substringBefore('@')+ assertEquals(alias, AddressValidator.canonicalAddress(local), "passes claim validation")+ }+ }++ @Test+ fun defaultSourceIsVaried() {+ val seen = (1..200).map { AliasGenerator.generate() }.toSet()+ assertTrue(seen.size > 190, "expected near-unique aliases, got ${seen.size}")+ }+}
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.ktindex f61b1c22ae..f475500ae9 100644--- a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt@@ -121,4 +121,20 @@ class MimeCodecTest { ) assertEquals(Triple("Hello", "line one\nline two", "[email protected]"), Triple(subject, body, from)) }++ @Test+ fun plainBodyCarriesSendingAliasAndStripsSubjectNewlines() {+ val raw = MimeCodec.buildPlainBody("[email protected]", "Hi\r\nBcc: x", "body", "[email protected]")+ val (subject, body, from) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8))+ assertEquals("[email protected]", from)+ assertEquals("Hi Bcc: x", subject, "no header injection via subject")+ assertEquals("body", body)+ }++ @Test+ fun encryptedEnvelopeRoundTripsThroughExtract() {+ val armored = "-----BEGIN PGP MESSAGE-----\n\nAAEC\n=abcd\n-----END PGP MESSAGE-----\n"+ val envelope = MimeCodec.buildEncryptedEnvelope(armored)+ assertEquals("AAEC", MimeCodec.extractPgpPayloadB64(envelope))+ } }
securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketTest.ktindex 4c94b37062..7f803cbeb7 100644--- a/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketTest.kt+++ b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketTest.kt@@ -10,19 +10,35 @@ class MailSocketTest { @Test fun subFrameRoundTripShape() {- val frame = MailSocket.subFrame("[email protected]", "ARMOR")+ val sig = byteArrayOf(7, 7, 7)+ val frame = MailSocket.subFrame("[email protected]", sig, "ARMOR") assertEquals(MailSocket.OP_SUB, frame[0]) val addrLen = MailSocket.readU16(frame, 1) assertEquals("[email protected]", frame.copyOfRange(3, 3 + addrLen).toString(Charsets.UTF_8))- assertEquals("ARMOR", frame.copyOfRange(3 + addrLen, frame.size).toString(Charsets.UTF_8))+ val sigLen = MailSocket.readU16(frame, 3 + addrLen)+ assertContentEquals(sig, frame.copyOfRange(5 + addrLen, 5 + addrLen + sigLen))+ assertEquals("ARMOR", frame.copyOfRange(5 + addrLen + sigLen, frame.size).toString(Charsets.UTF_8)) } @Test- fun pubFrameFlags() {- val enc = MailSocket.pubFrame("[email protected]", byteArrayOf(1, 2, 3), unencrypted = false)+ fun subPayloadMatchesServerContext() {+ val nonce = ByteArray(MailSocket.NONCE_LEN) { it.toByte() }+ val payload = MailSocket.subPayload(nonce, "[email protected]")+ val context = "maemail-sub-v1\u0000".toByteArray(Charsets.UTF_8)+ assertContentEquals(context + nonce + "[email protected]".toByteArray(Charsets.UTF_8), payload)+ }++ @Test+ fun pubFrameCarriesSenderAndFlags() {+ val enc = MailSocket.pubFrame("[email protected]", "[email protected]", byteArrayOf(1, 2, 3), unencrypted = false) assertEquals(MailSocket.OP_PUB, enc[0]) assertEquals(0, enc[1])- val plain = MailSocket.pubFrame("[email protected]", byteArrayOf(1, 2, 3), unencrypted = true)+ val fromLen = MailSocket.readU16(enc, 2)+ assertEquals("[email protected]", enc.copyOfRange(4, 4 + fromLen).toString(Charsets.UTF_8))+ val rcptLen = MailSocket.readU16(enc, 4 + fromLen)+ assertEquals("[email protected]", enc.copyOfRange(6 + fromLen, 6 + fromLen + rcptLen).toString(Charsets.UTF_8))+ assertContentEquals(byteArrayOf(1, 2, 3), enc.copyOfRange(6 + fromLen + rcptLen, enc.size))+ val plain = MailSocket.pubFrame("[email protected]", "[email protected]", byteArrayOf(1, 2, 3), unencrypted = true) assertEquals(MailSocket.FLAG_PLAIN, plain[1]) } @@ -34,58 +50,66 @@ class MailSocketTest { assertEquals("[email protected]", frame.copyOfRange(3, 3 + len).toString(Charsets.UTF_8)) } - @Test- fun parseMsgRoundTrip() {- val id = "abc-123"+ /** Builds a v2 MSG frame: [0x03][flags][u32 idLen][id][u16 rcptLen][rcpt][raw]. */+ private fun msgFrame(id: String, flags: Byte, rcpt: String, raw: ByteArray): ByteArray { val idBytes = id.toByteArray(Charsets.UTF_8)- val raw = byteArrayOf(9, 8, 7)- val buf = ByteArray(1 + 1 + 4 + idBytes.size + raw.size)+ val rcptBytes = rcpt.toByteArray(Charsets.UTF_8)+ val buf = ByteArray(6 + idBytes.size + 2 + rcptBytes.size + raw.size) buf[0] = MailSocket.OP_MSG- buf[1] = 0- buf[2] = 0; buf[3] = 0; buf[4] = 0; buf[5] = idBytes.size.toByte()+ buf[1] = flags+ buf[5] = idBytes.size.toByte() idBytes.copyInto(buf, 6)- raw.copyInto(buf, 6 + idBytes.size)- val parsed = MailSocket.parseMsg(buf)!!- assertEquals(id, parsed.first)- assertEquals(MailSocket.MsgFlags(unencrypted = false, spam = false), parsed.second)- assertContentEquals(raw, parsed.third)+ MailSocket.putU16(buf, 6 + idBytes.size, rcptBytes.size)+ rcptBytes.copyInto(buf, 8 + idBytes.size)+ raw.copyInto(buf, 8 + idBytes.size + rcptBytes.size)+ return buf+ }++ @Test+ fun parseMsgRoundTrip() {+ val raw = byteArrayOf(9, 8, 7)+ val parsed = MailSocket.parseMsg(msgFrame("abc-123", 0, "[email protected]", raw))!!+ assertEquals("abc-123", parsed.id)+ assertEquals("[email protected]", parsed.deliveredTo)+ assertEquals(MailSocket.MsgFlags(unencrypted = false, spam = false), parsed.flags)+ assertContentEquals(raw, parsed.raw) } @Test fun parseMsgSpamFlag() {- val id = "spam-1"- val idBytes = id.toByteArray(Charsets.UTF_8) val raw = byteArrayOf(1, 2, 3)- val buf = ByteArray(1 + 1 + 4 + idBytes.size + raw.size)- buf[0] = MailSocket.OP_MSG- buf[1] = MailSocket.FLAG_SPAM- buf[2] = 0; buf[3] = 0; buf[4] = 0; buf[5] = idBytes.size.toByte()- idBytes.copyInto(buf, 6)- raw.copyInto(buf, 6 + idBytes.size)- val parsed = MailSocket.parseMsg(buf)!!- assertEquals(id, parsed.first)+ val parsed = MailSocket.parseMsg(msgFrame("spam-1", MailSocket.FLAG_SPAM, "[email protected]", raw))!!+ assertEquals("spam-1", parsed.id) // Spam bit set, plaintext bit clear → encrypted spam.- assertEquals(MailSocket.MsgFlags(unencrypted = false, spam = true), parsed.second)- assertContentEquals(raw, parsed.third)+ assertEquals(MailSocket.MsgFlags(unencrypted = false, spam = true), parsed.flags)+ assertContentEquals(raw, parsed.raw) } @Test fun parseMsgPlainAndSpamBits() {- val id = "both-1"- val idBytes = id.toByteArray(Charsets.UTF_8)- val buf = ByteArray(1 + 1 + 4 + idBytes.size)- buf[0] = MailSocket.OP_MSG- buf[1] = (MailSocket.FLAG_PLAIN.toInt() or MailSocket.FLAG_SPAM.toInt()).toByte()- buf[2] = 0; buf[3] = 0; buf[4] = 0; buf[5] = idBytes.size.toByte()- idBytes.copyInto(buf, 6)- val parsed = MailSocket.parseMsg(buf)!!- assertEquals(MailSocket.MsgFlags(unencrypted = true, spam = true), parsed.second)+ val flags = (MailSocket.FLAG_PLAIN.toInt() or MailSocket.FLAG_SPAM.toInt()).toByte()+ val parsed = MailSocket.parseMsg(msgFrame("both-1", flags, "[email protected]", ByteArray(0)))!!+ assertEquals(MailSocket.MsgFlags(unencrypted = true, spam = true), parsed.flags) } @Test fun parseMsgRejectsTruncated() { assertNull(MailSocket.parseMsg(byteArrayOf(MailSocket.OP_MSG))) assertNull(MailSocket.parseMsg(byteArrayOf(MailSocket.OP_MSG, 0, 0)))+ val full = msgFrame("id", 0, "[email protected]", byteArrayOf(1))+ assertNull(MailSocket.parseMsg(full.copyOfRange(0, 10)), "rcpt cut off")+ }++ @Test+ fun parseSubResp() {+ val addr = "[email protected]".toByteArray(Charsets.UTF_8)+ val frame = ByteArray(4 + addr.size)+ frame[0] = MailSocket.OP_SUBRESP+ frame[1] = MailSocket.SUB_TAKEN.toByte()+ MailSocket.putU16(frame, 2, addr.size)+ addr.copyInto(frame, 4)+ assertEquals("[email protected]" to MailSocket.SUB_TAKEN, MailSocket.parseSubResp(frame))+ assertNull(MailSocket.parseSubResp(frame.copyOfRange(0, 5))) } @Test