This commit is contained in:
@@ -4,9 +4,9 @@ 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.
|
||||
The server stores an obligatory public title, an optional client-encrypted
|
||||
payload, and the public age recipients of registered devices. It never receives
|
||||
an age identity and Telegram always uses the public title.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -68,6 +68,10 @@ POST /v1/tasks/{id}/reschedule
|
||||
DELETE /v1/tasks/{id} (archived tasks only)
|
||||
GET /v1/routines
|
||||
POST /v1/routines
|
||||
GET /v1/encryption/devices
|
||||
GET /v1/encryption/recipients
|
||||
POST /v1/encryption/devices
|
||||
POST /v1/encryption/devices/{id}/revoke
|
||||
```
|
||||
|
||||
Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
|
||||
@@ -75,3 +79,7 @@ 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.
|
||||
|
||||
Only active device recipients are returned for encryption. Revocation affects
|
||||
new payloads; it cannot make ciphertext that a device already received
|
||||
unreadable.
|
||||
|
||||
@@ -130,6 +130,29 @@ pub struct DueNotification {
|
||||
pub priority: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateEncryptionDevice {
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct EncryptionDevice {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
pub status: String,
|
||||
pub created_at: i64,
|
||||
pub revoked_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct EncryptionRecipient {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IdResponse {
|
||||
pub id: i64,
|
||||
|
||||
@@ -4,7 +4,8 @@ use serde::Serialize;
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::model::{
|
||||
CreateRoutine, CreateTask, ErrorResponse, IdResponse, RescheduleTask, StatusResponse,
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, ErrorResponse, IdResponse, RescheduleTask,
|
||||
StatusResponse,
|
||||
};
|
||||
use crate::store::Store;
|
||||
|
||||
@@ -61,10 +62,52 @@ fn handle(mut request: Request, store: &Store, api_token: Option<&str>) {
|
||||
});
|
||||
respond_created(request, result);
|
||||
}
|
||||
(&Method::Get, "/v1/encryption/devices") => match store.list_encryption_devices() {
|
||||
Ok(devices) => respond_json(request, 200, &devices),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
},
|
||||
(&Method::Get, "/v1/encryption/recipients") => match store.list_encryption_recipients() {
|
||||
Ok(recipients) => respond_json(request, 200, &recipients),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
},
|
||||
(&Method::Post, "/v1/encryption/devices") => {
|
||||
let result = parse_json::<CreateEncryptionDevice>(&mut request)
|
||||
.and_then(|input| store.create_encryption_device(input));
|
||||
respond_created(request, result);
|
||||
}
|
||||
_ if path.starts_with("/v1/encryption/devices/") => {
|
||||
handle_device_action(request, store, &path)
|
||||
}
|
||||
_ => handle_task_action(request, store, &path),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_device_action(request: Request, store: &Store, path: &str) {
|
||||
let segments: Vec<_> = path.trim_matches('/').split('/').collect();
|
||||
if segments.len() != 5
|
||||
|| segments[0] != "v1"
|
||||
|| segments[1] != "encryption"
|
||||
|| segments[2] != "devices"
|
||||
|| segments[4] != "revoke"
|
||||
|| request.method() != &Method::Post
|
||||
{
|
||||
respond_error(request, 404, "route not found");
|
||||
return;
|
||||
}
|
||||
let id = match segments[3].parse::<i64>() {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
respond_error(request, 400, "device id must be an integer");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match store.revoke_encryption_device(id) {
|
||||
Ok(true) => respond_json(request, 200, &StatusResponse { status: "ok" }),
|
||||
Ok(false) => respond_error(request, 404, "active device not found"),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_task_action(mut request: Request, store: &Store, path: &str) {
|
||||
let segments: Vec<_> = path.trim_matches('/').split('/').collect();
|
||||
if segments.len() < 3 || segments[0] != "v1" || segments[1] != "tasks" {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use chrono::{Datelike, Days, NaiveDate, NaiveTime};
|
||||
use postgres::{Client, NoTls};
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, DueNotification, Routine, Schedule, Task};
|
||||
use crate::model::{
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, DueNotification, EncryptionDevice,
|
||||
EncryptionRecipient, Routine, Schedule, Task,
|
||||
};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, String>;
|
||||
|
||||
@@ -68,11 +71,97 @@ impl Store {
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN IF NOT EXISTS status_before_archive TEXT;
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;",
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
||||
CREATE TABLE IF NOT EXISTS encryption_devices (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
age_recipient TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
revoked_at TIMESTAMPTZ,
|
||||
CHECK (status IN ('active', 'revoked')),
|
||||
CHECK ((status = 'active' AND revoked_at IS NULL)
|
||||
OR (status = 'revoked' AND revoked_at IS NOT NULL))
|
||||
);",
|
||||
)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn list_encryption_devices(&self) -> Result<Vec<EncryptionDevice>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, name, age_recipient, status,
|
||||
EXTRACT(EPOCH FROM created_at)::BIGINT,
|
||||
EXTRACT(EPOCH FROM revoked_at)::BIGINT
|
||||
FROM encryption_devices
|
||||
ORDER BY status, id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| EncryptionDevice {
|
||||
id: row.get(0),
|
||||
name: row.get(1),
|
||||
age_recipient: row.get(2),
|
||||
status: row.get(3),
|
||||
created_at: row.get(4),
|
||||
revoked_at: row.get(5),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn list_encryption_recipients(&self) -> Result<Vec<EncryptionRecipient>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, name, age_recipient
|
||||
FROM encryption_devices
|
||||
WHERE status = 'active'
|
||||
ORDER BY id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| EncryptionRecipient {
|
||||
id: row.get(0),
|
||||
name: row.get(1),
|
||||
age_recipient: row.get(2),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn create_encryption_device(&self, device: CreateEncryptionDevice) -> Result<i64> {
|
||||
let name = device.name.trim();
|
||||
let recipient = device.age_recipient.trim();
|
||||
validate_device(name, recipient)?;
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO encryption_devices (name, age_recipient)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id",
|
||||
&[&name, &recipient],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn revoke_encryption_device(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE encryption_devices
|
||||
SET status = 'revoked', revoked_at = now()
|
||||
WHERE id = $1 AND status = 'active'",
|
||||
&[&id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
|
||||
validate_public_title(&task.public_title)?;
|
||||
validate_encrypted_fields(
|
||||
@@ -394,6 +483,22 @@ fn validate_public_title(title: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_device(name: &str, recipient: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
return Err("device name must not be empty".to_owned());
|
||||
}
|
||||
if name.len() > 100 {
|
||||
return Err("device name must be at most 100 bytes".to_owned());
|
||||
}
|
||||
if recipient.is_empty() {
|
||||
return Err("age recipient must not be empty".to_owned());
|
||||
}
|
||||
if recipient.len() > 4096 || recipient.contains('\n') || recipient.contains('\r') {
|
||||
return Err("age recipient must be a single line of at most 4096 bytes".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_encrypted_fields(
|
||||
payload: Option<&str>,
|
||||
version: Option<i16>,
|
||||
@@ -527,4 +632,14 @@ mod tests {
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_encryption_device_fields() {
|
||||
assert!(validate_device("Laptop", "age1example").is_ok());
|
||||
assert_eq!(
|
||||
validate_device("", "age1example").unwrap_err(),
|
||||
"device name must not be empty"
|
||||
);
|
||||
assert!(validate_device("Laptop", "age1example\nother").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ 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_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.
|
||||
|
||||
@@ -27,6 +28,11 @@ 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.
|
||||
|
||||
Register each device in the Devices view before creating private content. The
|
||||
client fetches all active public recipients and encrypts one age payload that
|
||||
each registered device can decrypt. Revoking a device excludes it from future
|
||||
payloads but does not re-encrypt existing tasks and routines.
|
||||
|
||||
Because the production server is loopback-only, either run the TUI on
|
||||
`hectic-lab` or open a local tunnel first:
|
||||
|
||||
@@ -36,13 +42,15 @@ ssh -N -L 8090:127.0.0.1:8090 hectic-lab
|
||||
|
||||
Keys:
|
||||
|
||||
- `Tab`: switch between tasks, routines, and the archive.
|
||||
- `Tab`: switch between tasks, routines, the archive, and encryption devices.
|
||||
- `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.
|
||||
- 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.
|
||||
- On Devices, `a` registers a public age recipient and `x` revokes it after
|
||||
confirmation. Private identities remain local and must never be entered here.
|
||||
|
||||
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
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, RescheduleTask, Routine, Task};
|
||||
use crate::model::{
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, EncryptionDevice, EncryptionRecipient,
|
||||
RescheduleTask, Routine, Task,
|
||||
};
|
||||
|
||||
pub struct ApiClient {
|
||||
base_url: String,
|
||||
@@ -28,6 +31,22 @@ impl ApiClient {
|
||||
self.get("/v1/tasks/archived")
|
||||
}
|
||||
|
||||
pub fn list_encryption_devices(&self) -> Result<Vec<EncryptionDevice>, String> {
|
||||
self.get("/v1/encryption/devices")
|
||||
}
|
||||
|
||||
pub fn list_encryption_recipients(&self) -> Result<Vec<EncryptionRecipient>, String> {
|
||||
self.get("/v1/encryption/recipients")
|
||||
}
|
||||
|
||||
pub fn create_encryption_device(&self, device: &CreateEncryptionDevice) -> Result<(), String> {
|
||||
self.send_json("/v1/encryption/devices", device)
|
||||
}
|
||||
|
||||
pub fn revoke_encryption_device(&self, id: i64) -> Result<(), String> {
|
||||
self.send_empty("POST", &format!("/v1/encryption/devices/{id}/revoke"))
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
|
||||
self.send_json("/v1/tasks", task)
|
||||
}
|
||||
|
||||
+112
-16
@@ -3,13 +3,16 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use crate::api::ApiClient;
|
||||
use crate::crypto::Crypto;
|
||||
use crate::model::{CreateRoutine, CreateTask, Routine, Schedule, Task};
|
||||
use crate::model::{
|
||||
CreateEncryptionDevice, CreateRoutine, CreateTask, EncryptionDevice, Routine, Schedule, Task,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum View {
|
||||
Tasks,
|
||||
Routines,
|
||||
Archive,
|
||||
Devices,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -17,6 +20,7 @@ pub enum FormKind {
|
||||
Task,
|
||||
Routine,
|
||||
Reschedule { task_id: i64 },
|
||||
Device,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -55,11 +59,12 @@ pub struct Form {
|
||||
pub enum PendingActionKind {
|
||||
Archive,
|
||||
Delete,
|
||||
RevokeDevice,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PendingAction {
|
||||
pub task_id: i64,
|
||||
pub item_id: i64,
|
||||
pub title: String,
|
||||
pub kind: PendingActionKind,
|
||||
}
|
||||
@@ -72,6 +77,7 @@ pub struct App {
|
||||
pub tasks: Vec<Task>,
|
||||
pub archived_tasks: Vec<Task>,
|
||||
pub routines: Vec<Routine>,
|
||||
pub devices: Vec<EncryptionDevice>,
|
||||
pub selected: usize,
|
||||
pub status: String,
|
||||
pub form: Option<Form>,
|
||||
@@ -89,6 +95,7 @@ impl App {
|
||||
tasks: Vec::new(),
|
||||
archived_tasks: Vec::new(),
|
||||
routines: Vec::new(),
|
||||
devices: Vec::new(),
|
||||
selected: 0,
|
||||
status: "connecting…".to_owned(),
|
||||
form: None,
|
||||
@@ -120,6 +127,9 @@ impl App {
|
||||
.for_each(|task| self.crypto.decrypt_task(task));
|
||||
self.archived_tasks = tasks;
|
||||
}),
|
||||
View::Devices => self.api.list_encryption_devices().map(|devices| {
|
||||
self.devices = devices;
|
||||
}),
|
||||
};
|
||||
self.selected = self.selected.min(self.item_count().saturating_sub(1));
|
||||
self.status = match result {
|
||||
@@ -143,6 +153,7 @@ impl App {
|
||||
View::Tasks => self.tasks.len(),
|
||||
View::Routines => self.routines.len(),
|
||||
View::Archive => self.archived_tasks.len(),
|
||||
View::Devices => self.devices.len(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,7 +166,8 @@ impl App {
|
||||
self.view = match self.view {
|
||||
View::Tasks => View::Routines,
|
||||
View::Routines => View::Archive,
|
||||
View::Archive => View::Tasks,
|
||||
View::Archive => View::Devices,
|
||||
View::Devices => View::Tasks,
|
||||
};
|
||||
self.selected = 0;
|
||||
self.refresh();
|
||||
@@ -172,6 +184,7 @@ impl App {
|
||||
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('x') if self.view == View::Devices => self.ask_revoke_device(),
|
||||
KeyCode::Char('s') if self.view == View::Tasks => self.open_reschedule_form(),
|
||||
_ => {}
|
||||
}
|
||||
@@ -183,11 +196,15 @@ impl App {
|
||||
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")
|
||||
(self.api.archive_task(pending.item_id), "archived")
|
||||
}
|
||||
PendingActionKind::Delete => {
|
||||
(self.api.delete_task(pending.task_id), "deleted permanently")
|
||||
(self.api.delete_task(pending.item_id), "deleted permanently")
|
||||
}
|
||||
PendingActionKind::RevokeDevice => (
|
||||
self.api.revoke_encryption_device(pending.item_id),
|
||||
"device revoked for future encryption",
|
||||
),
|
||||
};
|
||||
self.finish_action(result, success);
|
||||
}
|
||||
@@ -243,6 +260,7 @@ impl App {
|
||||
FormKind::Reschedule { task_id } => {
|
||||
self.api.reschedule_task(task_id, form.fields[0].display())
|
||||
}
|
||||
FormKind::Device => self.submit_device(&form),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
@@ -257,10 +275,12 @@ 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()),
|
||||
)?;
|
||||
let private_title = optional(form.fields[1].display());
|
||||
let notes = optional(form.fields[2].display());
|
||||
let recipients = self.recipients_for(&private_title, ¬es)?;
|
||||
let encrypted = self
|
||||
.crypto
|
||||
.encrypt_optional(private_title, notes, &recipients)?;
|
||||
self.api.create_task(&CreateTask {
|
||||
public_title: required(form.fields[0].display(), "public title")?,
|
||||
encrypted_payload: encrypted.encrypted_payload,
|
||||
@@ -274,10 +294,12 @@ impl App {
|
||||
}
|
||||
|
||||
fn submit_routine(&self, form: &Form) -> Result<(), String> {
|
||||
let encrypted = self.crypto.encrypt_optional(
|
||||
optional(form.fields[1].display()),
|
||||
optional(form.fields[2].display()),
|
||||
)?;
|
||||
let private_title = optional(form.fields[1].display());
|
||||
let notes = optional(form.fields[2].display());
|
||||
let recipients = self.recipients_for(&private_title, ¬es)?;
|
||||
let encrypted = self
|
||||
.crypto
|
||||
.encrypt_optional(private_title, notes, &recipients)?;
|
||||
let schedule = parse_schedule(form.fields[5].display(), form.fields[6].display())?;
|
||||
self.api.create_routine(&CreateRoutine {
|
||||
public_title: required(form.fields[0].display(), "public title")?,
|
||||
@@ -291,11 +313,35 @@ impl App {
|
||||
})
|
||||
}
|
||||
|
||||
fn submit_device(&self, form: &Form) -> Result<(), String> {
|
||||
self.api.create_encryption_device(&CreateEncryptionDevice {
|
||||
name: required(form.fields[0].display(), "device name")?,
|
||||
age_recipient: required(form.fields[1].display(), "age recipient")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn recipients_for(
|
||||
&self,
|
||||
private_title: &Option<String>,
|
||||
notes: &Option<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
if private_title.is_none() && notes.is_none() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
self.api.list_encryption_recipients().map(|recipients| {
|
||||
recipients
|
||||
.into_iter()
|
||||
.map(|recipient| recipient.age_recipient)
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn open_create_form(&mut self) {
|
||||
self.form = Some(match self.view {
|
||||
View::Tasks => task_form(),
|
||||
View::Routines => routine_form(),
|
||||
View::Archive => return,
|
||||
View::Devices => device_form(self.crypto.local_recipient().to_owned()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -326,7 +372,7 @@ impl App {
|
||||
return;
|
||||
};
|
||||
self.pending_action = Some(PendingAction {
|
||||
task_id: task.id,
|
||||
item_id: task.id,
|
||||
title: task.visible_title().to_owned(),
|
||||
kind: PendingActionKind::Archive,
|
||||
});
|
||||
@@ -338,12 +384,28 @@ impl App {
|
||||
return;
|
||||
};
|
||||
self.pending_action = Some(PendingAction {
|
||||
task_id: task.id,
|
||||
item_id: task.id,
|
||||
title: task.visible_title().to_owned(),
|
||||
kind: PendingActionKind::Delete,
|
||||
});
|
||||
}
|
||||
|
||||
fn ask_revoke_device(&mut self) {
|
||||
let Some(device) = self.devices.get(self.selected) else {
|
||||
self.status = "no device selected".to_owned();
|
||||
return;
|
||||
};
|
||||
if device.status != "active" {
|
||||
self.status = "device is already revoked".to_owned();
|
||||
return;
|
||||
}
|
||||
self.pending_action = Some(PendingAction {
|
||||
item_id: device.id,
|
||||
title: device.name.clone(),
|
||||
kind: PendingActionKind::RevokeDevice,
|
||||
});
|
||||
}
|
||||
|
||||
fn restore_selected(&mut self) {
|
||||
let Some(task) = self.archived_tasks.get(self.selected) else {
|
||||
self.status = "no archived task selected".to_owned();
|
||||
@@ -427,6 +489,17 @@ fn routine_form() -> Form {
|
||||
}
|
||||
}
|
||||
|
||||
fn device_form(recipient: String) -> Form {
|
||||
Form {
|
||||
kind: FormKind::Device,
|
||||
fields: vec![
|
||||
text_field("Device name", "required", String::new()),
|
||||
text_field("AGE recipient", "public key", recipient),
|
||||
],
|
||||
active: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_field(label: &'static str, hint: &'static str, value: String) -> Field {
|
||||
Field {
|
||||
label,
|
||||
@@ -553,7 +626,7 @@ mod tests {
|
||||
|
||||
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.item_id, 42);
|
||||
assert_eq!(pending.title, "Keep me");
|
||||
assert_eq!(pending.kind, PendingActionKind::Archive);
|
||||
|
||||
@@ -577,4 +650,27 @@ mod tests {
|
||||
PendingActionKind::Delete
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_device_requires_confirmation_before_revocation() {
|
||||
let mut app = App::new(
|
||||
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
|
||||
Crypto::disabled(),
|
||||
);
|
||||
app.view = View::Devices;
|
||||
app.devices.push(EncryptionDevice {
|
||||
id: 7,
|
||||
name: "Laptop".to_owned(),
|
||||
age_recipient: "age1example".to_owned(),
|
||||
status: "active".to_owned(),
|
||||
created_at: 0,
|
||||
revoked_at: None,
|
||||
});
|
||||
|
||||
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
|
||||
let pending = app.pending_action.as_ref().unwrap();
|
||||
assert_eq!(pending.item_id, 7);
|
||||
assert_eq!(pending.title, "Laptop");
|
||||
assert_eq!(pending.kind, PendingActionKind::RevokeDevice);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,14 +11,14 @@ const ENCRYPTION_VERSION: i16 = 1;
|
||||
static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub struct Crypto {
|
||||
recipient: Option<String>,
|
||||
local_recipient: Option<String>,
|
||||
identity_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Crypto {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
|
||||
local_recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
|
||||
identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ impl Crypto {
|
||||
#[cfg(test)]
|
||||
pub fn disabled() -> Self {
|
||||
Self {
|
||||
recipient: None,
|
||||
local_recipient: None,
|
||||
identity_file: None,
|
||||
}
|
||||
}
|
||||
@@ -35,14 +35,16 @@ impl Crypto {
|
||||
&self,
|
||||
private_title: Option<String>,
|
||||
notes: Option<String>,
|
||||
recipients: &[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())?;
|
||||
if recipients.is_empty() {
|
||||
return Err(
|
||||
"register at least one active encryption device for private fields".to_owned(),
|
||||
);
|
||||
}
|
||||
let content_id = new_content_id()?;
|
||||
let plaintext = serde_json::to_vec(&PrivatePayload {
|
||||
version: ENCRYPTION_VERSION as u8,
|
||||
@@ -51,10 +53,12 @@ impl Crypto {
|
||||
notes,
|
||||
})
|
||||
.map_err(|error| format!("cannot encode private fields: {error}"))?;
|
||||
let encrypted_payload = run_age(
|
||||
&["--encrypt", "--armor", "--recipient", recipient],
|
||||
&plaintext,
|
||||
)?;
|
||||
let mut arguments = vec!["--encrypt".to_owned(), "--armor".to_owned()];
|
||||
for recipient in recipients {
|
||||
arguments.push("--recipient".to_owned());
|
||||
arguments.push(recipient.clone());
|
||||
}
|
||||
let encrypted_payload = run_age(&arguments, &plaintext)?;
|
||||
let encrypted_payload = String::from_utf8(encrypted_payload)
|
||||
.map_err(|_| "age returned non-UTF-8 armored output".to_owned())?;
|
||||
Ok(EncryptedFields {
|
||||
@@ -64,6 +68,10 @@ 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(),
|
||||
@@ -113,7 +121,11 @@ impl Crypto {
|
||||
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],
|
||||
&[
|
||||
"--decrypt".to_owned(),
|
||||
"--identity".to_owned(),
|
||||
identity.to_owned(),
|
||||
],
|
||||
encrypted_payload.as_bytes(),
|
||||
)
|
||||
.map_err(|_| ())?;
|
||||
@@ -127,7 +139,7 @@ impl Crypto {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_age(arguments: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {
|
||||
fn run_age(arguments: &[String], input: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let mut child = Command::new("age")
|
||||
.args(arguments)
|
||||
.stdin(Stdio::piped())
|
||||
@@ -184,7 +196,7 @@ mod tests {
|
||||
assert!(recipient.status.success());
|
||||
|
||||
let crypto = Crypto {
|
||||
recipient: Some(
|
||||
local_recipient: Some(
|
||||
String::from_utf8(recipient.stdout)
|
||||
.unwrap()
|
||||
.trim()
|
||||
@@ -196,6 +208,7 @@ mod tests {
|
||||
.encrypt_optional(
|
||||
Some("Private appointment".to_owned()),
|
||||
Some("Private notes".to_owned()),
|
||||
&[crypto.local_recipient().to_owned()],
|
||||
)
|
||||
.unwrap();
|
||||
let decrypted = crypto
|
||||
@@ -215,4 +228,57 @@ mod tests {
|
||||
assert_eq!(decrypted.notes.as_deref(), Some("Private notes"));
|
||||
std::fs::remove_dir_all(test_dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_payload_decrypts_with_each_registered_identity() {
|
||||
let test_dir = env::temp_dir().join(format!(
|
||||
"routine-age-multi-test-{}",
|
||||
new_content_id().unwrap()
|
||||
));
|
||||
std::fs::create_dir(&test_dir).unwrap();
|
||||
let mut identities = Vec::new();
|
||||
let mut recipients = Vec::new();
|
||||
for index in 0..2 {
|
||||
let identity = test_dir.join(format!("identity-{index}.txt"));
|
||||
assert!(Command::new("age-keygen")
|
||||
.args(["-o", identity.to_str().unwrap()])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success());
|
||||
let recipient = Command::new("age-keygen")
|
||||
.args(["-y", identity.to_str().unwrap()])
|
||||
.output()
|
||||
.unwrap();
|
||||
recipients.push(
|
||||
String::from_utf8(recipient.stdout)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.to_owned(),
|
||||
);
|
||||
identities.push(identity);
|
||||
}
|
||||
let encryptor = Crypto {
|
||||
local_recipient: None,
|
||||
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),
|
||||
};
|
||||
let decrypted = decryptor
|
||||
.decrypt_fields(
|
||||
encrypted.encrypted_payload.as_deref(),
|
||||
encrypted.encryption_version,
|
||||
encrypted.content_id.as_deref(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(decrypted.private_title.as_deref(), Some("shared"));
|
||||
}
|
||||
std::fs::remove_dir_all(test_dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,27 @@ pub struct RescheduleTask {
|
||||
pub scheduled_date: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct EncryptionDevice {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
pub status: String,
|
||||
pub created_at: i64,
|
||||
pub revoked_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct EncryptionRecipient {
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreateEncryptionDevice {
|
||||
pub name: String,
|
||||
pub age_recipient: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct PrivatePayload {
|
||||
pub version: u8,
|
||||
|
||||
@@ -34,6 +34,11 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let devices_style = if app.view == View::Devices {
|
||||
active
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let date = if app.view == View::Tasks {
|
||||
format!(" {} ", app.date)
|
||||
} else {
|
||||
@@ -45,6 +50,8 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
Span::styled(" Routines ", routines_style),
|
||||
Span::raw(" "),
|
||||
Span::styled(" Archive ", archive_style),
|
||||
Span::raw(" "),
|
||||
Span::styled(" Devices ", devices_style),
|
||||
Span::raw(date),
|
||||
]))
|
||||
.block(Block::default().borders(Borders::ALL).title("Routine"));
|
||||
@@ -141,11 +148,34 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
ListItem::new(lines)
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
View::Devices => app
|
||||
.devices
|
||||
.iter()
|
||||
.map(|device| {
|
||||
let mark = if device.status == "active" {
|
||||
"●"
|
||||
} else {
|
||||
"○"
|
||||
};
|
||||
let revoked = device
|
||||
.revoked_at
|
||||
.map(|timestamp| format!(" revoked:{timestamp}"))
|
||||
.unwrap_or_default();
|
||||
ListItem::new(Line::from(format!(
|
||||
"{mark} {:<10} {} {} created:{}{revoked}",
|
||||
device.status,
|
||||
device.name,
|
||||
short_recipient(&device.age_recipient),
|
||||
device.created_at,
|
||||
)))
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
};
|
||||
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)",
|
||||
};
|
||||
let list = List::new(items)
|
||||
.block(Block::default().borders(Borders::ALL).title(title))
|
||||
@@ -157,10 +187,11 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
|
||||
let help = match app.view {
|
||||
View::Tasks => {
|
||||
"q quit Tab routines h/l day t today j/k move a add Space complete s move x delete r refresh"
|
||||
"q quit Tab routines h/l day t today j/k move a add Space complete s move x archive 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",
|
||||
View::Devices => "q quit Tab tasks j/k move a register device x revoke r refresh",
|
||||
};
|
||||
let footer = Paragraph::new(vec![
|
||||
Line::from(help),
|
||||
@@ -178,6 +209,7 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
FormKind::Task => format!("New task for {}", app.date),
|
||||
FormKind::Routine => "New routine".to_owned(),
|
||||
FormKind::Reschedule { .. } => "Reschedule task".to_owned(),
|
||||
FormKind::Device => "Register encryption device".to_owned(),
|
||||
};
|
||||
let lines = form
|
||||
.fields
|
||||
@@ -210,12 +242,15 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
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 (subject, verb, title) = match pending.kind {
|
||||
PendingActionKind::Archive => ("task", "Archive", "Confirm archive"),
|
||||
PendingActionKind::Delete => {
|
||||
("task", "Permanently delete", "Confirm permanent deletion")
|
||||
}
|
||||
PendingActionKind::RevokeDevice => ("device", "Revoke", "Confirm device revocation"),
|
||||
};
|
||||
let dialog = Paragraph::new(vec![
|
||||
Line::from(format!("{verb} task “{}”?", pending.title)),
|
||||
Line::from(format!("{verb} {subject} “{}”?", pending.title)),
|
||||
Line::from(""),
|
||||
Line::styled(
|
||||
"y: confirm • n/Esc: cancel",
|
||||
@@ -229,6 +264,23 @@ pub fn render(frame: &mut Frame, app: &App) {
|
||||
}
|
||||
}
|
||||
|
||||
fn short_recipient(recipient: &str) -> String {
|
||||
const EDGE: usize = 10;
|
||||
if recipient.chars().count() <= EDGE * 2 + 1 {
|
||||
return recipient.to_owned();
|
||||
}
|
||||
let start: String = recipient.chars().take(EDGE).collect();
|
||||
let end: String = recipient
|
||||
.chars()
|
||||
.rev()
|
||||
.take(EDGE)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev()
|
||||
.collect();
|
||||
format!("{start}…{end}")
|
||||
}
|
||||
|
||||
fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect {
|
||||
let vertical_margin = area.height.saturating_sub(height) / 2;
|
||||
let vertical = Layout::vertical([
|
||||
|
||||
Reference in New Issue
Block a user