diff --git a/package/routine-server/README.md b/package/routine-server/README.md index 9ccce850..323f3b15 100644 --- a/package/routine-server/README.md +++ b/package/routine-server/README.md @@ -59,6 +59,7 @@ Routes: ```text GET /health GET /v1/tasks?date=YYYY-MM-DD +GET /v1/tasks/overdue?before=YYYY-MM-DD GET /v1/tasks/archived POST /v1/tasks PUT /v1/tasks/{id} diff --git a/package/routine-server/src/server.rs b/package/routine-server/src/server.rs index 7ec93f0e..a716239b 100644 --- a/package/routine-server/src/server.rs +++ b/package/routine-server/src/server.rs @@ -40,6 +40,14 @@ fn handle(mut request: Request, store: &Store, api_token: Option<&str>) { Err(error) => respond_failure(request, &error), } } + (&Method::Get, "/v1/tasks/overdue") => { + let before = query_parameter(&query, "before") + .unwrap_or_else(|| Local::now().date_naive().to_string()); + match store.list_overdue_tasks(&before) { + Ok(tasks) => respond_json(request, 200, &tasks), + Err(error) => respond_failure(request, &error), + } + } (&Method::Post, "/v1/tasks") => { let result = parse_json::(&mut request).and_then(|input| store.create_task(input)); diff --git a/package/routine-server/src/store.rs b/package/routine-server/src/store.rs index db78c7d2..3a50f1e2 100644 --- a/package/routine-server/src/store.rs +++ b/package/routine-server/src/store.rs @@ -265,6 +265,36 @@ impl Store { Ok(rows.into_iter().map(task_from_row).collect()) } + pub fn list_overdue_tasks(&self, before: &str) -> Result> { + let before = parse_date(before)?; + let mut client = self.connect()?; + let rows = client + .query( + "SELECT id, routine_id, public_title, encrypted_payload, + encryption_version, content_id, section, priority, + scheduled_date, reminder_time, status, + EXTRACT(EPOCH FROM completed_at)::BIGINT + FROM tasks + WHERE scheduled_date < $1 + AND status = 'pending' + ORDER BY scheduled_date, + CASE section + WHEN 'morning' THEN 0 + WHEN 'work' THEN 1 + ELSE 2 + END, + CASE priority + WHEN 'must' THEN 0 + WHEN 'should' THEN 1 + ELSE 2 + END, + id", + &[&before], + ) + .map_err(db_error)?; + Ok(rows.into_iter().map(task_from_row).collect()) + } + pub fn list_archived_tasks(&self) -> Result> { let mut client = self.connect()?; let rows = client diff --git a/package/routine-tui/README.md b/package/routine-tui/README.md index 00d8fbe7..79cf0884 100644 --- a/package/routine-tui/README.md +++ b/package/routine-tui/README.md @@ -10,19 +10,30 @@ Configuration: - `ROUTINE_API_URL` defaults to `http://127.0.0.1:8090`. - `ROUTINE_API_TOKEN` is sent as a bearer token when set. -- `ROUTINE_AGE_RECIPIENT` pre-fills this device's public recipient when it is - registered in the Devices view. - `ROUTINE_AGE_IDENTITY_FILE` points to the local age identity used for decryption. The identity is never sent to the server. +- `ROUTINE_AGE_IDENTITY_COMMAND` is an alternative command that prints the age + identity to stdout. It runs once before the TUI starts, so password prompts + use the normal terminal. Its output is stored in a temporary `0600` file and + removed when the client exits. Generate an identity and configure the client: ```sh age-keygen -o ~/.config/routine/identity.txt -export ROUTINE_AGE_RECIPIENT='age1...' +age-keygen -y ~/.config/routine/identity.txt # paste this age1... value in Devices export ROUTINE_AGE_IDENTITY_FILE="$HOME/.config/routine/identity.txt" ``` +Alternatively, load the identity from a password manager: + +```sh +export ROUTINE_AGE_IDENTITY_COMMAND='pass show routine/age-identity' +``` + +Set only one identity source. The command must print the identity itself, not a +path, and must send prompts or diagnostics to the terminal rather than stdout. + Every task and routine has a required public title used by Telegram. When a private title decrypts successfully, the TUI displays it instead. If no private title exists—or the identity is unavailable—the TUI displays the public title. @@ -57,3 +68,7 @@ Weekly routine days use ISO numbers (`1` Monday through `7` Sunday). Monthly days use `1` through `31`; days beyond the end of a short month clamp to its last day. +On today's Tasks screen, pending tasks from earlier dates appear first as +`Overdue`, with their original scheduled date. Completing, rescheduling, +editing, and archiving work the same way as for today's tasks. + diff --git a/package/routine-tui/src/api.rs b/package/routine-tui/src/api.rs index 45201862..e4e24f46 100644 --- a/package/routine-tui/src/api.rs +++ b/package/routine-tui/src/api.rs @@ -23,6 +23,10 @@ impl ApiClient { self.get(&format!("/v1/tasks?date={date}")) } + pub fn list_overdue_tasks(&self, before: &str) -> Result, String> { + self.get(&format!("/v1/tasks/overdue?before={before}")) + } + pub fn list_routines(&self) -> Result, String> { self.get("/v1/routines") } diff --git a/package/routine-tui/src/app.rs b/package/routine-tui/src/app.rs index eb8c17dd..3e43fa81 100644 --- a/package/routine-tui/src/app.rs +++ b/package/routine-tui/src/app.rs @@ -75,6 +75,7 @@ pub struct App { pub crypto: Crypto, pub view: View, pub date: NaiveDate, + pub overdue_tasks: Vec, pub tasks: Vec, pub archived_tasks: Vec, pub routines: Vec, @@ -93,6 +94,7 @@ impl App { crypto, view: View::Tasks, date: Local::now().date_naive(), + overdue_tasks: Vec::new(), tasks: Vec::new(), archived_tasks: Vec::new(), routines: Vec::new(), @@ -107,15 +109,7 @@ impl App { pub fn refresh(&mut self) { let result = match self.view { - View::Tasks => self - .api - .list_tasks(&self.date.to_string()) - .map(|mut tasks| { - tasks - .iter_mut() - .for_each(|task| self.crypto.decrypt_task(task)); - self.tasks = tasks; - }), + View::Tasks => self.refresh_tasks(), View::Routines => self.api.list_routines().map(|mut routines| { routines .iter_mut() @@ -151,13 +145,41 @@ impl App { pub fn item_count(&self) -> usize { match self.view { - View::Tasks => self.tasks.len(), + View::Tasks => self.overdue_tasks.len() + self.tasks.len(), View::Routines => self.routines.len(), View::Archive => self.archived_tasks.len(), View::Devices => self.devices.len(), } } + fn refresh_tasks(&mut self) -> Result<(), String> { + let date = self.date.to_string(); + let mut tasks = self.api.list_tasks(&date)?; + tasks + .iter_mut() + .for_each(|task| self.crypto.decrypt_task(task)); + + let mut overdue_tasks = if self.date == Local::now().date_naive() { + self.api.list_overdue_tasks(&date)? + } else { + Vec::new() + }; + overdue_tasks + .iter_mut() + .for_each(|task| self.crypto.decrypt_task(task)); + self.tasks = tasks; + self.overdue_tasks = overdue_tasks; + Ok(()) + } + + fn selected_task(&self) -> Option<&Task> { + self.overdue_tasks.get(self.selected).or_else(|| { + self.selected + .checked_sub(self.overdue_tasks.len()) + .and_then(|index| self.tasks.get(index)) + }) + } + fn handle_normal_key(&mut self, key: KeyEvent) { match key.code { KeyCode::Char('q') => self.quit = true, @@ -355,12 +377,12 @@ impl App { View::Tasks => task_form(), View::Routines => routine_form(), View::Archive => return, - View::Devices => device_form(self.crypto.local_recipient().to_owned()), + View::Devices => device_form(), }); } fn open_reschedule_form(&mut self) { - let Some(task) = self.tasks.get(self.selected) else { + let Some(task) = self.selected_task() else { self.status = "no task selected".to_owned(); return; }; @@ -372,7 +394,7 @@ impl App { } fn open_edit_task_form(&mut self) { - let Some(task) = self.tasks.get(self.selected) else { + let Some(task) = self.selected_task() else { self.status = "no task selected".to_owned(); return; }; @@ -384,7 +406,7 @@ impl App { } fn complete_selected(&mut self) { - let Some(task) = self.tasks.get(self.selected) else { + let Some(task) = self.selected_task() else { self.status = "no task selected".to_owned(); return; }; @@ -393,7 +415,7 @@ impl App { } fn ask_archive_selected(&mut self) { - let Some(task) = self.tasks.get(self.selected) else { + let Some(task) = self.selected_task() else { self.status = "no task selected".to_owned(); return; }; @@ -547,12 +569,12 @@ fn routine_form() -> Form { } } -fn device_form(recipient: String) -> Form { +fn device_form() -> Form { Form { kind: FormKind::Device, fields: vec![ text_field("Device name", "required", String::new()), - text_field("AGE recipient", "public key", recipient), + text_field("AGE recipient", "public key", String::new()), ], active: 0, } @@ -711,6 +733,24 @@ mod tests { assert_eq!(app.status, "action cancelled"); } + #[test] + fn overdue_tasks_are_selected_before_todays_tasks() { + let mut app = App::new( + ApiClient::new("http://127.0.0.1:1".to_owned(), None), + Crypto::disabled(), + ); + let overdue = task(); + let mut today = task(); + today.id = 43; + app.overdue_tasks.push(overdue); + app.tasks.push(today); + + assert_eq!(app.item_count(), 2); + assert_eq!(app.selected_task().unwrap().id, 42); + app.selected = 1; + assert_eq!(app.selected_task().unwrap().id, 43); + } + #[test] fn archived_task_requires_confirmation_before_permanent_delete() { let mut app = App::new( diff --git a/package/routine-tui/src/crypto.rs b/package/routine-tui/src/crypto.rs index 24521dbb..c779f847 100644 --- a/package/routine-tui/src/crypto.rs +++ b/package/routine-tui/src/crypto.rs @@ -1,5 +1,9 @@ use std::env; +use std::fs::OpenOptions; use std::io::Write; +use std::os::unix::fs::OpenOptionsExt; +#[cfg(test)] +use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -11,23 +15,50 @@ const ENCRYPTION_VERSION: i16 = 1; static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0); pub struct Crypto { - local_recipient: Option, identity_file: Option, + temporary_identity_file: Option, } impl Crypto { - pub fn from_env() -> Self { - Self { - local_recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(), - identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from), + pub fn from_env() -> Result { + Self::from_configuration( + env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from), + env::var("ROUTINE_AGE_IDENTITY_COMMAND").ok(), + ) + } + + fn from_configuration( + identity_file: Option, + identity_command: Option, + ) -> Result { + match (identity_file, identity_command) { + (Some(_), Some(_)) => Err( + "set only one of ROUTINE_AGE_IDENTITY_FILE or ROUTINE_AGE_IDENTITY_COMMAND" + .to_owned(), + ), + (Some(identity_file), None) => Ok(Self { + identity_file: Some(identity_file), + temporary_identity_file: None, + }), + (None, Some(command)) => { + let identity_file = run_identity_command(&command)?; + Ok(Self { + identity_file: Some(identity_file.clone()), + temporary_identity_file: Some(identity_file), + }) + } + (None, None) => Ok(Self { + identity_file: None, + temporary_identity_file: None, + }), } } #[cfg(test)] pub fn disabled() -> Self { Self { - local_recipient: None, identity_file: None, + temporary_identity_file: None, } } @@ -68,10 +99,6 @@ impl Crypto { }) } - pub fn local_recipient(&self) -> &str { - self.local_recipient.as_deref().unwrap_or("") - } - pub fn decrypt_task(&self, task: &mut Task) { match self.decrypt_fields( task.encrypted_payload.as_deref(), @@ -139,6 +166,49 @@ impl Crypto { } } +impl Drop for Crypto { + fn drop(&mut self) { + if let Some(path) = &self.temporary_identity_file { + let _ = std::fs::remove_file(path); + } + } +} + +fn run_identity_command(command: &str) -> Result { + if command.trim().is_empty() { + return Err("ROUTINE_AGE_IDENTITY_COMMAND must not be empty".to_owned()); + } + let output = Command::new("sh") + .args(["-c", command]) + .stdin(Stdio::inherit()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .output() + .map_err(|error| format!("cannot start ROUTINE_AGE_IDENTITY_COMMAND: {error}"))?; + if !output.status.success() { + return Err(format!( + "ROUTINE_AGE_IDENTITY_COMMAND exited with {}", + output.status + )); + } + if output.stdout.iter().all(u8::is_ascii_whitespace) { + return Err("ROUTINE_AGE_IDENTITY_COMMAND returned an empty identity".to_owned()); + } + + let path = env::temp_dir().join(format!("routine-age-identity-{}", new_content_id()?)); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .map_err(|error| format!("cannot create temporary age identity: {error}"))?; + if let Err(error) = file.write_all(&output.stdout) { + let _ = std::fs::remove_file(&path); + return Err(format!("cannot write temporary age identity: {error}")); + } + Ok(path) +} + fn run_age(arguments: &[String], input: &[u8]) -> Result, String> { let mut child = Command::new("age") .args(arguments) @@ -195,20 +265,18 @@ mod tests { .unwrap(); assert!(recipient.status.success()); - let crypto = Crypto { - local_recipient: Some( - String::from_utf8(recipient.stdout) - .unwrap() - .trim() - .to_owned(), - ), - identity_file: Some(identity_file), - }; + let crypto = + Crypto::from_configuration(None, Some(format!("cat {}", identity_file.display()))) + .unwrap(); + let recipient = String::from_utf8(recipient.stdout) + .unwrap() + .trim() + .to_owned(); let encrypted = crypto .encrypt_optional( Some("Private appointment".to_owned()), Some("Private notes".to_owned()), - &[crypto.local_recipient().to_owned()], + &[recipient], ) .unwrap(); let decrypted = crypto @@ -258,16 +326,16 @@ mod tests { identities.push(identity); } let encryptor = Crypto { - local_recipient: None, identity_file: None, + temporary_identity_file: None, }; let encrypted = encryptor .encrypt_optional(Some("shared".to_owned()), None, &recipients) .unwrap(); for identity_file in identities { let decryptor = Crypto { - local_recipient: None, identity_file: Some(identity_file), + temporary_identity_file: None, }; let decrypted = decryptor .decrypt_fields( @@ -281,4 +349,31 @@ mod tests { } std::fs::remove_dir_all(test_dir).unwrap(); } + + #[test] + fn identity_command_is_loaded_before_use_and_removed_on_drop() { + let crypto = + Crypto::from_configuration(None, Some("printf 'AGE-SECRET-KEY-TEST\\n'".to_owned())) + .unwrap(); + let path = crypto.identity_file.clone().unwrap(); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "AGE-SECRET-KEY-TEST\n" + ); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + drop(crypto); + assert!(!path.exists()); + } + + #[test] + fn identity_sources_are_mutually_exclusive() { + let error = Crypto::from_configuration( + Some(PathBuf::from("identity.txt")), + Some("password-manager read identity".to_owned()), + ) + .err() + .unwrap(); + assert!(error.contains("set only one")); + } } diff --git a/package/routine-tui/src/main.rs b/package/routine-tui/src/main.rs index 760c1a5b..e1f6da72 100644 --- a/package/routine-tui/src/main.rs +++ b/package/routine-tui/src/main.rs @@ -31,7 +31,10 @@ fn run() -> Result<(), String> { let base_url = env::var("ROUTINE_API_URL").unwrap_or_else(|_| "http://127.0.0.1:8090".to_owned()); let token = env::var("ROUTINE_API_TOKEN").ok(); - let mut app = App::new(ApiClient::new(base_url, token), Crypto::from_env()); + // Resolve command-backed identities before raw mode so password prompts use + // the normal terminal and cannot corrupt the TUI screen. + let crypto = Crypto::from_env()?; + let mut app = App::new(ApiClient::new(base_url, token), crypto); app.refresh(); enable_raw_mode().map_err(io_error)?; diff --git a/package/routine-tui/src/ui.rs b/package/routine-tui/src/ui.rs index 8a8edd6f..e3b631c6 100644 --- a/package/routine-tui/src/ui.rs +++ b/package/routine-tui/src/ui.rs @@ -5,7 +5,7 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra use ratatui::Frame; use crate::app::{App, FormKind, PendingActionKind, View}; -use crate::model::schedule_label; +use crate::model::{schedule_label, Task}; pub fn render(frame: &mut Frame, app: &App) { let rows = Layout::vertical([ @@ -59,36 +59,10 @@ pub fn render(frame: &mut Frame, app: &App) { let items = match app.view { View::Tasks => app - .tasks + .overdue_tasks .iter() - .map(|task| { - let mark = if task.status == "completed" { - "✓" - } else { - "○" - }; - let reminder = task - .reminder_time - .as_deref() - .map(|time| format!(" @{time}")) - .unwrap_or_default(); - let source = task.routine_id.map(|_| " ↻").unwrap_or_default(); - let completed = task.completed_at.map(|_| " done").unwrap_or_default(); - let lock = if task.decryption_failed { " 🔒" } else { "" }; - let mut lines = vec![Line::from(format!( - "{mark} {:<8} {:<8} {}{reminder}{source}{completed}{lock}", - task.section, - task.priority, - task.visible_title() - ))]; - if let Some(notes) = task.visible_notes() { - lines.push(Line::styled( - format!(" {notes}"), - Style::default().fg(Color::DarkGray), - )); - } - ListItem::new(lines) - }) + .map(|task| task_list_item(task, true)) + .chain(app.tasks.iter().map(|task| task_list_item(task, false))) .collect::>(), View::Routines => app .routines @@ -105,13 +79,15 @@ pub fn render(frame: &mut Frame, app: &App) { } else { "" }; - let mut lines = vec![Line::from(format!( - "{enabled} {:<8} {:<8} {} — {}{reminder}{lock}", - routine.section, - routine.priority, - routine.visible_title(), - schedule_label(&routine.schedule) - ))]; + let mut lines = vec![Line::from(vec![ + Span::raw(format!("{enabled} {:<8} ", routine.section)), + priority_span(&routine.priority), + Span::raw(format!( + " {} — {}{reminder}{lock}", + routine.visible_title(), + schedule_label(&routine.schedule) + )), + ])]; if let Some(notes) = routine.visible_notes() { lines.push(Line::styled( format!(" {notes}"), @@ -132,13 +108,11 @@ pub fn render(frame: &mut Frame, app: &App) { .unwrap_or_default(); let source = task.routine_id.map(|_| " ↻").unwrap_or_default(); let lock = if task.decryption_failed { " 🔒" } else { "" }; - let mut lines = vec![Line::from(format!( - "▣ {} {:<8} {:<8} {}{reminder}{source}{lock}", - task.scheduled_date, - task.section, - task.priority, - task.visible_title() - ))]; + let mut lines = vec![Line::from(vec![ + Span::raw(format!("▣ {} {:<8} ", task.scheduled_date, task.section)), + priority_span(&task.priority), + Span::raw(format!(" {}{reminder}{source}{lock}", task.visible_title())), + ])]; if let Some(notes) = task.visible_notes() { lines.push(Line::styled( format!(" {notes}"), @@ -172,10 +146,16 @@ pub fn render(frame: &mut Frame, app: &App) { .collect::>(), }; let title = match app.view { - View::Tasks => "Tasks for selected day", - View::Routines => "Daily, weekly, and monthly routines", - View::Archive => "Archived tasks", - View::Devices => "Encryption devices (public recipients only)", + View::Tasks if !app.overdue_tasks.is_empty() => { + format!( + "Overdue ({}) • Tasks for selected day", + app.overdue_tasks.len() + ) + } + View::Tasks => "Tasks for selected day".to_owned(), + View::Routines => "Daily, weekly, and monthly routines".to_owned(), + View::Archive => "Archived tasks".to_owned(), + View::Devices => "Encryption devices (public recipients only)".to_owned(), }; let list = List::new(items) .block(Block::default().borders(Borders::ALL).title(title)) @@ -265,6 +245,59 @@ pub fn render(frame: &mut Frame, app: &App) { } } +fn task_list_item(task: &Task, overdue: bool) -> ListItem<'static> { + let mark = if task.status == "completed" { + "✓" + } else { + "○" + }; + let reminder = task + .reminder_time + .as_deref() + .map(|time| format!(" @{time}")) + .unwrap_or_default(); + let source = task.routine_id.map(|_| " ↻").unwrap_or_default(); + let completed = task.completed_at.map(|_| " done").unwrap_or_default(); + let lock = if task.decryption_failed { " 🔒" } else { "" }; + let prefix = if overdue { + Span::styled( + format!("⚠ {} {:<8} ", task.scheduled_date, task.section), + Style::default().fg(Color::Red).add_modifier(Modifier::BOLD), + ) + } else { + Span::raw(format!("{mark} {:<8} ", task.section)) + }; + let mut lines = vec![Line::from(vec![ + prefix, + priority_span(&task.priority), + Span::raw(format!( + " {}{reminder}{source}{completed}{lock}", + task.visible_title() + )), + ])]; + if let Some(notes) = task.visible_notes() { + lines.push(Line::styled( + format!(" {notes}"), + Style::default().fg(Color::DarkGray), + )); + } + ListItem::new(lines) +} + +fn priority_span(priority: &str) -> Span<'static> { + Span::styled(format!("{priority:<8}"), priority_style(priority)) +} + +fn priority_style(priority: &str) -> Style { + let color = match priority { + "must" => Color::Red, + "should" => Color::Yellow, + "optional" => Color::Green, + _ => Color::Reset, + }; + Style::default().fg(color).add_modifier(Modifier::BOLD) +} + fn short_recipient(recipient: &str) -> String { const EDGE: usize = 10; if recipient.chars().count() <= EDGE * 2 + 1 { @@ -298,3 +331,15 @@ fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect { ]) .split(vertical[1])[1] } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn priorities_have_distinct_colors() { + assert_eq!(priority_style("must").fg, Some(Color::Red)); + assert_eq!(priority_style("should").fg, Some(Color::Yellow)); + assert_eq!(priority_style("optional").fg, Some(Color::Green)); + } +}