approval: disclose what sign_event/encrypt cannot show in full (H2)
The dialog now shows the client-requested created_at and warns (adw::Banner) when content, tags, tag values or an encrypt message exceed what it can show, and offers the full encrypt message. incoming() rejects a malformed kind/content/tags instead of coercing them.
This commit is contained in:
5 files changed
+525
-43
No files matched your search
@@ -170,9 +170,14 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
our own words — never "it", because the application's name is a row and the
|
||||
body must not carry client text (it is not selectable) — then the payload as a
|
||||
bounded, scrollable card, so a long note cannot push the buttons off screen.
|
||||
"Signing as" and "Application" stay above the fold; the verifiable-but-secondary
|
||||
fields (client key, declared URL, kind number, raw tags, method, peer, "asked
|
||||
for") live in a collapsed **Details** expander. A pairing whose client declared
|
||||
"Signing as", "Application", the event **kind** and its client-requested
|
||||
**Created at** timestamp stay above the fold (kind and timestamp are part of
|
||||
what is signed); the verifiable-but-secondary fields (client key, declared URL,
|
||||
raw tags, method, peer, "asked for") live in a collapsed **Details** expander.
|
||||
Anything the dialog cannot show in full is disclosed by an `AdwBanner` above the
|
||||
fold — truncated content (against the responder's `CONTENT_LIMIT`), hidden
|
||||
tags/tag values, and a timestamp more than an hour from now — so nothing that is
|
||||
signed or encrypted is invisible (**WYSIWYS**, H2). A pairing whose client declared
|
||||
no name also gets a **name field** there — under "Application", above the
|
||||
Details — because that is the one prompt where the user decides to trust an
|
||||
app and can still give it a name; the entered name travels back in the
|
||||
|
||||
+15
-1
@@ -70,15 +70,29 @@ pub enum Request {
|
||||
/// show it in full; it is **not** reduced to a short preview, because
|
||||
/// the original bytes are what gets signed.
|
||||
content: String,
|
||||
/// Total characters in the full content, so the UI can disclose a cut
|
||||
/// against the bound the responder applied.
|
||||
content_chars: usize,
|
||||
/// The event's tags, in order, for the Tags group below the content.
|
||||
/// Empty when the event has none.
|
||||
tags: Vec<TagView>,
|
||||
/// Tags dropped by the display cap, and tag values dropped by the field
|
||||
/// cap or the strict parser. Shown so nothing signed is hidden silently.
|
||||
tags_omitted: usize,
|
||||
tag_fields_omitted: usize,
|
||||
/// The client-requested NIP-01 `created_at`. Displayed, because a
|
||||
/// replaceable event with a far-future timestamp is a real hazard.
|
||||
created_at: Timestamp,
|
||||
},
|
||||
/// A message would be encrypted to someone.
|
||||
Encrypt {
|
||||
method: &'static str,
|
||||
peer: String,
|
||||
preview: String,
|
||||
/// The full plaintext, bounded by the responder's content limit and shown
|
||||
/// in a scrollable view (not a short preview that could hide payload).
|
||||
message: String,
|
||||
/// Total characters in the full plaintext, for the same disclosure.
|
||||
message_chars: usize,
|
||||
},
|
||||
/// A message would be decrypted from someone.
|
||||
Decrypt {
|
||||
|
||||
+208
-31
@@ -873,10 +873,17 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => {
|
||||
let kind = incoming.kind.as_u16();
|
||||
let (content_shown, content_chars) = content(&incoming.content);
|
||||
let (tags_view, tags_omitted, tag_fields_omitted) = tags(&incoming.tags);
|
||||
let request = Request::Sign {
|
||||
kind,
|
||||
content: content(&incoming.content),
|
||||
tags: tags(&incoming.tags),
|
||||
content: content_shown,
|
||||
content_chars,
|
||||
tags: tags_view,
|
||||
tags_omitted,
|
||||
// Include the non-string members the strict parser dropped.
|
||||
tag_fields_omitted: tag_fields_omitted + incoming.dropped_members,
|
||||
created_at: incoming.created_at,
|
||||
};
|
||||
let keys = authorize(
|
||||
config,
|
||||
@@ -898,10 +905,12 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
Ok(peer) => match app_identity(config, &event.pubkey) {
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => {
|
||||
let (message, message_chars) = content(payload(¶ms));
|
||||
let request = Request::Encrypt {
|
||||
method: nim_name(m),
|
||||
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
|
||||
preview: preview(payload(¶ms)),
|
||||
message,
|
||||
message_chars,
|
||||
};
|
||||
let keys = authorize(
|
||||
config,
|
||||
@@ -1254,35 +1263,68 @@ struct Incoming {
|
||||
content: String,
|
||||
created_at: Timestamp,
|
||||
tags: Vec<Tag>,
|
||||
/// Non-string members dropped from the tag arrays (counted so the dialog can
|
||||
/// disclose them rather than hiding them silently).
|
||||
dropped_members: usize,
|
||||
}
|
||||
|
||||
/// Parse the event out of a `sign_event` parameter.
|
||||
///
|
||||
/// Strict about the shapes that decide what is signed: a missing or out-of-range
|
||||
/// `kind`, a non-string `content`, or a `tags`/tag that is not an array is an
|
||||
/// error rather than a silent coercion. A `created_at` the client omitted is
|
||||
/// filled with now, as NIP-42/NIP-98/NWC clients expect.
|
||||
fn incoming(raw: Option<&String>) -> std::result::Result<Incoming, String> {
|
||||
let raw = raw.ok_or("sign_event: missing event")?;
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(raw).map_err(|error| error.to_string())?;
|
||||
|
||||
let kind = Kind::from(value["kind"].as_u64().unwrap_or(1) as u16);
|
||||
let content = value["content"].as_str().unwrap_or_default().to_string();
|
||||
let kind_number = value["kind"]
|
||||
.as_u64()
|
||||
.ok_or("sign_event: missing or non-numeric kind")?;
|
||||
let kind = Kind::from(u16::try_from(kind_number).map_err(|_| "sign_event: kind out of range")?);
|
||||
|
||||
let content = match &value["content"] {
|
||||
serde_json::Value::Null => String::new(),
|
||||
serde_json::Value::String(text) => text.clone(),
|
||||
_ => return Err("sign_event: content is not a string".to_string()),
|
||||
};
|
||||
let created_at = value["created_at"]
|
||||
.as_u64()
|
||||
.map(Timestamp::from)
|
||||
.unwrap_or_else(Timestamp::now);
|
||||
let tags: Vec<Tag> = value["tags"]
|
||||
.as_array()
|
||||
.map(|tags| {
|
||||
tags.iter()
|
||||
.filter_map(|tag| tag.as_array())
|
||||
.filter_map(|parts| Tag::parse(parts.iter().filter_map(|p| p.as_str())).ok())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut dropped_members = 0;
|
||||
let tags: Vec<Tag> = match &value["tags"] {
|
||||
serde_json::Value::Null => Vec::new(),
|
||||
serde_json::Value::Array(items) => {
|
||||
let mut parsed = Vec::with_capacity(items.len());
|
||||
for item in items {
|
||||
let serde_json::Value::Array(parts) = item else {
|
||||
return Err("sign_event: a tag is not an array".to_string());
|
||||
};
|
||||
let mut fields = Vec::with_capacity(parts.len());
|
||||
for part in parts {
|
||||
match part.as_str() {
|
||||
Some(field) => fields.push(field.to_string()),
|
||||
None => dropped_members += 1,
|
||||
}
|
||||
}
|
||||
if let Ok(tag) = Tag::parse(fields.iter().map(String::as_str)) {
|
||||
parsed.push(tag);
|
||||
}
|
||||
}
|
||||
parsed
|
||||
}
|
||||
_ => return Err("sign_event: tags is not an array".to_string()),
|
||||
};
|
||||
|
||||
Ok(Incoming {
|
||||
kind,
|
||||
content,
|
||||
created_at,
|
||||
tags,
|
||||
dropped_members,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1324,28 +1366,32 @@ fn preview(text: &str) -> String {
|
||||
/// Much larger than [`PREVIEW_CHARS`]: the dialog renders the content readably
|
||||
/// (and can show it in full on request), so it must not be reduced to a snippet.
|
||||
/// Still bounded, so a hostile payload cannot travel unbounded over the channel.
|
||||
const CONTENT_LIMIT: usize = 32 * 1024;
|
||||
///
|
||||
/// Public within the crate so the approval dialog can disclose a cut against the
|
||||
/// same bound the responder applied.
|
||||
pub(crate) const CONTENT_LIMIT: usize = 32 * 1024;
|
||||
|
||||
/// A plain, bounded copy of attacker-controlled event content.
|
||||
/// A plain, bounded copy of attacker-controlled event content, with the total
|
||||
/// number of characters so the dialog can disclose what was cut.
|
||||
///
|
||||
/// Carriage returns are dropped (they break single-line rendering); nothing else
|
||||
/// is changed, because the original bytes are what gets signed. The UI is what
|
||||
/// decides how to present it.
|
||||
fn content(text: &str) -> String {
|
||||
fn content(text: &str) -> (String, usize) {
|
||||
let mut shown = String::new();
|
||||
let mut count = 0;
|
||||
let mut total = 0;
|
||||
for character in text.chars() {
|
||||
if character == '\r' {
|
||||
continue;
|
||||
}
|
||||
if count >= CONTENT_LIMIT {
|
||||
if total < CONTENT_LIMIT {
|
||||
shown.push(character);
|
||||
} else if total == CONTENT_LIMIT {
|
||||
shown.push('…');
|
||||
break;
|
||||
}
|
||||
shown.push(character);
|
||||
count += 1;
|
||||
total += 1;
|
||||
}
|
||||
shown
|
||||
(shown, total)
|
||||
}
|
||||
|
||||
/// How many tags travel to the dialog, and how many values of each.
|
||||
@@ -1355,17 +1401,26 @@ fn content(text: &str) -> String {
|
||||
const TAG_LIMIT: usize = 500;
|
||||
const TAG_FIELDS: usize = 8;
|
||||
|
||||
/// The event's tags, in order, for the dialog's Tags group.
|
||||
fn tags(tags: &[Tag]) -> Vec<TagView> {
|
||||
tags.iter()
|
||||
/// The event's tags, in order, for the dialog's Tags group, plus how many tags
|
||||
/// and how many tag values were dropped.
|
||||
///
|
||||
/// The dialog shows the values in full, but a hostile event must not put an
|
||||
/// unbounded list on the channel — and the user must be told what was cut.
|
||||
fn tags(tags: &[Tag]) -> (Vec<TagView>, usize, usize) {
|
||||
let mut omitted_fields = 0;
|
||||
let views: Vec<TagView> = tags
|
||||
.iter()
|
||||
.take(TAG_LIMIT)
|
||||
.filter_map(|tag| {
|
||||
let mut fields = tag.as_slice().iter();
|
||||
let name = fields.next()?.clone();
|
||||
let values = fields.take(TAG_FIELDS).cloned().collect();
|
||||
let values: Vec<String> = fields.by_ref().take(TAG_FIELDS).cloned().collect();
|
||||
omitted_fields += fields.count();
|
||||
Some(TagView { name, values })
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
let omitted_tags = tags.len().saturating_sub(TAG_LIMIT);
|
||||
(views, omitted_tags, omitted_fields)
|
||||
}
|
||||
|
||||
/// The peer pubkey that the first parameter of the nip04/nip44 calls refers to.
|
||||
@@ -2032,9 +2087,12 @@ mod tests {
|
||||
let shown = seen
|
||||
.iter()
|
||||
.find_map(|request| match request {
|
||||
Request::Sign { kind, content, tags } => {
|
||||
Some((*kind, content.clone(), tags.clone()))
|
||||
}
|
||||
Request::Sign {
|
||||
kind,
|
||||
content,
|
||||
tags,
|
||||
..
|
||||
} => Some((*kind, content.clone(), tags.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the user was asked");
|
||||
@@ -2271,6 +2329,125 @@ mod tests {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// `incoming()` is strict about the shapes that decide what is signed: a
|
||||
/// malformed event is refused rather than silently coerced (H2).
|
||||
#[test]
|
||||
fn incoming_rejects_malformed_events() {
|
||||
let parse = |value: serde_json::Value| {
|
||||
let raw = value.to_string();
|
||||
incoming(Some(&raw))
|
||||
};
|
||||
// Missing, non-numeric, and out-of-range kind.
|
||||
assert!(parse(serde_json::json!({"content": "hi"})).is_err());
|
||||
assert!(parse(serde_json::json!({"kind": "1", "content": "hi"})).is_err());
|
||||
assert!(parse(serde_json::json!({"kind": 70000, "content": "hi"})).is_err());
|
||||
// A non-string content.
|
||||
assert!(parse(serde_json::json!({"kind": 1, "content": 5})).is_err());
|
||||
// `tags` that is not an array, and a tag that is not an array.
|
||||
assert!(parse(serde_json::json!({"kind": 1, "tags": "x"})).is_err());
|
||||
assert!(parse(serde_json::json!({"kind": 1, "tags": ["x"]})).is_err());
|
||||
// A missing event is an error.
|
||||
assert!(incoming(None).is_err());
|
||||
// A well-formed event is accepted, and a null content is empty.
|
||||
let ok = parse(serde_json::json!({"kind": 1, "content": "hi", "tags": [["t", "nostr"]]}))
|
||||
.expect("a well-formed event parses");
|
||||
assert_eq!(ok.kind.as_u16(), 1);
|
||||
assert!(parse(serde_json::json!({"kind": 1, "tags": []})).is_ok());
|
||||
}
|
||||
|
||||
/// `incoming()` counts non-string tag members so the dialog can disclose
|
||||
/// them instead of dropping them silently ([R2.2]).
|
||||
#[test]
|
||||
fn incoming_counts_dropped_tag_members() {
|
||||
let raw =
|
||||
serde_json::json!({"kind": 1, "content": "hi", "tags": [["t", 5, "nostr"]]}).to_string();
|
||||
let parsed = incoming(Some(&raw)).expect("parses");
|
||||
assert_eq!(parsed.dropped_members, 1);
|
||||
assert_eq!(parsed.tags[0].as_slice().len(), 2, "the number is dropped");
|
||||
}
|
||||
|
||||
/// `content()` reports the total it was cut from, and drops `\r` from both
|
||||
/// the shown copy and the count, so the banner predicate is exact.
|
||||
#[test]
|
||||
fn content_reports_the_total_it_was_cut_from() {
|
||||
assert_eq!(content("hello"), ("hello".to_string(), 5));
|
||||
let long = "a".repeat(CONTENT_LIMIT + 10);
|
||||
let (shown, total) = content(&long);
|
||||
assert_eq!(total, CONTENT_LIMIT + 10);
|
||||
assert_eq!(shown.chars().count(), CONTENT_LIMIT + 1, "cut + one ellipsis");
|
||||
assert!(shown.ends_with('…'));
|
||||
// Exactly at the limit: no ellipsis, no truncation.
|
||||
let (shown, total) = content(&"b".repeat(CONTENT_LIMIT));
|
||||
assert_eq!(total, CONTENT_LIMIT);
|
||||
assert!(!shown.ends_with('…'));
|
||||
// Carriage returns are not part of the shown copy or the count.
|
||||
assert_eq!(content("a\r\nb"), ("a\nb".to_string(), 3));
|
||||
}
|
||||
|
||||
/// `tags()` reports how many tags and tag values it could not show.
|
||||
#[test]
|
||||
fn tags_report_what_the_dialog_cannot_show() {
|
||||
let many: Vec<Tag> = (0..3)
|
||||
.map(|index| {
|
||||
let mut parts = vec![format!("t{index}")];
|
||||
parts.extend((0..TAG_FIELDS + 2).map(|value| format!("v{value}")));
|
||||
Tag::parse(parts.iter().map(String::as_str)).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let (views, omitted_tags, omitted_fields) = tags(&many);
|
||||
assert_eq!(views.len(), 3);
|
||||
assert_eq!(omitted_tags, 0);
|
||||
assert_eq!(omitted_fields, 3 * 2, "two values per tag were dropped");
|
||||
assert_eq!(views[0].values.len(), TAG_FIELDS);
|
||||
|
||||
let over: Vec<Tag> = (0..TAG_LIMIT + 5)
|
||||
.map(|index| Tag::parse([format!("t{index}").as_str()]).unwrap())
|
||||
.collect();
|
||||
let (views, omitted_tags, omitted_fields) = tags(&over);
|
||||
assert_eq!(views.len(), TAG_LIMIT);
|
||||
assert_eq!(omitted_tags, 5);
|
||||
assert_eq!(omitted_fields, 0);
|
||||
}
|
||||
|
||||
/// The parse-time drop reaches the dialog: a `sign_event` carrying a
|
||||
/// non-string tag member is signed, and the recorded request discloses the
|
||||
/// dropped member ([R2.2] fold at the call site).
|
||||
#[tokio::test]
|
||||
async fn a_dropped_tag_member_is_disclosed_in_the_request() {
|
||||
let client = Keys::generate();
|
||||
let (approver, task, seen) = recording_approver(|_| Decision::Always);
|
||||
let config = config("ws://127.0.0.1:1", approver);
|
||||
let device = config.device_keys.public_key();
|
||||
pair(&client, &config).await;
|
||||
|
||||
let params = serde_json::json!([serde_json::json!({
|
||||
"kind": 1,
|
||||
"content": "hi",
|
||||
"tags": [["t", 5, "nostr"]],
|
||||
})
|
||||
.to_string()]);
|
||||
let request = client_request(&client, &device, "sign_event", params);
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
assert!(read_response(&response, &client, &device)["result"].is_string());
|
||||
|
||||
let seen = seen.lock().unwrap();
|
||||
let fields = seen
|
||||
.iter()
|
||||
.find_map(|request| match request {
|
||||
Request::Sign {
|
||||
tag_fields_omitted, ..
|
||||
} => Some(*tag_fields_omitted),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the user was asked");
|
||||
assert_eq!(fields, 1, "the dropped tag member is disclosed");
|
||||
drop(seen);
|
||||
task.abort();
|
||||
}
|
||||
|
||||
/// Logout forgets the application; connecting afterwards asks again.
|
||||
#[tokio::test]
|
||||
async fn logout_forgets_the_application() {
|
||||
|
||||
+275
-5
@@ -10,12 +10,14 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_channel::Receiver;
|
||||
use nostr::types::Timestamp;
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::gio;
|
||||
use gtk::gio::prelude::ApplicationExt;
|
||||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
@@ -524,6 +526,12 @@ fn details(
|
||||
.spacing(12)
|
||||
.build();
|
||||
|
||||
// Anything the dialog cannot show in full is disclosed up front (H2): a
|
||||
// truncated payload or an out-of-range timestamp must not be invisible.
|
||||
for warning in request_warnings(&question.request) {
|
||||
content.append(&banner(&warning));
|
||||
}
|
||||
|
||||
content.append(&identity_field(state, &question.identity));
|
||||
content.append(&application_field(state, client));
|
||||
// A client that declared no name: naming it sits right under "Application",
|
||||
@@ -531,13 +539,17 @@ fn details(
|
||||
if let Some(entry) = name_entry {
|
||||
content.append(&name_field(entry));
|
||||
}
|
||||
// The kind is part of what is being signed, so it sits with the payload
|
||||
// rather than collapsed under Details.
|
||||
if let Request::Sign { kind, .. } = &question.request {
|
||||
// The kind and the client-requested timestamp are part of what is being
|
||||
// signed, so they sit above the fold with the payload, not under Details.
|
||||
if let Request::Sign {
|
||||
kind, created_at, ..
|
||||
} = &question.request
|
||||
{
|
||||
content.append(&plain::text_field(
|
||||
"Kind",
|
||||
&format!("{} ({})", kind, kind::name(*kind)),
|
||||
));
|
||||
content.append(&plain::text_field("Created at", &when(*created_at)));
|
||||
}
|
||||
|
||||
match &question.request {
|
||||
@@ -549,10 +561,18 @@ fn details(
|
||||
Request::Sign {
|
||||
kind,
|
||||
content: signed,
|
||||
content_chars,
|
||||
tags,
|
||||
..
|
||||
} => {
|
||||
if content::has_content(signed) {
|
||||
content.append(&content::card(signed, *kind, widget, deadline));
|
||||
content.append(&content::card(
|
||||
signed,
|
||||
*kind,
|
||||
*content_chars > crate::signer::CONTENT_LIMIT,
|
||||
widget,
|
||||
deadline,
|
||||
));
|
||||
}
|
||||
// Tags stay in view rather than collapsed under Details, because for
|
||||
// some kinds they are the payload itself.
|
||||
@@ -560,7 +580,9 @@ fn details(
|
||||
content.append(&content::tags_card(tags, widget, deadline));
|
||||
}
|
||||
}
|
||||
Request::Encrypt { preview, .. } => content.append(&block("Message", preview)),
|
||||
Request::Encrypt { message, .. } => {
|
||||
content.append(&message_block("Message", message, widget, deadline));
|
||||
}
|
||||
Request::Decrypt { preview, .. } => content.append(&block("Ciphertext", preview)),
|
||||
}
|
||||
|
||||
@@ -761,6 +783,193 @@ fn note(text: &str) -> gtk::Label {
|
||||
label
|
||||
}
|
||||
|
||||
/// A prominent warning banner for something the dialog cannot show in full.
|
||||
///
|
||||
/// `AdwBanner` renders its title as Pango markup **by default**, so markup is
|
||||
/// turned off before the title is set. The text here is our own words (never
|
||||
/// client-supplied), but the discipline is the same everywhere.
|
||||
fn banner(text: &str) -> adw::Banner {
|
||||
let banner = adw::Banner::new("");
|
||||
banner.set_use_markup(false);
|
||||
banner.set_title(text);
|
||||
banner.set_revealed(true);
|
||||
banner
|
||||
}
|
||||
|
||||
/// A client-requested timestamp as local time, for the "Created at" row.
|
||||
fn when(created_at: Timestamp) -> String {
|
||||
glib::DateTime::from_unix_local(created_at.as_secs() as i64)
|
||||
.and_then(|time| time.format("%Y-%m-%d %H:%M"))
|
||||
.map(|formatted| formatted.to_string())
|
||||
.unwrap_or_else(|_| created_at.to_string())
|
||||
}
|
||||
|
||||
/// A coarse "3 days" / "2 hours" / "40 minutes" for a warning.
|
||||
fn human_delta(seconds: u64) -> String {
|
||||
if seconds >= 86_400 {
|
||||
format!("{} days", seconds / 86_400)
|
||||
} else if seconds >= 3_600 {
|
||||
format!("{} hours", seconds / 3_600)
|
||||
} else {
|
||||
format!("{} minutes", seconds / 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the dialog cannot show in full, as banner texts (H2).
|
||||
///
|
||||
/// Pure apart from reading the clock for the timestamp check, so the wording and
|
||||
/// the predicate are unit-testable. The point is that nothing Regent signs or
|
||||
/// encrypts is invisible without disclosure.
|
||||
fn request_warnings(request: &Request) -> Vec<String> {
|
||||
let limit = crate::signer::CONTENT_LIMIT;
|
||||
let mut warnings = Vec::new();
|
||||
match request {
|
||||
Request::Sign {
|
||||
content_chars,
|
||||
tags,
|
||||
tags_omitted,
|
||||
tag_fields_omitted,
|
||||
created_at,
|
||||
..
|
||||
} => {
|
||||
if *content_chars > limit {
|
||||
warnings.push(format!(
|
||||
"Showing the first {} KiB of {} KiB of event content.",
|
||||
limit / 1024,
|
||||
content_chars.div_ceil(1024)
|
||||
));
|
||||
}
|
||||
if *tags_omitted > 0 {
|
||||
warnings.push(format!(
|
||||
"{} of {} tags are not shown.",
|
||||
tags_omitted,
|
||||
tags.len() + tags_omitted
|
||||
));
|
||||
}
|
||||
if *tag_fields_omitted > 0 {
|
||||
warnings.push(format!("{} tag values are not shown.", tag_fields_omitted));
|
||||
}
|
||||
let now = Timestamp::now().as_secs() as i64;
|
||||
let delta = created_at.as_secs() as i64 - now;
|
||||
if delta.unsigned_abs() > 3_600 {
|
||||
let when = human_delta(delta.unsigned_abs());
|
||||
warnings.push(if delta > 0 {
|
||||
format!("The event is timestamped {when} in the future.")
|
||||
} else {
|
||||
format!("The event is timestamped {when} in the past.")
|
||||
});
|
||||
}
|
||||
}
|
||||
Request::Encrypt { message_chars, .. } if *message_chars > limit => {
|
||||
warnings.push(format!(
|
||||
"Showing the first {} KiB of {} KiB of the message.",
|
||||
limit / 1024,
|
||||
message_chars.div_ceil(1024)
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
warnings
|
||||
}
|
||||
|
||||
/// A titled, bounded, scrollable block for a long client string, with a button
|
||||
/// that opens the same text in a larger dialog — so the full message is always
|
||||
/// reachable and never hidden after a short preview.
|
||||
fn message_block(
|
||||
title: &str,
|
||||
value: &str,
|
||||
parent: &impl IsA<gtk::Widget>,
|
||||
deadline: Option<Instant>,
|
||||
) -> gtk::Box {
|
||||
let container = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
.spacing(4)
|
||||
.build();
|
||||
|
||||
let header = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Horizontal)
|
||||
.spacing(12)
|
||||
.build();
|
||||
header.append(
|
||||
>k::Label::builder()
|
||||
.label(title)
|
||||
.xalign(0.0)
|
||||
.hexpand(true)
|
||||
.css_classes(["dim-label"])
|
||||
.build(),
|
||||
);
|
||||
let view_button = gtk::Button::builder()
|
||||
.label("View full message")
|
||||
.css_classes(["flat"])
|
||||
.valign(gtk::Align::Center)
|
||||
.build();
|
||||
view_button.set_tooltip_text(Some("Show the full message"));
|
||||
header.append(&view_button);
|
||||
container.append(&header);
|
||||
|
||||
let body = plain::label(value);
|
||||
body.set_margin_top(8);
|
||||
body.set_margin_bottom(8);
|
||||
body.set_margin_start(8);
|
||||
body.set_margin_end(8);
|
||||
body.set_hexpand(true);
|
||||
|
||||
let scrolled = gtk::ScrolledWindow::builder()
|
||||
.child(&body)
|
||||
.propagate_natural_height(true)
|
||||
.max_content_height(160)
|
||||
.hscrollbar_policy(gtk::PolicyType::Never)
|
||||
.build();
|
||||
|
||||
let frame = gtk::Box::builder().css_classes(["card"]).build();
|
||||
frame.append(&scrolled);
|
||||
container.append(&frame);
|
||||
|
||||
let window = parent.root().and_downcast::<gtk::Window>();
|
||||
let full = value.to_string();
|
||||
view_button.connect_clicked(move |_| {
|
||||
present_message(window.as_ref(), &full, deadline);
|
||||
});
|
||||
container
|
||||
}
|
||||
|
||||
/// The full message in its own dialog, so a structure that grows on click can
|
||||
/// never be clipped by the approval dialog.
|
||||
fn present_message(parent: Option<>k::Window>, text: &str, deadline: Option<Instant>) {
|
||||
let body = plain::label(text);
|
||||
body.set_margin_top(12);
|
||||
body.set_margin_bottom(12);
|
||||
body.set_margin_start(12);
|
||||
body.set_margin_end(12);
|
||||
|
||||
let scrolled = gtk::ScrolledWindow::builder()
|
||||
.child(&body)
|
||||
.propagate_natural_height(true)
|
||||
.max_content_height(400)
|
||||
.hscrollbar_policy(gtk::PolicyType::Never)
|
||||
.build();
|
||||
|
||||
let header = adw::HeaderBar::new();
|
||||
let toolbar = adw::ToolbarView::new();
|
||||
toolbar.add_top_bar(&header);
|
||||
toolbar.set_content(Some(&scrolled));
|
||||
toolbar.set_size_request(plain::DIALOG_WIDTH, -1);
|
||||
|
||||
let dialog = adw::Dialog::builder()
|
||||
.title("Message")
|
||||
.follows_content_size(true)
|
||||
.child(&toolbar)
|
||||
.build();
|
||||
dialog.present(parent);
|
||||
|
||||
if let Some(left) = remaining(deadline) {
|
||||
let dialog = dialog.clone();
|
||||
glib::timeout_add_local_once(left.max(Duration::from_millis(1)), move || {
|
||||
dialog.force_close();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -790,4 +999,65 @@ mod tests {
|
||||
"An application was disconnected"
|
||||
);
|
||||
}
|
||||
|
||||
fn sign_request(
|
||||
content_chars: usize,
|
||||
tags: usize,
|
||||
tags_omitted: usize,
|
||||
tag_fields_omitted: usize,
|
||||
created_at: Timestamp,
|
||||
) -> Request {
|
||||
Request::Sign {
|
||||
kind: 1,
|
||||
content: "hi".to_string(),
|
||||
content_chars,
|
||||
tags: vec![crate::signer::approval::TagView {
|
||||
name: "t".to_string(),
|
||||
values: vec!["nostr".to_string()],
|
||||
}; tags],
|
||||
tags_omitted,
|
||||
tag_fields_omitted,
|
||||
created_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// A request the dialog can show in full carries no banners.
|
||||
#[test]
|
||||
fn a_fully_shown_request_has_no_warnings() {
|
||||
let request = sign_request(10, 1, 0, 0, Timestamp::now());
|
||||
assert!(request_warnings(&request).is_empty());
|
||||
}
|
||||
|
||||
/// Everything the dialog hides is disclosed: a truncated payload, hidden
|
||||
/// tags/fields, and an out-of-range timestamp.
|
||||
#[test]
|
||||
fn hidden_payload_and_time_are_disclosed() {
|
||||
let request = sign_request(
|
||||
crate::signer::CONTENT_LIMIT + 5,
|
||||
1,
|
||||
3,
|
||||
2,
|
||||
Timestamp::now() + Duration::from_secs(3 * 86_400),
|
||||
);
|
||||
let warnings = request_warnings(&request);
|
||||
assert_eq!(warnings.len(), 4, "{warnings:?}");
|
||||
assert!(warnings[0].contains("32 KiB"));
|
||||
assert!(warnings[1].contains("3 of 4 tags"));
|
||||
assert!(warnings[2].contains("2 tag values"));
|
||||
assert!(warnings[3].contains("future"));
|
||||
}
|
||||
|
||||
/// An encrypt message past the bound is disclosed too.
|
||||
#[test]
|
||||
fn a_long_encrypt_message_is_disclosed() {
|
||||
let request = Request::Encrypt {
|
||||
method: "nip44_encrypt",
|
||||
peer: "npub1".to_string(),
|
||||
message: "hi".to_string(),
|
||||
message_chars: crate::signer::CONTENT_LIMIT + 1,
|
||||
};
|
||||
let warnings = request_warnings(&request);
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].contains("32 KiB"));
|
||||
}
|
||||
}
|
||||
+19
-3
@@ -158,6 +158,7 @@ fn collapse(fields: Vec<Field>) -> Vec<Field> {
|
||||
pub fn card(
|
||||
content: &str,
|
||||
kind_number: u16,
|
||||
truncated: bool,
|
||||
parent: &impl IsA<gtk::Widget>,
|
||||
deadline: Option<Instant>,
|
||||
) -> gtk::Box {
|
||||
@@ -206,7 +207,7 @@ pub fn card(
|
||||
let window = parent.root().and_downcast::<gtk::Window>();
|
||||
let content = content.to_string();
|
||||
view_button.connect_clicked(move |_| {
|
||||
present_preview(window.as_ref(), &content, kind_number, deadline);
|
||||
present_preview(window.as_ref(), &content, kind_number, truncated, deadline);
|
||||
});
|
||||
|
||||
container
|
||||
@@ -446,6 +447,7 @@ fn present_preview(
|
||||
parent: Option<>k::Window>,
|
||||
content: &str,
|
||||
kind_number: u16,
|
||||
truncated: bool,
|
||||
deadline: Option<Instant>,
|
||||
) {
|
||||
let classified = view(content, kind_number);
|
||||
@@ -461,7 +463,17 @@ fn present_preview(
|
||||
let original = padded_scroller(&monospace(content));
|
||||
let stack = gtk::Stack::builder().build();
|
||||
stack.add_titled(&formatted, Some("formatted"), "Formatted");
|
||||
stack.add_titled(&original, Some("original"), "Original");
|
||||
// The "Original" page shows the *bounded* copy, so say so when a cut
|
||||
// happened: the full event content is what gets signed, not this view.
|
||||
stack.add_titled(
|
||||
&original,
|
||||
Some("original"),
|
||||
if truncated {
|
||||
"Original (first 32 KiB)"
|
||||
} else {
|
||||
"Original"
|
||||
},
|
||||
);
|
||||
header.set_title_widget(Some(>k::StackSwitcher::builder().stack(&stack).build()));
|
||||
toolbar.set_content(Some(&stack));
|
||||
} else {
|
||||
@@ -472,7 +484,11 @@ fn present_preview(
|
||||
toolbar.set_size_request(plain::DIALOG_WIDTH, -1);
|
||||
|
||||
let dialog = adw::Dialog::builder()
|
||||
.title("Event content")
|
||||
.title(if truncated {
|
||||
"Event content (first 32 KiB)"
|
||||
} else {
|
||||
"Event content"
|
||||
})
|
||||
.follows_content_size(true)
|
||||
.child(&toolbar)
|
||||
.build();
|
||||
|
||||
Reference in new issue
Block a user