Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix paste password retry flow

Manav Rathi27ea63edd4da
diff --git a/docs/docs/paste/faq.md b/docs/docs/paste/faq.md
index 4e222cbb24..15eac27e5e 100644
--- a/docs/docs/paste/faq.md
+++ b/docs/docs/paste/faq.md
@@ -19,7 +19,7 @@ A paste lasts until Ente serves the ciphertext to a browser, or 24 hours from cr
### Can I open the same paste twice? {#paste-open-twice}
-No. A paste is consumed when Ente serves the ciphertext to a browser. For regular links that is the first open; for password-protected links, entering the wrong password after the ciphertext is fetched also consumes the paste. Reloading the page, opening the link on a second device, or sharing it onward after that all result in "This paste has expired or was already opened."
+No. A paste is consumed when Ente serves the ciphertext to a browser. For regular links that is the first open. For password-protected links, a wrong password can be retried in the same tab because the encrypted paste stays in memory there. Reloading the page, opening the link on a second device, or sharing it onward after that all result in "This paste has expired or was already opened."
If you need the recipient to be able to refer back to the text, ask them to copy it once they have opened the paste, or use [Ente Locker](/locker/) for durable storage.
diff --git a/docs/docs/paste/features/security.md b/docs/docs/paste/features/security.md
index 5c9e2f234f..769b8cfdd7 100644
--- a/docs/docs/paste/features/security.md
+++ b/docs/docs/paste/features/security.md
@@ -44,7 +44,7 @@ When the recipient opens the link:
5. The paste key is used to decrypt the text.
6. Ente deletes the paste from its servers.
-For a wrong password, step 3 produces the wrong key-encryption key, step 4 fails the authentication tag check, and the page shows "Incorrect paste password". Because the ciphertext was already fetched for this one-time open, the paste cannot be retried. Ask the sender to create a new paste.
+For a wrong password, step 3 produces the wrong key-encryption key, step 4 fails the authentication tag check, and the page shows "Incorrect paste password". The page keeps the encrypted paste in memory, so the recipient can retry in the same tab. If the page is closed or reloaded, the sender needs to create a new paste.
## What Ente's servers store
diff --git a/docs/docs/paste/getting-started.md b/docs/docs/paste/getting-started.md
index 51ab6d9174..7d9a12e2c0 100644
--- a/docs/docs/paste/getting-started.md
+++ b/docs/docs/paste/getting-started.md
@@ -99,12 +99,12 @@ When the recipient opens the link:
3. The decrypted text appears in a read-only text area with a "Copy" button.
4. Ente's servers delete the paste. The message "This paste has been removed from Ente servers." appears below the text.
-If the paste is password protected, the recipient sees an "Enter paste password" prompt before step 1. They enter the password and click "Open paste". Decryption only succeeds with the correct password.
+If the paste is password protected, the recipient sees an "Enter paste password" prompt before step 1. They enter the password and click "Open paste". Decryption only succeeds with the correct password. If they enter a wrong password, they can retry in the same tab.
## What can go wrong
- **"This paste has expired or was already opened."** The link has been consumed by someone else, or the 24-hour window has elapsed. The paste cannot be recovered. Create a new one.
-- **"Incorrect paste password"** (password-protected pastes only). The password did not produce the right key. Because the paste was already fetched for this one-time open, it cannot be retried. Ask the sender to create a new paste.
+- **"Incorrect paste password"** (password-protected pastes only). The password did not produce the right key. Retry in the same tab. If the page was closed or reloaded, ask the sender to create a new paste.
- **"Missing key in URL" / "Invalid key in URL"** The fragment after `#` is missing or malformed. This usually means the link was truncated when it was shared. Ask the sender to resend the full link, and prefer copying and pasting it exactly rather than retyping it.
- **"Paste is unavailable"** The link is being opened by a tool that looks like a link-preview bot or crawler, or the request was not made from `paste.ente.com`. Open the link directly in a regular browser tab.
diff --git a/rust/apps/cli/src/commands/paste.rs b/rust/apps/cli/src/commands/paste.rs
index 144bcffc9f..b75bb47a6f 100644
--- a/rust/apps/cli/src/commands/paste.rs
+++ b/rust/apps/cli/src/commands/paste.rs
@@ -47,13 +47,7 @@ pub async fn handle_paste_command(cmd: PasteCommand) -> Result<()> {
endpoint,
} => {
let (access_token, paste_key) = parse_paste_reference(&link_or_token, key)?;
- let password = if paste_key.password_required {
- Some(resolve_paste_password()?)
- } else {
- None
- };
- let text =
- consume_paste(&endpoint, &access_token, &paste_key, password.as_deref()).await?;
+ let text = consume_paste(&endpoint, &access_token, &paste_key).await?;
print!("{text}");
Ok(())
}
@@ -98,10 +92,10 @@ fn resolve_new_paste_password() -> Result<String> {
}
}
-fn resolve_paste_password() -> Result<String> {
+fn resolve_paste_password_attempt() -> Result<PastePasswordAttempt> {
match paste_password_from_env()? {
- Some(password) => Ok(password),
- None => prompt_paste_password(),
+ Some(password) => Ok(PastePasswordAttempt::Env(password)),
+ None => Ok(PastePasswordAttempt::Prompted(prompt_paste_password()?)),
}
}
@@ -129,12 +123,27 @@ fn prompt_new_paste_password() -> Result<String> {
}
fn prompt_paste_password() -> Result<String> {
- let password = Password::new()
+ prompt_valid_paste_password(prompt_raw_paste_password)
+}
+
+fn prompt_raw_paste_password() -> Result<String> {
+ Password::new()
.with_prompt("Paste password")
.interact()
- .map_err(dialoguer_error)?;
- validate_password(&password)?;
- Ok(password)
+ .map_err(dialoguer_error)
+}
+
+fn prompt_valid_paste_password<F>(mut prompt_password: F) -> Result<String>
+where
+ F: FnMut() -> Result<String>,
+{
+ loop {
+ let password = prompt_password()?;
+ match validate_password(&password) {
+ Ok(()) => return Ok(password),
+ Err(error) => eprintln!("{error}"),
+ }
+ }
}
fn dialoguer_error(error: dialoguer::Error) -> Error {
@@ -151,6 +160,23 @@ fn validate_password(password: &str) -> Result<()> {
}
}
+enum PastePasswordAttempt {
+ Env(String),
+ Prompted(String),
+}
+
+impl PastePasswordAttempt {
+ fn value(&self) -> &str {
+ match self {
+ Self::Env(password) | Self::Prompted(password) => password,
+ }
+ }
+
+ fn can_retry(&self) -> bool {
+ matches!(self, Self::Prompted(_))
+ }
+}
+
async fn create_paste(
endpoint: &str,
paste_origin: &str,
@@ -168,28 +194,99 @@ async fn create_paste(
))
}
-async fn consume_paste(
+async fn consume_paste(endpoint: &str, access_token: &str, paste_key: &PasteKey) -> Result<String> {
+ consume_paste_with_password_resolver(
+ endpoint,
+ access_token,
+ paste_key,
+ resolve_paste_password_attempt,
+ )
+ .await
+}
+
+async fn consume_paste_with_password_resolver<F>(
endpoint: &str,
access_token: &str,
paste_key: &PasteKey,
- password: Option<&str>,
-) -> Result<String> {
+ resolve_password: F,
+) -> Result<String>
+where
+ F: FnOnce() -> Result<PastePasswordAttempt>,
+{
let client = paste_http_client()?;
let request = PasteTokenRequest {
access_token: access_token.to_string(),
};
+ let password = if paste_key.password_required {
+ guard_cookie(&client, endpoint, &request).await?;
+ Some(resolve_password()?)
+ } else {
+ None
+ };
let cookie = guard_cookie(&client, endpoint, &request).await?;
- let payload: PastePayload = post_json(
+ let payload = consume_paste_payload(&client, endpoint, &request, &cookie).await?;
+
+ match password {
+ Some(password) => decrypt_password_protected_paste(paste_key, &payload, password),
+ None => decrypt_consumed_paste(paste_key, None, &payload),
+ }
+}
+
+async fn consume_paste_payload(
+ client: &Client,
+ endpoint: &str,
+ request: &PasteTokenRequest,
+ cookie: &str,
+) -> Result<PastePayload> {
+ post_json(
&client,
endpoint,
"/paste/consume",
&request,
Some(("X-Paste-Consume", "1")),
- Some(&cookie),
+ Some(cookie),
+ )
+ .await
+}
+
+fn decrypt_password_protected_paste(
+ paste_key: &PasteKey,
+ payload: &PastePayload,
+ password: PastePasswordAttempt,
+) -> Result<String> {
+ decrypt_password_protected_paste_with_prompt(
+ paste_key,
+ payload,
+ password,
+ prompt_raw_paste_password,
)
- .await?;
+}
- decrypt_consumed_paste(paste_key, password, &payload)
+fn decrypt_password_protected_paste_with_prompt<F>(
+ paste_key: &PasteKey,
+ payload: &PastePayload,
+ mut password: PastePasswordAttempt,
+ mut prompt_password: F,
+) -> Result<String>
+where
+ F: FnMut() -> Result<String>,
+{
+ loop {
+ let key_encryption_key =
+ derive_paste_key_encryption_key(paste_key, Some(password.value()), payload)?;
+ let paste_key = match decrypt_paste_key_for_password(payload, &key_encryption_key) {
+ Ok(paste_key) => paste_key,
+ Err(Error::AuthenticationFailed(_)) if password.can_retry() => {
+ eprintln!("Incorrect paste password. Try again.");
+ password = PastePasswordAttempt::Prompted(prompt_valid_paste_password(
+ &mut prompt_password,
+ )?);
+ continue;
+ }
+ Err(error) => return Err(error),
+ };
+ return decrypt_consumed_text(&paste_key, payload);
+ }
}
fn paste_http_client() -> Result<Client> {
@@ -327,21 +424,61 @@ fn decrypt_consumed_paste(
password: Option<&str>,
payload: &PastePayload,
) -> Result<String> {
+ let key_encryption_key = derive_paste_key_encryption_key(paste_key, password, payload)?;
+ let paste_key = decrypt_wrapped_paste_key(payload, &key_encryption_key)?;
+ decrypt_consumed_text(&paste_key, payload)
+}
+
+fn derive_paste_key_encryption_key(
+ paste_key: &PasteKey,
+ password: Option<&str>,
+ payload: &PastePayload,
+) -> Result<Vec<u8>> {
let salt = BASE64.decode(&payload.kdf_nonce)?;
let kdf_secret = paste_key.kdf_secret(password)?;
- let key_encryption_key = argon::derive_key(
+ Ok(argon::derive_key(
&kdf_secret,
&salt,
payload.kdf_mem_limit,
payload.kdf_ops_limit,
- )?;
- let encrypted_paste_key = BASE64.decode(&payload.encrypted_paste_key)?;
- let encrypted_paste_key_nonce = BASE64.decode(&payload.encrypted_paste_key_nonce)?;
- let paste_key = secretbox::decrypt(
+ )?)
+}
+
+fn decrypt_paste_key_for_password(
+ payload: &PastePayload,
+ key_encryption_key: &[u8],
+) -> Result<Vec<u8>> {
+ let (encrypted_paste_key, encrypted_paste_key_nonce) = decode_wrapped_paste_key(payload)?;
+ secretbox::decrypt(
&encrypted_paste_key,
&encrypted_paste_key_nonce,
- &key_encryption_key,
- )?;
+ key_encryption_key,
+ )
+ .map_err(|_| Error::AuthenticationFailed("Incorrect paste password".to_string()))
+}
+
+fn decrypt_wrapped_paste_key(payload: &PastePayload, key_encryption_key: &[u8]) -> Result<Vec<u8>> {
+ let (encrypted_paste_key, encrypted_paste_key_nonce) = decode_wrapped_paste_key(payload)?;
+ Ok(secretbox::decrypt(
+ &encrypted_paste_key,
+ &encrypted_paste_key_nonce,
+ key_encryption_key,
+ )?)
+}
+
+fn decode_wrapped_paste_key(payload: &PastePayload) -> Result<(Vec<u8>, Vec<u8>)> {
+ let encrypted_paste_key = BASE64.decode(&payload.encrypted_paste_key)?;
+ let encrypted_paste_key_nonce = BASE64.decode(&payload.encrypted_paste_key_nonce)?;
+ if encrypted_paste_key.len() < secretbox::MAC_BYTES {
+ return Err(invalid_paste_payload());
+ }
+ if encrypted_paste_key_nonce.len() != secretbox::NONCE_BYTES {
+ return Err(invalid_paste_payload());
+ }
+ Ok((encrypted_paste_key, encrypted_paste_key_nonce))
+}
+
+fn decrypt_consumed_text(paste_key: &[u8], payload: &PastePayload) -> Result<String> {
let encrypted_data = BASE64.decode(&payload.encrypted_data)?;
let decryption_header = BASE64.decode(&payload.decryption_header)?;
let text: PasteText = blob::decrypt_json(
@@ -354,6 +491,10 @@ fn decrypt_consumed_paste(
Ok(text.text)
}
+fn invalid_paste_payload() -> Error {
+ Error::Crypto("Invalid paste payload".to_string())
+}
+
fn create_fragment_secret() -> String {
let mut secret = String::with_capacity(FRAGMENT_SECRET_LENGTH);
let threshold = 256 - (256 % FRAGMENT_SECRET_ALPHABET.len());
@@ -560,6 +701,106 @@ mod tests {
assert!(matches!(error, Error::Crypto(_)));
}
+ #[test]
+ fn reject_wrong_env_paste_password() {
+ crypto::init().unwrap();
+
+ let (paste_key, payload) =
+ encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();
+ let error = decrypt_password_protected_paste(
+ &paste_key,
+ &payload,
+ PastePasswordAttempt::Env("wrong horse".to_string()),
+ )
+ .unwrap_err();
+
+ assert!(matches!(error, Error::AuthenticationFailed(_)));
+ }
+
+ #[test]
+ fn prompted_password_retry_can_recover() {
+ crypto::init().unwrap();
+
+ let (paste_key, payload) =
+ encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();
+ let mut retry_passwords = ["correct horse"].into_iter();
+ let text = decrypt_password_protected_paste_with_prompt(
+ &paste_key,
+ &payload,
+ PastePasswordAttempt::Prompted("wrong horse".to_string()),
+ || Ok::<_, Error>(retry_passwords.next().expect("retry password").to_string()),
+ )
+ .unwrap();
+
+ assert_eq!(text, "protected paste");
+ assert_eq!(retry_passwords.next(), None);
+ }
+
+ #[test]
+ fn prompted_password_retry_ignores_empty_password() {
+ crypto::init().unwrap();
+
+ let (paste_key, payload) =
+ encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();
+ let mut retry_passwords = ["", "correct horse"].into_iter();
+ let text = decrypt_password_protected_paste_with_prompt(
+ &paste_key,
+ &payload,
+ PastePasswordAttempt::Prompted("wrong horse".to_string()),
+ || Ok::<_, Error>(retry_passwords.next().expect("retry password").to_string()),
+ )
+ .unwrap();
+
+ assert_eq!(text, "protected paste");
+ assert_eq!(retry_passwords.next(), None);
+ }
+
+ #[test]
+ fn prompted_password_retry_does_not_hide_structural_payload_errors() {
+ crypto::init().unwrap();
+
+ let (paste_key, mut payload) =
+ encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();
+ payload.kdf_nonce = "not base64".to_string();
+ let mut prompts = 0;
+ let error = decrypt_password_protected_paste_with_prompt(
+ &paste_key,
+ &payload,
+ PastePasswordAttempt::Prompted("correct horse".to_string()),
+ || {
+ prompts += 1;
+ Ok::<_, Error>("correct horse".to_string())
+ },
+ )
+ .unwrap_err();
+
+ assert!(matches!(error, Error::Base64Decode(_)));
+ assert_eq!(prompts, 0);
+ }
+
+ #[test]
+ fn prompted_password_retry_does_not_hide_wrapped_key_payload_errors() {
+ crypto::init().unwrap();
+
+ let (paste_key, mut payload) =
+ encrypt_paste_for_create("protected paste", Some("correct horse")).unwrap();
+ payload.encrypted_paste_key = "not base64".to_string();
+ let mut prompts = 0;
+ let error = decrypt_password_protected_paste_with_prompt(
+ &paste_key,
+ &payload,
+ PastePasswordAttempt::Prompted("correct horse".to_string()),
+ || {
+ prompts += 1;
+ Ok::<_, Error>("correct horse".to_string())
+ },
+ )
+ .unwrap_err();
+
+ assert!(matches!(error, Error::Base64Decode(_)));
+ assert_eq!(prompts, 0);
+ }
+
#[test]
fn parse_full_paste_link() {
let (token, paste_key) =
@@ -663,7 +904,7 @@ mod tests {
.create_async()
.await;
- let text = consume_paste(&server.url(), access_token, &paste_key, None)
+ let text = consume_paste(&server.url(), access_token, &paste_key)
.await
.unwrap();
@@ -672,6 +913,67 @@ mod tests {
consume.assert_async().await;
}
+ #[tokio::test]
+ async fn password_paste_refreshes_guard_after_password_resolution() {
+ crypto::init().unwrap();
+
+ let access_token = "ABC123";
+ let paste_key = PasteKey::parse("p-AbCd1234EfGh").unwrap();
+ let payload = test_payload("guarded paste", &paste_key, Some("correct horse"));
+ let mut server = Server::new_async().await;
+
+ let availability_guard = server
+ .mock("POST", "/paste/guard")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "accessToken": access_token,
+ })))
+ .with_status(200)
+ .with_header(
+ "set-cookie",
+ "paste_guard=availability-cookie; Path=/; HttpOnly",
+ )
+ .with_body("{}")
+ .expect(1)
+ .create_async()
+ .await;
+
+ let consume_guard = server
+ .mock("POST", "/paste/guard")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "accessToken": access_token,
+ })))
+ .with_status(200)
+ .with_header("set-cookie", "paste_guard=consume-cookie; Path=/; HttpOnly")
+ .with_body("{}")
+ .expect(1)
+ .create_async()
+ .await;
+
+ let consume = server
+ .mock("POST", "/paste/consume")
+ .match_header("x-paste-consume", "1")
+ .match_header("cookie", "paste_guard=consume-cookie")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "accessToken": access_token,
+ })))
+ .with_status(200)
+ .with_body(serde_json::to_string(&payload).unwrap())
+ .create_async()
+ .await;
+
+ let text =
+ consume_paste_with_password_resolver(&server.url(), access_token, &paste_key, || {
+ Ok(PastePasswordAttempt::Env("correct horse".to_string()))
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(text, "guarded paste");
+ availability_guard.assert_async().await;
+ consume_guard.assert_async().await;
+ consume.assert_async().await;
+ }
+
fn test_payload(text: &str, key_reference: &PasteKey, password: Option<&str>) -> PastePayload {
let paste_key = [7u8; secretbox::KEY_BYTES];
let encrypted = blob::encrypt_json(
diff --git a/rust/apps/cli/tests/paste.rs b/rust/apps/cli/tests/paste.rs
index e78171e080..9bb3967b0a 100644
--- a/rust/apps/cli/tests/paste.rs
+++ b/rust/apps/cli/tests/paste.rs
@@ -12,7 +12,9 @@ fn paste() -> TestResult {
full_link_roundtrip(fixture)?;
token_and_key_roundtrip(fixture)?;
stdin_roundtrip(fixture)?;
- password_protected_roundtrip(fixture)
+ password_protected_roundtrip(fixture)?;
+ wrong_password_consumes_password_protected_paste(fixture)?;
+ consumed_password_paste_checks_availability_before_password(fixture)
})
}
@@ -105,22 +107,83 @@ fn password_protected_roundtrip(fixture: &Fixture) -> TestResult {
let cli = fixture.cli_session("password-protected")?;
let text = unique_text("password-protected");
let password = format!("password {}", Uuid::new_v4());
+ let link = create_password_paste(&cli, fixture, &text, &password)?;
let env = [(PASTE_PASSWORD_ENV, password.as_str())];
- let link = cli.run_ok_with_env(
+ assert!(link.password_required);
+
+ let consumed = cli.run_ok_with_env(
&[
"paste",
- "create",
+ "consume",
"--endpoint",
fixture.endpoint(),
- "--paste-origin",
- fixture.paste_origin(),
- "--password",
- &text,
+ &link.raw,
],
&env,
)?;
- let link = PasteLink::parse(link.trim(), fixture.paste_origin());
- assert!(link.password_required);
+ assert_eq!(consumed, text);
+
+ Ok(())
+}
+
+fn wrong_password_consumes_password_protected_paste(fixture: &Fixture) -> TestResult {
+ let cli = fixture.cli_session("wrong-password")?;
+ let text = unique_text("wrong-password");
+ let password = format!("password {}", Uuid::new_v4());
+ let link = create_password_paste(&cli, fixture, &text, &password)?;
+
+ let wrong_env = [(PASTE_PASSWORD_ENV, "wrong password")];
+ let wrong = cli.run_with_env(
+ &[
+ "paste",
+ "consume",
+ "--endpoint",
+ fixture.endpoint(),
+ &link.raw,
+ ],
+ &wrong_env,
+ )?;
+ assert!(
+ !wrong.status.success(),
+ "wrong password unexpectedly succeeded"
+ );
+ assert!(
+ String::from_utf8_lossy(&wrong.stderr).contains("Incorrect paste password"),
+ "wrong password should fail locally, got stderr: {}",
+ String::from_utf8_lossy(&wrong.stderr),
+ );
+
+ let correct_env = [(PASTE_PASSWORD_ENV, password.as_str())];
+ let second = cli.run_with_env(
+ &[
+ "paste",
+ "consume",
+ "--endpoint",
+ fixture.endpoint(),
+ &link.raw,
+ ],
+ &correct_env,
+ )?;
+ assert!(
+ !second.status.success(),
+ "second consume unexpectedly succeeded with stdout: {}",
+ String::from_utf8_lossy(&second.stdout),
+ );
+ assert!(
+ String::from_utf8_lossy(&second.stderr).contains("API error (410)"),
+ "second consume should fail with 410, got stderr: {}",
+ String::from_utf8_lossy(&second.stderr),
+ );
+
+ Ok(())
+}
+
+fn consumed_password_paste_checks_availability_before_password(fixture: &Fixture) -> TestResult {
+ let cli = fixture.cli_session("consumed-password")?;
+ let text = unique_text("consumed-password");
+ let password = format!("password {}", Uuid::new_v4());
+ let link = create_password_paste(&cli, fixture, &text, &password)?;
+ let env = [(PASTE_PASSWORD_ENV, password.as_str())];
let consumed = cli.run_ok_with_env(
&[
@@ -134,6 +197,32 @@ fn password_protected_roundtrip(fixture: &Fixture) -> TestResult {
)?;
assert_eq!(consumed, text);
+ let invalid_env = [(PASTE_PASSWORD_ENV, "")];
+ let second = cli.run_with_env(
+ &[
+ "paste",
+ "consume",
+ "--endpoint",
+ fixture.endpoint(),
+ &link.raw,
+ ],
+ &invalid_env,
+ )?;
+ assert!(
+ !second.status.success(),
+ "second consume unexpectedly succeeded"
+ );
+ assert!(
+ String::from_utf8_lossy(&second.stderr).contains("API error (410)"),
+ "consumed paste should fail before password validation, got stderr: {}",
+ String::from_utf8_lossy(&second.stderr),
+ );
+ assert!(
+ !String::from_utf8_lossy(&second.stderr).contains("Paste password is empty"),
+ "consumed paste validated password before guard: {}",
+ String::from_utf8_lossy(&second.stderr),
+ );
+
Ok(())
}
@@ -150,6 +239,29 @@ fn create_paste(cli: &Cli, fixture: &Fixture, text: &str) -> TestResult<PasteLin
Ok(PasteLink::parse(link.trim(), fixture.paste_origin()))
}
+fn create_password_paste(
+ cli: &Cli,
+ fixture: &Fixture,
+ text: &str,
+ password: &str,
+) -> TestResult<PasteLink> {
+ let env = [(PASTE_PASSWORD_ENV, password)];
+ let link = cli.run_ok_with_env(
+ &[
+ "paste",
+ "create",
+ "--endpoint",
+ fixture.endpoint(),
+ "--paste-origin",
+ fixture.paste_origin(),
+ "--password",
+ text,
+ ],
+ &env,
+ )?;
+ Ok(PasteLink::parse(link.trim(), fixture.paste_origin()))
+}
+
fn unique_text(scope: &str) -> String {
format!("paste cli {scope} scenario {}", Uuid::new_v4())
}
diff --git a/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx b/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
index 9efcd647e9..c2209891fd 100644
--- a/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
+++ b/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
@@ -16,7 +16,6 @@ import {
Tooltip,
Typography,
} from "@mui/material";
-import useMediaQuery from "@mui/material/useMediaQuery";
import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
import { usePasteColorMode } from "features/paste/hooks/usePasteColorMode";
import { getPasteThemeTokens } from "features/paste/theme/pasteThemeTokens";
@@ -50,7 +49,6 @@ export const PasteCreatePanel = ({
onCopyLink,
onShareLink,
}: PasteCreatePanelProps) => {
- const isMobile = useMediaQuery("(max-width:599.95px)", { noSsr: true });
const { resolvedMode } = usePasteColorMode();
const tokens = getPasteThemeTokens(resolvedMode);
const [passwordProtected, setPasswordProtected] = useState(false);
@@ -80,10 +78,28 @@ export const PasteCreatePanel = ({
? "0 22px 56px rgba(0, 0, 0, 0.48)"
: "0 18px 44px rgba(17, 49, 114, 0.18)";
const privacyPills = [
- "Private",
- isMobile ? "E2EE" : "End-to-end encrypted",
- "One-time view",
- "Auto-deletes after 24 hours",
+ { key: "private", label: "Private" },
+ {
+ key: "e2ee",
+ label: (
+ <>
+ <Box
+ component="span"
+ sx={{ display: { xs: "inline", sm: "none" } }}
+ >
+ E2EE
+ </Box>
+ <Box
+ component="span"
+ sx={{ display: { xs: "none", sm: "inline" } }}
+ >
+ End-to-end encrypted
+ </Box>
+ </>
+ ),
+ },
+ { key: "one-time-view", label: "One-time view" },
+ { key: "auto-delete", label: "Auto-deletes after 24 hours" },
];
const passwordFieldSx = {
...pasteTextFieldSx(tokens, "14px"),
@@ -473,9 +489,9 @@ export const PasteCreatePanel = ({
userSelect: "none",
}}
>
- {privacyPills.map((label) => (
+ {privacyPills.map(({ key, label }) => (
<Box
- key={label}
+ key={key}
component="span"
aria-disabled="true"
sx={{
diff --git a/web/apps/paste/src/features/paste/components/PasteViewPanel.tsx b/web/apps/paste/src/features/paste/components/PasteViewPanel.tsx
index 464bc02c22..10499e3e40 100644
--- a/web/apps/paste/src/features/paste/components/PasteViewPanel.tsx
+++ b/web/apps/paste/src/features/paste/components/PasteViewPanel.tsx
@@ -20,6 +20,7 @@ interface PasteViewPanelProps {
consumeError: string | null;
resolvedText: string | null;
passwordRequired: boolean;
+ passwordError: string | null;
onSubmitPassword: (password: string) => Promise<void>;
onCopyText: (value: string) => Promise<void>;
}
@@ -29,6 +30,7 @@ export const PasteViewPanel = ({
consumeError,
resolvedText,
passwordRequired,
+ passwordError,
onSubmitPassword,
onCopyText,
}: PasteViewPanelProps) => {
@@ -82,12 +84,27 @@ export const PasteViewPanel = ({
>
Enter paste password
</Typography>
+ <Typography
+ variant="mini"
+ sx={{
+ maxWidth: 420,
+ color: tokens.status.loadingBody,
+ fontWeight: 500,
+ lineHeight: 1.35,
+ textAlign: "center",
+ }}
+ >
+ Password is checked in your browser. If it fails,
+ retry here instead of reopening the link.
+ </Typography>
<TextField
variant="filled"
hiddenLabel
fullWidth
type="password"
value={password}
+ error={!!passwordError}
+ helperText={passwordError}
autoFocus
autoComplete="off"
placeholder="Password"
@@ -113,6 +130,17 @@ export const PasteViewPanel = ({
tokens.surface.inputGradient,
boxShadow: tokens.surface.inputShadow,
},
+ "& .MuiFilledInput-root.Mui-error": {
+ borderColor: tokens.status.errorIcon,
+ },
+ "& .MuiFormHelperText-root": {
+ mx: 0,
+ mt: 0.75,
+ color: tokens.status.errorBody,
+ fontSize: "0.8rem",
+ lineHeight: 1.25,
+ textAlign: "center",
+ },
},
]}
/>
diff --git a/web/apps/paste/src/features/paste/hooks/useConsumePaste.ts b/web/apps/paste/src/features/paste/hooks/useConsumePaste.ts
index 0e52a45474..e2486f1e46 100644
--- a/web/apps/paste/src/features/paste/hooks/useConsumePaste.ts
+++ b/web/apps/paste/src/features/paste/hooks/useConsumePaste.ts
@@ -1,57 +1,75 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { consumePaste, setGuard } from "services/paste";
+import { consumePaste, setGuard, type PastePayload } from "services/paste";
import type { PageMode } from "../types";
import { waitUntilVisible } from "../utils/browser";
import {
decryptConsumedPaste,
+ IncorrectPastePasswordError,
parsePasteKey,
type PasteKey,
} from "../utils/pasteCrypto";
+const errorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : "Paste is unavailable";
+
export const useConsumePaste = (mode: PageMode, accessToken: string | null) => {
const [consuming, setConsuming] = useState(false);
const [consumeError, setConsumeError] = useState<string | null>(null);
const [resolvedText, setResolvedText] = useState<string | null>(null);
const [passwordRequired, setPasswordRequired] = useState(false);
+ const [passwordError, setPasswordError] = useState<string | null>(null);
- const startedConsumeRef = useRef(false);
+ const consumeInFlightRef = useRef(false);
+ const consumedPayloadRef = useRef<PastePayload | null>(null);
const pasteKeyRef = useRef<PasteKey | null>(null);
+ const confirmPasteAvailable = useCallback(async () => {
+ if (!accessToken) return;
+
+ try {
+ setConsuming(true);
+ setConsumeError(null);
+ await waitUntilVisible();
+ await setGuard(accessToken);
+ setPasswordRequired(true);
+ } catch (error) {
+ setConsumeError(errorMessage(error));
+ } finally {
+ setConsuming(false);
+ }
+ }, [accessToken]);
+
const consume = useCallback(
async (pasteKey: PasteKey, password?: string) => {
- if (!accessToken || startedConsumeRef.current) {
+ if (!accessToken || consumeInFlightRef.current) {
return;
}
- startedConsumeRef.current = true;
+ consumeInFlightRef.current = true;
try {
setConsuming(true);
setConsumeError(null);
+ setPasswordError(null);
- await waitUntilVisible();
- await setGuard(accessToken);
- const payload = await consumePaste(accessToken);
- let decryptedText: string;
- try {
- decryptedText = await decryptConsumedPaste(
- pasteKey,
- payload,
- password,
- );
- } catch (error) {
- if (pasteKey.passwordRequired) {
- throw new Error("Incorrect paste password");
- }
- throw error;
+ let payload = consumedPayloadRef.current;
+ if (!payload) {
+ await waitUntilVisible();
+ await setGuard(accessToken);
+ payload = await consumePaste(accessToken);
+ consumedPayloadRef.current = payload;
}
- setResolvedText(decryptedText);
+ setResolvedText(
+ await decryptConsumedPaste(pasteKey, payload, password),
+ );
+ setPasswordRequired(false);
} catch (error) {
- const message =
- error instanceof Error
- ? error.message
- : "Paste is unavailable";
- setConsumeError(message);
+ if (error instanceof IncorrectPastePasswordError) {
+ setPasswordError("Incorrect paste password");
+ } else {
+ setConsumeError(errorMessage(error));
+ }
} finally {
+ consumeInFlightRef.current = false;
setConsuming(false);
}
},
@@ -70,20 +88,18 @@ export const useConsumePaste = (mode: PageMode, accessToken: string | null) => {
const pasteKey = parsePasteKey(fragment);
pasteKeyRef.current = pasteKey;
if (pasteKey.passwordRequired) {
- setPasswordRequired(true);
+ void confirmPasteAvailable();
} else {
void consume(pasteKey);
}
} catch (error) {
- const message =
- error instanceof Error ? error.message : "Paste is unavailable";
- setConsumeError(message);
+ setConsumeError(errorMessage(error));
}
- }, [mode, accessToken, consume]);
+ }, [mode, accessToken, confirmPasteAvailable, consume]);
const submitPassword = async (password: string) => {
if (!password) {
- setConsumeError("Enter the paste password");
+ setPasswordError("Enter the paste password");
return;
}
if (!pasteKeyRef.current) {
@@ -98,6 +114,7 @@ export const useConsumePaste = (mode: PageMode, accessToken: string | null) => {
consumeError,
resolvedText,
passwordRequired,
+ passwordError,
submitPassword,
};
};
diff --git a/web/apps/paste/src/features/paste/utils/pasteCrypto.ts b/web/apps/paste/src/features/paste/utils/pasteCrypto.ts
index fe037577e3..c6a01a32dd 100644
--- a/web/apps/paste/src/features/paste/utils/pasteCrypto.ts
+++ b/web/apps/paste/src/features/paste/utils/pasteCrypto.ts
@@ -22,6 +22,12 @@ export interface PasteKey {
passwordRequired: boolean;
}
+export class IncorrectPastePasswordError extends Error {
+ constructor() {
+ super("Incorrect paste password");
+ }
+}
+
export const createFragmentSecret = () =>
newID("").slice(0, FRAGMENT_SECRET_LENGTH);
@@ -93,13 +99,20 @@ const resolvePasteKey = async (
payload.kdfMemLimit,
);
- return await decryptBox(
- {
- encryptedData: payload.encryptedPasteKey,
- nonce: payload.encryptedPasteKeyNonce,
- },
- keyEncryptionKey,
- );
+ try {
+ return await decryptBox(
+ {
+ encryptedData: payload.encryptedPasteKey,
+ nonce: payload.encryptedPasteKeyNonce,
+ },
+ keyEncryptionKey,
+ );
+ } catch (error) {
+ if (pasteKey.passwordRequired) {
+ throw new IncorrectPastePasswordError();
+ }
+ throw error;
+ }
};
export const decryptConsumedPaste = async (
diff --git a/web/apps/paste/src/pages/index.tsx b/web/apps/paste/src/pages/index.tsx
index d4572fbd39..854ce93b5b 100644
--- a/web/apps/paste/src/pages/index.tsx
+++ b/web/apps/paste/src/pages/index.tsx
@@ -30,6 +30,7 @@ const Page = () => {
consumeError,
resolvedText,
passwordRequired,
+ passwordError,
submitPassword,
} = useConsumePaste(mode, accessToken);
@@ -82,6 +83,7 @@ const Page = () => {
consumeError={consumeError}
resolvedText={resolvedText}
passwordRequired={passwordRequired}
+ passwordError={passwordError}
onSubmitPassword={submitPassword}
onCopyText={copyTextToClipboard}
/>