encryption
runner nix smoke / nix label and flake smoke (push) Canceled after 0s

This commit is contained in:
2026-10-15 00:40:41 +00:00
parent 7bceeb255e
commit 60d2e5d80f
13 changed files with 799 additions and 118 deletions
+14 -3
View File
@@ -4,6 +4,10 @@ Small PostgreSQL-backed HTTP service for one-off tasks and daily, weekly, or
monthly routine tasks. The server generates future task occurrences and can
send due reminders through the Telegram Bot API.
The server stores an obligatory public title and an optional client-encrypted
payload. It never receives an age identity and Telegram always uses the public
title.
## Configuration
| Variable | Default | Purpose |
@@ -27,7 +31,7 @@ Create a weekly routine:
curl -X POST http://127.0.0.1:8090/v1/routines \
-H 'Content-Type: application/json' \
-d '{
"title": "Exercise",
"public_title": "Exercise",
"section": "evening",
"priority": "should",
"schedule": {"kind": "weekly", "weekdays": [1, 3, 5]},
@@ -39,7 +43,7 @@ Create a monthly routine that moves day 31 to a shorter month's final day:
```json
{
"title": "Review finances",
"public_title": "Review finances",
"section": "work",
"priority": "must",
"schedule": {
@@ -55,12 +59,19 @@ Routes:
```text
GET /health
GET /v1/tasks?date=YYYY-MM-DD
GET /v1/tasks/archived
POST /v1/tasks
POST /v1/tasks/{id}/complete
POST /v1/tasks/{id}/archive
POST /v1/tasks/{id}/restore
POST /v1/tasks/{id}/reschedule
DELETE /v1/tasks/{id}
DELETE /v1/tasks/{id} (archived tasks only)
GET /v1/routines
POST /v1/routines
```
Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
When private data is present, `encrypted_payload`, `encryption_version`, and
`content_id` must all be set. `encrypted_payload` is an ASCII-armored age file
containing the client's versioned JSON document.
+1 -1
View File
@@ -57,7 +57,7 @@ fn worker_tick(
while let Some(notification) = store.next_due_notification(&date, &time)? {
let text = format!(
"Routine reminder: {} [{} / {}]",
notification.title, notification.section, notification.priority
notification.public_title, notification.section, notification.priority
);
telegram.send_message(&text)?;
store.mark_notification_sent(notification.task_id)?;
+21 -9
View File
@@ -57,9 +57,13 @@ fn default_true() -> bool {
#[derive(Debug, Deserialize)]
pub struct CreateTask {
pub title: String,
pub public_title: String,
#[serde(default)]
pub notes: Option<String>,
pub encrypted_payload: Option<String>,
#[serde(default)]
pub encryption_version: Option<i16>,
#[serde(default)]
pub content_id: Option<String>,
pub section: Section,
pub priority: Priority,
pub scheduled_date: String,
@@ -76,8 +80,10 @@ pub struct RescheduleTask {
pub struct Task {
pub id: i64,
pub routine_id: Option<i64>,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
@@ -88,9 +94,13 @@ pub struct Task {
#[derive(Debug, Deserialize)]
pub struct CreateRoutine {
pub title: String,
pub public_title: String,
#[serde(default)]
pub notes: Option<String>,
pub encrypted_payload: Option<String>,
#[serde(default)]
pub encryption_version: Option<i16>,
#[serde(default)]
pub content_id: Option<String>,
pub section: Section,
pub priority: Priority,
pub schedule: Schedule,
@@ -101,8 +111,10 @@ pub struct CreateRoutine {
#[derive(Debug, Clone, Serialize)]
pub struct Routine {
pub id: i64,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
@@ -113,7 +125,7 @@ pub struct Routine {
#[derive(Debug, Clone)]
pub struct DueNotification {
pub task_id: i64,
pub title: String,
pub public_title: String,
pub section: String,
pub priority: String,
}
+8 -2
View File
@@ -44,6 +44,10 @@ fn handle(mut request: Request, store: &Store, api_token: Option<&str>) {
parse_json::<CreateTask>(&mut request).and_then(|input| store.create_task(input));
respond_created(request, result);
}
(&Method::Get, "/v1/tasks/archived") => match store.list_archived_tasks() {
Ok(tasks) => respond_json(request, 200, &tasks),
Err(error) => respond_failure(request, &error),
},
(&Method::Get, "/v1/routines") => match store.list_routines() {
Ok(routines) => respond_json(request, 200, &routines),
Err(error) => respond_failure(request, &error),
@@ -80,11 +84,13 @@ fn handle_task_action(mut request: Request, store: &Store, path: &str) {
let changed = match (request.method(), segments.get(3).copied()) {
(&Method::Post, Some("complete")) if segments.len() == 4 => store.complete_task(id),
(&Method::Post, Some("archive")) if segments.len() == 4 => store.archive_task(id),
(&Method::Post, Some("restore")) if segments.len() == 4 => store.restore_task(id),
(&Method::Post, Some("reschedule")) if segments.len() == 4 => {
parse_json::<RescheduleTask>(&mut request)
.and_then(|input| store.reschedule_task(id, &input.scheduled_date))
}
(&Method::Delete, None) if segments.len() == 3 => store.delete_task(id),
(&Method::Delete, None) if segments.len() == 3 => store.delete_archived_task(id),
_ => {
respond_error(request, 404, "route not found");
return;
@@ -93,7 +99,7 @@ fn handle_task_action(mut request: Request, store: &Store, path: &str) {
match changed {
Ok(true) => respond_json(request, 200, &StatusResponse { status: "ok" }),
Ok(false) => respond_error(request, 404, "task not found or already completed"),
Ok(false) => respond_error(request, 404, "task not found or action not allowed"),
Err(error) => respond_failure(request, &error),
}
}
+163 -56
View File
@@ -27,40 +27,59 @@ impl Store {
.batch_execute(
"CREATE TABLE IF NOT EXISTS routines (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
public_title TEXT NOT NULL,
encrypted_payload TEXT,
encryption_version SMALLINT,
content_id TEXT,
section TEXT NOT NULL,
priority TEXT NOT NULL,
schedule_json JSONB NOT NULL,
reminder_time TIME,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
);
CREATE TABLE IF NOT EXISTS tasks (
id BIGSERIAL PRIMARY KEY,
routine_id BIGINT REFERENCES routines(id),
title TEXT NOT NULL,
notes TEXT,
public_title TEXT NOT NULL,
encrypted_payload TEXT,
encryption_version SMALLINT,
content_id TEXT,
section TEXT NOT NULL,
priority TEXT NOT NULL,
scheduled_date DATE NOT NULL,
reminder_time TIME,
status TEXT NOT NULL DEFAULT 'pending',
status_before_archive TEXT,
completed_at TIMESTAMPTZ,
archived_at TIMESTAMPTZ,
notification_sent_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(routine_id, scheduled_date)
UNIQUE(routine_id, scheduled_date),
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
);
CREATE INDEX IF NOT EXISTS tasks_by_date
ON tasks(scheduled_date, status);
CREATE INDEX IF NOT EXISTS tasks_due_notification
ON tasks(scheduled_date, reminder_time, notification_sent_at);",
ON tasks(scheduled_date, reminder_time, notification_sent_at);
ALTER TABLE tasks
ADD COLUMN IF NOT EXISTS status_before_archive TEXT;
ALTER TABLE tasks
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;",
)
.map_err(db_error)
}
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
validate_title(&task.title)?;
validate_public_title(&task.public_title)?;
validate_encrypted_fields(
task.encrypted_payload.as_deref(),
task.encryption_version,
task.content_id.as_deref(),
)?;
let scheduled_date = parse_date(&task.scheduled_date)?;
let reminder_time = parse_reminder(task.reminder_time.as_deref())?;
@@ -68,12 +87,15 @@ impl Store {
let row = client
.query_one(
"INSERT INTO tasks (
title, notes, section, priority, scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6)
public_title, encrypted_payload, encryption_version, content_id,
section, priority, scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id",
&[
&task.title.trim(),
&task.notes,
&task.public_title.trim(),
&task.encrypted_payload,
&task.encryption_version,
&task.content_id,
&task.section.as_str(),
&task.priority.as_str(),
&scheduled_date,
@@ -89,11 +111,13 @@ impl Store {
let mut client = self.connect()?;
let rows = client
.query(
"SELECT id, routine_id, title, notes, section, priority,
"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 != 'archived'
ORDER BY
CASE section
WHEN 'morning' THEN 0
@@ -109,25 +133,24 @@ impl Store {
&[&date],
)
.map_err(db_error)?;
Ok(rows
.into_iter()
.map(|row| {
let scheduled_date: NaiveDate = row.get(6);
let reminder_time: Option<NaiveTime> = row.get(7);
Task {
id: row.get(0),
routine_id: row.get(1),
title: row.get(2),
notes: row.get(3),
section: row.get(4),
priority: row.get(5),
scheduled_date: scheduled_date.to_string(),
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
status: row.get(8),
completed_at: row.get(9),
}
})
.collect())
Ok(rows.into_iter().map(task_from_row).collect())
}
pub fn list_archived_tasks(&self) -> Result<Vec<Task>> {
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 status = 'archived'
ORDER BY archived_at DESC, id DESC",
&[],
)
.map_err(db_error)?;
Ok(rows.into_iter().map(task_from_row).collect())
}
pub fn complete_task(&self, id: i64) -> Result<bool> {
@@ -136,7 +159,7 @@ impl Store {
.execute(
"UPDATE tasks
SET status = 'completed', completed_at = now()
WHERE id = $1 AND status != 'completed'",
WHERE id = $1 AND status NOT IN ('completed', 'archived')",
&[&id],
)
.map(|changed| changed == 1)
@@ -150,23 +173,61 @@ impl Store {
.execute(
"UPDATE tasks
SET scheduled_date = $1, notification_sent_at = NULL
WHERE id = $2",
WHERE id = $2 AND status != 'archived'",
&[&date, &id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn delete_task(&self, id: i64) -> Result<bool> {
pub fn archive_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute("DELETE FROM tasks WHERE id = $1", &[&id])
.execute(
"UPDATE tasks
SET status_before_archive = status,
status = 'archived',
archived_at = now()
WHERE id = $1 AND status != 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn restore_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute(
"UPDATE tasks
SET status = COALESCE(status_before_archive, 'pending'),
status_before_archive = NULL,
archived_at = NULL
WHERE id = $1 AND status = 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn delete_archived_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute(
"DELETE FROM tasks WHERE id = $1 AND status = 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn create_routine(&self, routine: CreateRoutine) -> Result<i64> {
validate_title(&routine.title)?;
validate_public_title(&routine.public_title)?;
validate_encrypted_fields(
routine.encrypted_payload.as_deref(),
routine.encryption_version,
routine.content_id.as_deref(),
)?;
validate_schedule(&routine.schedule)?;
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
let schedule_json = serde_json::to_value(&routine.schedule).map_err(json_error)?;
@@ -175,12 +236,15 @@ impl Store {
let row = client
.query_one(
"INSERT INTO routines (
title, notes, section, priority, schedule_json, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6)
public_title, encrypted_payload, encryption_version, content_id,
section, priority, schedule_json, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id",
&[
&routine.title.trim(),
&routine.notes,
&routine.public_title.trim(),
&routine.encrypted_payload,
&routine.encryption_version,
&routine.content_id,
&routine.section.as_str(),
&routine.priority.as_str(),
&schedule_json,
@@ -195,7 +259,8 @@ impl Store {
let mut client = self.connect()?;
let rows = client
.query(
"SELECT id, title, notes, section, priority, schedule_json,
"SELECT id, public_title, encrypted_payload, encryption_version,
content_id, section, priority, schedule_json,
reminder_time, enabled
FROM routines ORDER BY id",
&[],
@@ -203,18 +268,20 @@ impl Store {
.map_err(db_error)?;
rows.into_iter()
.map(|row| {
let schedule_json: serde_json::Value = row.get(5);
let schedule_json: serde_json::Value = row.get(7);
let schedule = serde_json::from_value(schedule_json).map_err(json_error)?;
let reminder_time: Option<NaiveTime> = row.get(6);
let reminder_time: Option<NaiveTime> = row.get(8);
Ok(Routine {
id: row.get(0),
title: row.get(1),
notes: row.get(2),
section: row.get(3),
priority: row.get(4),
public_title: row.get(1),
encrypted_payload: row.get(2),
encryption_version: row.get(3),
content_id: row.get(4),
section: row.get(5),
priority: row.get(6),
schedule,
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
enabled: row.get(7),
enabled: row.get(9),
})
})
.collect()
@@ -237,14 +304,17 @@ impl Store {
inserted += client
.execute(
"INSERT INTO tasks (
routine_id, title, notes, section, priority,
routine_id, public_title, encrypted_payload,
encryption_version, content_id, section, priority,
scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7)
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (routine_id, scheduled_date) DO NOTHING",
&[
&routine.id,
&routine.title,
&routine.notes,
&routine.public_title,
&routine.encrypted_payload,
&routine.encryption_version,
&routine.content_id,
&routine.section,
&routine.priority,
&date,
@@ -263,7 +333,7 @@ impl Store {
let mut client = self.connect()?;
let row = client
.query_opt(
"SELECT id, title, section, priority
"SELECT id, public_title, section, priority
FROM tasks
WHERE scheduled_date = $1
AND reminder_time IS NOT NULL
@@ -277,7 +347,7 @@ impl Store {
.map_err(db_error)?;
Ok(row.map(|row| DueNotification {
task_id: row.get(0),
title: row.get(1),
public_title: row.get(1),
section: row.get(2),
priority: row.get(3),
}))
@@ -295,7 +365,26 @@ impl Store {
}
}
fn validate_title(title: &str) -> Result<()> {
fn task_from_row(row: postgres::Row) -> Task {
let scheduled_date: NaiveDate = row.get(8);
let reminder_time: Option<NaiveTime> = row.get(9);
Task {
id: row.get(0),
routine_id: row.get(1),
public_title: row.get(2),
encrypted_payload: row.get(3),
encryption_version: row.get(4),
content_id: row.get(5),
section: row.get(6),
priority: row.get(7),
scheduled_date: scheduled_date.to_string(),
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
status: row.get(10),
completed_at: row.get(11),
}
}
fn validate_public_title(title: &str) -> Result<()> {
if title.trim().is_empty() {
Err("title must not be empty".to_owned())
} else if title.len() > 300 {
@@ -305,6 +394,24 @@ fn validate_title(title: &str) -> Result<()> {
}
}
fn validate_encrypted_fields(
payload: Option<&str>,
version: Option<i16>,
content_id: Option<&str>,
) -> Result<()> {
if payload.map(str::len).unwrap_or(0) > 128 * 1024 {
return Err("encrypted_payload must be at most 128 KiB".to_owned());
}
if content_id.map(str::len).unwrap_or(0) > 128 {
return Err("content_id must be at most 128 bytes".to_owned());
}
if payload.is_some() == version.is_some() && version.is_some() == content_id.is_some() {
Ok(())
} else {
Err("encrypted_payload, encryption_version, and content_id must be set together".to_owned())
}
}
fn parse_date(date: &str) -> Result<NaiveDate> {
NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| "date must use YYYY-MM-DD".to_owned())
}
+20 -2
View File
@@ -10,6 +10,22 @@ 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` enables encryption of private titles and notes.
- `ROUTINE_AGE_IDENTITY_FILE` points to the local age identity used for
decryption. The identity is never sent to the server.
Generate an identity and configure the client:
```sh
age-keygen -o ~/.config/routine/identity.txt
export ROUTINE_AGE_RECIPIENT='age1...'
export ROUTINE_AGE_IDENTITY_FILE="$HOME/.config/routine/identity.txt"
```
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.
Notes are always inside the encrypted JSON.
Because the production server is loopback-only, either run the TUI on
`hectic-lab` or open a local tunnel first:
@@ -20,11 +36,13 @@ ssh -N -L 8090:127.0.0.1:8090 hectic-lab
Keys:
- `Tab`: switch between tasks and routines.
- `Tab`: switch between tasks, routines, and the archive.
- `h`/`l`: previous/next day; `t`: today.
- `j`/`k`: move selection; `r`: refresh; `q`: quit.
- `a`: add a task or routine; `Ctrl+S`: save a form; `Esc`: cancel.
- `Space`: complete task; `s`: reschedule; `x`: delete.
- On Tasks, `Space` completes, `s` reschedules, and `x` archives after confirmation.
- On Archive, `u` restores to the original day and section; `x` permanently
deletes after confirmation.
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
+9 -1
View File
@@ -1,6 +1,8 @@
{
cargoToml,
age,
lib,
makeWrapper,
nativeBuildInputs,
pkgs,
...
@@ -12,10 +14,16 @@ in
version = cargo.package.version;
src = ./.;
inherit nativeBuildInputs;
nativeBuildInputs = nativeBuildInputs ++ [ makeWrapper ];
nativeCheckInputs = [ age ];
cargoLock.lockFile = ./Cargo.lock;
doCheck = true;
postFixup = ''
wrapProgram $out/bin/routine-tui \
--prefix PATH : ${lib.makeBinPath [ age ]}
'';
meta = {
description = cargo.package.description;
license = lib.licenses.mit;
+12
View File
@@ -24,6 +24,10 @@ impl ApiClient {
self.get("/v1/routines")
}
pub fn list_archived_tasks(&self) -> Result<Vec<Task>, String> {
self.get("/v1/tasks/archived")
}
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
self.send_json("/v1/tasks", task)
}
@@ -36,6 +40,14 @@ impl ApiClient {
self.send_empty("POST", &format!("/v1/tasks/{id}/complete"))
}
pub fn archive_task(&self, id: i64) -> Result<(), String> {
self.send_empty("POST", &format!("/v1/tasks/{id}/archive"))
}
pub fn restore_task(&self, id: i64) -> Result<(), String> {
self.send_empty("POST", &format!("/v1/tasks/{id}/restore"))
}
pub fn delete_task(&self, id: i64) -> Result<(), String> {
self.send_empty("DELETE", &format!("/v1/tasks/{id}"))
}
+192 -28
View File
@@ -2,12 +2,14 @@ use chrono::{Days, Local, NaiveDate};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::api::ApiClient;
use crate::crypto::Crypto;
use crate::model::{CreateRoutine, CreateTask, Routine, Schedule, Task};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
Tasks,
Routines,
Archive,
}
#[derive(Debug, Clone, Copy)]
@@ -49,29 +51,48 @@ pub struct Form {
pub active: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingActionKind {
Archive,
Delete,
}
#[derive(Debug, Clone)]
pub struct PendingAction {
pub task_id: i64,
pub title: String,
pub kind: PendingActionKind,
}
pub struct App {
pub api: ApiClient,
pub crypto: Crypto,
pub view: View,
pub date: NaiveDate,
pub tasks: Vec<Task>,
pub archived_tasks: Vec<Task>,
pub routines: Vec<Routine>,
pub selected: usize,
pub status: String,
pub form: Option<Form>,
pub pending_action: Option<PendingAction>,
pub quit: bool,
}
impl App {
pub fn new(api: ApiClient) -> Self {
pub fn new(api: ApiClient, crypto: Crypto) -> Self {
Self {
api,
crypto,
view: View::Tasks,
date: Local::now().date_naive(),
tasks: Vec::new(),
archived_tasks: Vec::new(),
routines: Vec::new(),
selected: 0,
status: "connecting…".to_owned(),
form: None,
pending_action: None,
quit: false,
}
}
@@ -81,11 +102,24 @@ impl App {
View::Tasks => self
.api
.list_tasks(&self.date.to_string())
.map(|tasks| self.tasks = tasks),
View::Routines => self
.api
.list_routines()
.map(|routines| self.routines = routines),
.map(|mut tasks| {
tasks
.iter_mut()
.for_each(|task| self.crypto.decrypt_task(task));
self.tasks = tasks;
}),
View::Routines => self.api.list_routines().map(|mut routines| {
routines
.iter_mut()
.for_each(|routine| self.crypto.decrypt_routine(routine));
self.routines = routines;
}),
View::Archive => self.api.list_archived_tasks().map(|mut tasks| {
tasks
.iter_mut()
.for_each(|task| self.crypto.decrypt_task(task));
self.archived_tasks = tasks;
}),
};
self.selected = self.selected.min(self.item_count().saturating_sub(1));
self.status = match result {
@@ -95,7 +129,9 @@ impl App {
}
pub fn handle_key(&mut self, key: KeyEvent) {
if self.form.is_some() {
if self.pending_action.is_some() {
self.handle_action_confirmation(key);
} else if self.form.is_some() {
self.handle_form_key(key);
} else {
self.handle_normal_key(key);
@@ -106,6 +142,7 @@ impl App {
match self.view {
View::Tasks => self.tasks.len(),
View::Routines => self.routines.len(),
View::Archive => self.archived_tasks.len(),
}
}
@@ -117,7 +154,8 @@ impl App {
KeyCode::Tab => {
self.view = match self.view {
View::Tasks => View::Routines,
View::Routines => View::Tasks,
View::Routines => View::Archive,
View::Archive => View::Tasks,
};
self.selected = 0;
self.refresh();
@@ -129,14 +167,38 @@ impl App {
self.refresh();
}
KeyCode::Char('r') => self.refresh(),
KeyCode::Char('a') => self.open_create_form(),
KeyCode::Char('a') if self.view != View::Archive => self.open_create_form(),
KeyCode::Char(' ') if self.view == View::Tasks => self.complete_selected(),
KeyCode::Char('x') if self.view == View::Tasks => self.delete_selected(),
KeyCode::Char('x') if self.view == View::Tasks => self.ask_archive_selected(),
KeyCode::Char('x') if self.view == View::Archive => self.ask_delete_selected(),
KeyCode::Char('u') if self.view == View::Archive => self.restore_selected(),
KeyCode::Char('s') if self.view == View::Tasks => self.open_reschedule_form(),
_ => {}
}
}
fn handle_action_confirmation(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
let pending = self.pending_action.take().expect("task action is pending");
let (result, success) = match pending.kind {
PendingActionKind::Archive => {
(self.api.archive_task(pending.task_id), "archived")
}
PendingActionKind::Delete => {
(self.api.delete_task(pending.task_id), "deleted permanently")
}
};
self.finish_action(result, success);
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.pending_action = None;
self.status = "action cancelled".to_owned();
}
_ => {}
}
}
fn handle_form_key(&mut self, key: KeyEvent) {
if key.code == KeyCode::Esc {
self.form = None;
@@ -195,25 +257,37 @@ impl App {
}
fn submit_task(&self, form: &Form) -> Result<(), String> {
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
self.api.create_task(&CreateTask {
title: required(form.fields[0].display(), "title")?,
section: form.fields[1].display().to_owned(),
priority: form.fields[2].display().to_owned(),
reminder_time: optional(form.fields[3].display()),
notes: optional(form.fields[4].display()),
public_title: required(form.fields[0].display(), "public title")?,
encrypted_payload: encrypted.encrypted_payload,
encryption_version: encrypted.encryption_version,
content_id: encrypted.content_id,
section: form.fields[3].display().to_owned(),
priority: form.fields[4].display().to_owned(),
reminder_time: optional(form.fields[5].display()),
scheduled_date: self.date.to_string(),
})
}
fn submit_routine(&self, form: &Form) -> Result<(), String> {
let schedule = parse_schedule(form.fields[3].display(), form.fields[4].display())?;
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
let schedule = parse_schedule(form.fields[5].display(), form.fields[6].display())?;
self.api.create_routine(&CreateRoutine {
title: required(form.fields[0].display(), "title")?,
section: form.fields[1].display().to_owned(),
priority: form.fields[2].display().to_owned(),
public_title: required(form.fields[0].display(), "public title")?,
encrypted_payload: encrypted.encrypted_payload,
encryption_version: encrypted.encryption_version,
content_id: encrypted.content_id,
section: form.fields[3].display().to_owned(),
priority: form.fields[4].display().to_owned(),
schedule,
reminder_time: optional(form.fields[5].display()),
notes: optional(form.fields[6].display()),
reminder_time: optional(form.fields[7].display()),
})
}
@@ -221,6 +295,7 @@ impl App {
self.form = Some(match self.view {
View::Tasks => task_form(),
View::Routines => routine_form(),
View::Archive => return,
});
}
@@ -245,13 +320,37 @@ impl App {
self.finish_action(result, "completed");
}
fn delete_selected(&mut self) {
fn ask_archive_selected(&mut self) {
let Some(task) = self.tasks.get(self.selected) else {
self.status = "no task selected".to_owned();
return;
};
let result = self.api.delete_task(task.id);
self.finish_action(result, "deleted");
self.pending_action = Some(PendingAction {
task_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Archive,
});
}
fn ask_delete_selected(&mut self) {
let Some(task) = self.archived_tasks.get(self.selected) else {
self.status = "no archived task selected".to_owned();
return;
};
self.pending_action = Some(PendingAction {
task_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Delete,
});
}
fn restore_selected(&mut self) {
let Some(task) = self.archived_tasks.get(self.selected) else {
self.status = "no archived task selected".to_owned();
return;
};
let result = self.api.restore_task(task.id);
self.finish_action(result, "restored to its original day and section");
}
fn finish_action(&mut self, result: Result<(), String>, success: &str) {
@@ -292,11 +391,16 @@ fn task_form() -> Form {
Form {
kind: FormKind::Task,
fields: vec![
text_field("Title", "required", String::new()),
text_field(
"Public title",
"required; Telegram uses this",
String::new(),
),
text_field("Private title", "optional; encrypted", String::new()),
text_field("Notes", "optional; encrypted", String::new()),
choice_field("Section", &["morning", "work", "evening"]),
choice_field("Priority", &["must", "should", "optional"]),
text_field("Reminder", "optional HH:MM", String::new()),
text_field("Notes", "optional", String::new()),
],
active: 0,
}
@@ -306,13 +410,18 @@ fn routine_form() -> Form {
Form {
kind: FormKind::Routine,
fields: vec![
text_field("Title", "required", String::new()),
text_field(
"Public title",
"required; Telegram uses this",
String::new(),
),
text_field("Private title", "optional; encrypted", String::new()),
text_field("Notes", "optional; encrypted", String::new()),
choice_field("Section", &["morning", "work", "evening"]),
choice_field("Priority", &["must", "should", "optional"]),
choice_field("Repeat", &["daily", "weekly", "monthly"]),
text_field("Days", "weekly 1-7; monthly 1-31", String::new()),
text_field("Reminder", "optional HH:MM", String::new()),
text_field("Notes", "optional", String::new()),
],
active: 0,
}
@@ -398,6 +507,26 @@ fn parse_days(input: &str, maximum: u32) -> Result<Vec<u32>, String> {
mod tests {
use super::*;
fn task() -> Task {
Task {
id: 42,
routine_id: None,
public_title: "Keep me".to_owned(),
encrypted_payload: None,
encryption_version: None,
content_id: None,
section: "morning".to_owned(),
priority: "must".to_owned(),
scheduled_date: "2026-10-15".to_owned(),
reminder_time: None,
status: "pending".to_owned(),
completed_at: None,
private_title: None,
private_notes: None,
decryption_failed: false,
}
}
#[test]
fn parses_and_normalizes_weekdays() {
assert!(matches!(
@@ -413,4 +542,39 @@ mod tests {
"days must contain values 1 through 31"
);
}
#[test]
fn active_task_archives_only_after_confirmation() {
let mut app = App::new(
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
Crypto::disabled(),
);
app.tasks.push(task());
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
let pending = app.pending_action.as_ref().unwrap();
assert_eq!(pending.task_id, 42);
assert_eq!(pending.title, "Keep me");
assert_eq!(pending.kind, PendingActionKind::Archive);
app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.pending_action.is_none());
assert_eq!(app.status, "action cancelled");
}
#[test]
fn archived_task_requires_confirmation_before_permanent_delete() {
let mut app = App::new(
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
Crypto::disabled(),
);
app.view = View::Archive;
app.archived_tasks.push(task());
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
assert_eq!(
app.pending_action.as_ref().unwrap().kind,
PendingActionKind::Delete
);
}
}
+218
View File
@@ -0,0 +1,218 @@
use std::env;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::model::{EncryptedFields, PrivatePayload, Routine, Task};
const ENCRYPTION_VERSION: i16 = 1;
static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0);
pub struct Crypto {
recipient: Option<String>,
identity_file: Option<PathBuf>,
}
impl Crypto {
pub fn from_env() -> Self {
Self {
recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
}
}
#[cfg(test)]
pub fn disabled() -> Self {
Self {
recipient: None,
identity_file: None,
}
}
pub fn encrypt_optional(
&self,
private_title: Option<String>,
notes: Option<String>,
) -> Result<EncryptedFields, String> {
if private_title.is_none() && notes.is_none() {
return Ok(EncryptedFields::default());
}
let recipient = self
.recipient
.as_deref()
.ok_or_else(|| "ROUTINE_AGE_RECIPIENT is required for private fields".to_owned())?;
let content_id = new_content_id()?;
let plaintext = serde_json::to_vec(&PrivatePayload {
version: ENCRYPTION_VERSION as u8,
content_id: content_id.clone(),
private_title,
notes,
})
.map_err(|error| format!("cannot encode private fields: {error}"))?;
let encrypted_payload = run_age(
&["--encrypt", "--armor", "--recipient", recipient],
&plaintext,
)?;
let encrypted_payload = String::from_utf8(encrypted_payload)
.map_err(|_| "age returned non-UTF-8 armored output".to_owned())?;
Ok(EncryptedFields {
encrypted_payload: Some(encrypted_payload),
encryption_version: Some(ENCRYPTION_VERSION),
content_id: Some(content_id),
})
}
pub fn decrypt_task(&self, task: &mut Task) {
match self.decrypt_fields(
task.encrypted_payload.as_deref(),
task.encryption_version,
task.content_id.as_deref(),
) {
Ok(Some(private)) => {
task.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
task.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => task.decryption_failed = true,
}
}
pub fn decrypt_routine(&self, routine: &mut Routine) {
match self.decrypt_fields(
routine.encrypted_payload.as_deref(),
routine.encryption_version,
routine.content_id.as_deref(),
) {
Ok(Some(private)) => {
routine.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
routine.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => routine.decryption_failed = true,
}
}
fn decrypt_fields(
&self,
encrypted_payload: Option<&str>,
encryption_version: Option<i16>,
content_id: Option<&str>,
) -> Result<Option<PrivatePayload>, ()> {
let Some(encrypted_payload) = encrypted_payload else {
return Ok(None);
};
if encryption_version != Some(ENCRYPTION_VERSION) {
return Err(());
}
let identity_file = self.identity_file.as_ref().ok_or(())?;
let identity = identity_file.to_str().ok_or(())?;
let plaintext = run_age(
&["--decrypt", "--identity", identity],
encrypted_payload.as_bytes(),
)
.map_err(|_| ())?;
let private: PrivatePayload = serde_json::from_slice(&plaintext).map_err(|_| ())?;
if private.version != ENCRYPTION_VERSION as u8
|| Some(private.content_id.as_str()) != content_id
{
return Err(());
}
Ok(Some(private))
}
}
fn run_age(arguments: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {
let mut child = Command::new("age")
.args(arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| format!("cannot start age: {error}"))?;
child
.stdin
.take()
.ok_or_else(|| "cannot open age input".to_owned())?
.write_all(input)
.map_err(|error| format!("cannot write age input: {error}"))?;
let output = child
.wait_with_output()
.map_err(|error| format!("cannot wait for age: {error}"))?;
if output.status.success() {
Ok(output.stdout)
} else {
let detail = String::from_utf8_lossy(&output.stderr);
Err(format!("age failed: {}", detail.trim()))
}
}
fn new_content_id() -> Result<String, String> {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| "system clock is before Unix epoch".to_owned())?
.as_nanos();
let counter = CONTENT_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
let process = std::process::id() as u128;
Ok(format!("{:032x}", nanos ^ (process << 64) ^ counter))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn age_round_trip_preserves_private_json_and_content_id() {
let test_dir =
env::temp_dir().join(format!("routine-age-test-{}", new_content_id().unwrap()));
std::fs::create_dir(&test_dir).unwrap();
let identity_file = test_dir.join("identity.txt");
let generated = Command::new("age-keygen")
.args(["-o", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(generated.status.success());
let recipient = Command::new("age-keygen")
.args(["-y", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(recipient.status.success());
let crypto = Crypto {
recipient: Some(
String::from_utf8(recipient.stdout)
.unwrap()
.trim()
.to_owned(),
),
identity_file: Some(identity_file),
};
let encrypted = crypto
.encrypt_optional(
Some("Private appointment".to_owned()),
Some("Private notes".to_owned()),
)
.unwrap();
let decrypted = crypto
.decrypt_fields(
encrypted.encrypted_payload.as_deref(),
encrypted.encryption_version,
encrypted.content_id.as_deref(),
)
.unwrap()
.unwrap();
assert_eq!(decrypted.content_id, encrypted.content_id.unwrap());
assert_eq!(
decrypted.private_title.as_deref(),
Some("Private appointment")
);
assert_eq!(decrypted.notes.as_deref(), Some("Private notes"));
std::fs::remove_dir_all(test_dir).unwrap();
}
}
+3 -1
View File
@@ -1,5 +1,6 @@
mod api;
mod app;
mod crypto;
mod model;
mod ui;
@@ -17,6 +18,7 @@ use ratatui::Terminal;
use api::ApiClient;
use app::App;
use crypto::Crypto;
fn main() {
if let Err(error) = run() {
@@ -29,7 +31,7 @@ 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));
let mut app = App::new(ApiClient::new(base_url, token), Crypto::from_env());
app.refresh();
enable_raw_mode().map_err(io_error)?;
+66 -8
View File
@@ -4,24 +4,41 @@ use serde::{Deserialize, Serialize};
pub struct Task {
pub id: i64,
pub routine_id: Option<i64>,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
pub reminder_time: Option<String>,
pub status: String,
pub completed_at: Option<i64>,
#[serde(skip)]
pub private_title: Option<String>,
#[serde(skip)]
pub private_notes: Option<String>,
#[serde(skip)]
pub decryption_failed: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Routine {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
pub reminder_time: Option<String>,
pub enabled: bool,
#[serde(skip)]
pub private_title: Option<String>,
#[serde(skip)]
pub private_notes: Option<String>,
#[serde(skip)]
pub decryption_failed: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -39,8 +56,10 @@ pub enum Schedule {
#[derive(Debug, Serialize)]
pub struct CreateTask {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
@@ -49,8 +68,10 @@ pub struct CreateTask {
#[derive(Debug, Serialize)]
pub struct CreateRoutine {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
@@ -62,6 +83,43 @@ pub struct RescheduleTask {
pub scheduled_date: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PrivatePayload {
pub version: u8,
pub content_id: String,
#[serde(default)]
pub private_title: Option<String>,
#[serde(default)]
pub notes: Option<String>,
}
#[derive(Debug, Default)]
pub struct EncryptedFields {
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
}
impl Task {
pub fn visible_title(&self) -> &str {
self.private_title.as_deref().unwrap_or(&self.public_title)
}
pub fn visible_notes(&self) -> Option<&str> {
self.private_notes.as_deref()
}
}
impl Routine {
pub fn visible_title(&self) -> &str {
self.private_title.as_deref().unwrap_or(&self.public_title)
}
pub fn visible_notes(&self) -> Option<&str> {
self.private_notes.as_deref()
}
}
pub fn schedule_label(schedule: &Schedule) -> String {
match schedule {
Schedule::Daily => "daily".to_owned(),
+72 -7
View File
@@ -4,7 +4,7 @@ use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Frame;
use crate::app::{App, FormKind, View};
use crate::app::{App, FormKind, PendingActionKind, View};
use crate::model::schedule_label;
pub fn render(frame: &mut Frame, app: &App) {
@@ -29,6 +29,11 @@ pub fn render(frame: &mut Frame, app: &App) {
} else {
Style::default()
};
let archive_style = if app.view == View::Archive {
active
} else {
Style::default()
};
let date = if app.view == View::Tasks {
format!(" {} ", app.date)
} else {
@@ -38,6 +43,8 @@ pub fn render(frame: &mut Frame, app: &App) {
Span::styled(" Tasks ", tasks_style),
Span::raw(" "),
Span::styled(" Routines ", routines_style),
Span::raw(" "),
Span::styled(" Archive ", archive_style),
Span::raw(date),
]))
.block(Block::default().borders(Borders::ALL).title("Routine"));
@@ -60,11 +67,14 @@ pub fn render(frame: &mut Frame, app: &App) {
.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}",
task.section, task.priority, task.title
"{mark} {:<8} {:<8} {}{reminder}{source}{completed}{lock}",
task.section,
task.priority,
task.visible_title()
))];
if let Some(notes) = task.notes.as_deref().filter(|notes| !notes.is_empty()) {
if let Some(notes) = task.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
@@ -83,14 +93,46 @@ pub fn render(frame: &mut Frame, app: &App) {
.as_deref()
.map(|time| format!(" @{time}"))
.unwrap_or_default();
let lock = if routine.decryption_failed {
" 🔒"
} else {
""
};
let mut lines = vec![Line::from(format!(
"{enabled} {:<8} {:<8} {} — {}{reminder}",
"{enabled} {:<8} {:<8} {} — {}{reminder}{lock}",
routine.section,
routine.priority,
routine.title,
routine.visible_title(),
schedule_label(&routine.schedule)
))];
if let Some(notes) = routine.notes.as_deref().filter(|notes| !notes.is_empty()) {
if let Some(notes) = routine.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
));
}
ListItem::new(lines)
})
.collect::<Vec<_>>(),
View::Archive => app
.archived_tasks
.iter()
.map(|task| {
let reminder = task
.reminder_time
.as_deref()
.map(|time| format!(" @{time}"))
.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()
))];
if let Some(notes) = task.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
@@ -103,6 +145,7 @@ pub fn render(frame: &mut Frame, app: &App) {
let title = match app.view {
View::Tasks => "Tasks for selected day",
View::Routines => "Daily, weekly, and monthly routines",
View::Archive => "Archived tasks",
};
let list = List::new(items)
.block(Block::default().borders(Borders::ALL).title(title))
@@ -117,6 +160,7 @@ pub fn render(frame: &mut Frame, app: &App) {
"q quit Tab routines h/l day t today j/k move a add Space complete s move x delete r refresh"
}
View::Routines => "q quit Tab tasks j/k move a add routine r refresh",
View::Archive => "q quit Tab tasks j/k move u restore x delete permanently r refresh",
};
let footer = Paragraph::new(vec![
Line::from(help),
@@ -162,6 +206,27 @@ pub fn render(frame: &mut Frame, app: &App) {
.block(Block::default().borders(Borders::ALL).title(title));
frame.render_widget(dialog, area);
}
if let Some(pending) = &app.pending_action {
let area = centered_rect(60, 7, frame.area());
frame.render_widget(Clear, area);
let (verb, title) = match pending.kind {
PendingActionKind::Archive => ("Archive", "Confirm archive"),
PendingActionKind::Delete => ("Permanently delete", "Confirm permanent deletion"),
};
let dialog = Paragraph::new(vec![
Line::from(format!("{verb} task “{}”?", pending.title)),
Line::from(""),
Line::styled(
"y: confirm • n/Esc: cancel",
Style::default().fg(Color::Yellow),
),
])
.alignment(Alignment::Center)
.wrap(Wrap { trim: true })
.block(Block::default().borders(Borders::ALL).title(title));
frame.render_widget(dialog, area);
}
}
fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect {