1use rusqlite::{params, OptionalExtension};
11
12use super::error::StoreError;
13use super::store::Store;
14
15pub(super) const SCHEMA: &str = "
16 -- An entry whose value an agent had the Vault read (`import`, `capture`) and the person has not seen yet: a use of it
17 -- never goes ahead on silence until they have marked it seen or answered a use of it once. `entry_created_at` ties the
18 -- row to one incarnation of a reused id. One row per entry; a later change by an agent replaces it.
19 CREATE TABLE IF NOT EXISTS db_vault_unseen (
20 entry_id TEXT PRIMARY KEY,
21 entry_created_at INTEGER NOT NULL,
22 by_agent TEXT NOT NULL,
23 at INTEGER NOT NULL
24 );
25
26 -- The details an agent's edit replaced (label, plain fields, tags: never a value), kept 7 days so the person can put them
27 -- back. Written in the same transaction as the change.
28 CREATE TABLE IF NOT EXISTS db_vault_details_kept (
29 id INTEGER PRIMARY KEY AUTOINCREMENT,
30 entry_id TEXT NOT NULL,
31 entry_created_at INTEGER NOT NULL,
32 label TEXT NOT NULL,
33 fields TEXT NOT NULL,
34 tags TEXT NOT NULL,
35 changed_at INTEGER NOT NULL,
36 changed_by TEXT NOT NULL,
37 what TEXT NOT NULL
38 );
39 CREATE INDEX IF NOT EXISTS db_vault_details_kept_entry ON db_vault_details_kept (entry_id, entry_created_at);
40
41 -- A change of where a login is offered (site, realm, proxy) that an agent asked for on a login it did not make. It is
42 -- only a record until the person accepts it; one per entry and field, kept 7 days.
43 CREATE TABLE IF NOT EXISTS db_vault_proposals (
44 entry_id TEXT NOT NULL,
45 field TEXT NOT NULL,
46 entry_created_at INTEGER NOT NULL,
47 entry_updated_at INTEGER NOT NULL,
48 value TEXT NOT NULL,
49 agent TEXT NOT NULL,
50 reason TEXT NOT NULL,
51 at INTEGER NOT NULL,
52 PRIMARY KEY (entry_id, field)
53 );
54
55 -- Which changes by agents the person has marked seen, on this machine only (never synced): one by one, or every change up
56 -- to a line (`Seen all`).
57 CREATE TABLE IF NOT EXISTS db_vault_changes_seen (
58 seq INTEGER PRIMARY KEY
59 );
60 CREATE TABLE IF NOT EXISTS db_vault_changes_seen_all (
61 id INTEGER PRIMARY KEY CHECK (id = 1),
62 through_seq INTEGER NOT NULL
63 );
64";
65pub(super) const COLUMNS: [&str; 1] = ["ALTER TABLE db_vault_unseen ADD COLUMN what TEXT NOT NULL DEFAULT 'value'"];
67
68#[derive(Debug, Clone, PartialEq)]
70pub struct Unseen {
71 pub by_agent: String,
72 pub at: i64,
73 pub what: String,
75}
76
77pub const VALUE: &str = "value";
79pub const SITE: &str = "site";
80
81fn merged(old: &str, new: &str) -> String {
83 let (value, site) = (old.contains(VALUE) || new.contains(VALUE), old.contains(SITE) || new.contains(SITE));
84 match (value, site) {
85 (true, true) => format!("{VALUE} and {SITE}"),
86 (false, true) => SITE.to_string(),
87 _ => VALUE.to_string(),
88 }
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub struct DetailsKept {
94 pub entry_id: String,
95 pub entry_created_at: i64,
96 pub label: String,
97 pub fields: String,
98 pub tags: String,
99 pub changed_at: i64,
100 pub changed_by: String,
101 pub what: String,
103}
104
105#[derive(Debug, Clone, PartialEq)]
107pub struct Proposal {
108 pub entry_id: String,
109 pub field: String,
110 pub entry_created_at: i64,
111 pub entry_updated_at: i64,
112 pub value: String,
113 pub agent: String,
114 pub reason: String,
115 pub at: i64,
116}
117
118fn mark_in(tx: &rusqlite::Transaction<'_>, entry_id: &str, entry_created_at: i64, by_agent: &str, at: i64, what: &str) -> Result<(), StoreError> {
120 tx.execute("DELETE FROM db_vault_grants WHERE entry_id = ?1", params![entry_id])?;
121 let before: Option<String> = tx.query_row("SELECT what FROM db_vault_unseen WHERE entry_id = ?1 AND entry_created_at = ?2", params![entry_id, entry_created_at], |r| r.get(0)).optional()?;
122 let what = before.map_or_else(|| what.to_string(), |old| merged(&old, what));
123 tx.execute(
124 "INSERT OR REPLACE INTO db_vault_unseen (entry_id, entry_created_at, by_agent, at, what) VALUES (?1, ?2, ?3, ?4, ?5)",
125 params![entry_id, entry_created_at, by_agent, at, what],
126 )?;
127 Ok(())
128}
129
130impl Store {
131 pub fn vault_unseen_mark(&self, entry_id: &str, entry_created_at: i64, by_agent: &str, at: i64, what: &str) -> Result<(), StoreError> {
135 let mut conn = self.conn.lock().unwrap();
136 let tx = conn.transaction()?;
137 mark_in(&tx, entry_id, entry_created_at, by_agent, at, what)?;
138 tx.commit()?;
139 Ok(())
140 }
141
142 pub fn vault_unseen_get(&self, entry_id: &str) -> Result<Option<Unseen>, StoreError> {
144 let conn = self.conn.lock().unwrap();
145 Ok(conn
146 .query_row(
147 "SELECT u.by_agent, u.at, u.what FROM db_vault_unseen u JOIN db_vault_entries e ON e.id = u.entry_id AND e.created_at = u.entry_created_at WHERE u.entry_id = ?1",
148 params![entry_id],
149 |r| Ok(Unseen { by_agent: r.get(0)?, at: r.get(1)?, what: r.get(2)? }),
150 )
151 .optional()?)
152 }
153
154 pub fn vault_unseen_clear(&self, entry_id: &str) -> Result<bool, StoreError> {
156 let conn = self.conn.lock().unwrap();
157 Ok(conn.execute("DELETE FROM db_vault_unseen WHERE entry_id = ?1", params![entry_id])? > 0)
158 }
159
160 pub fn vault_update_details_kept(&self, row: &super::vault::VaultRow, was: &[u8], was_fields: &str, kept: &DetailsKept, unseen_site_by: Option<&str>) -> Result<bool, StoreError> {
166 let mut conn = self.conn.lock().unwrap();
167 let tx = conn.transaction()?;
168 let n = tx.execute(
169 "UPDATE db_vault_entries SET label = ?2, fields = ?3, tags = ?4, updated_at = ?5 WHERE id = ?1 AND created_at = ?6 AND sealed = ?7 AND fields = ?8 AND label = ?9 AND tags = ?10",
170 params![row.id, row.label, row.fields, row.tags, row.updated_at, row.created_at, was, was_fields, kept.label, kept.tags],
171 )?;
172 if n == 0 {
173 return Ok(false);
174 }
175 tx.execute(
176 "INSERT INTO db_vault_details_kept (entry_id, entry_created_at, label, fields, tags, changed_at, changed_by, what) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
177 params![kept.entry_id, kept.entry_created_at, kept.label, kept.fields, kept.tags, kept.changed_at, kept.changed_by, kept.what],
178 )?;
179 if let Some(agent) = unseen_site_by {
180 mark_in(&tx, &row.id, row.created_at, agent, row.updated_at, SITE)?;
181 }
182 tx.commit()?;
183 Ok(true)
184 }
185
186 pub fn vault_details_kept(&self, entry_id: &str, entry_created_at: i64) -> Result<Vec<DetailsKept>, StoreError> {
188 let conn = self.conn.lock().unwrap();
189 let mut stmt = conn.prepare(
190 "SELECT entry_id, entry_created_at, label, fields, tags, changed_at, changed_by, what FROM db_vault_details_kept WHERE entry_id = ?1 AND entry_created_at = ?2 ORDER BY id DESC",
191 )?;
192 let rows = stmt.query_map(params![entry_id, entry_created_at], |r| {
193 Ok(DetailsKept { entry_id: r.get(0)?, entry_created_at: r.get(1)?, label: r.get(2)?, fields: r.get(3)?, tags: r.get(4)?, changed_at: r.get(5)?, changed_by: r.get(6)?, what: r.get(7)? })
194 })?;
195 Ok(rows.collect::<Result<_, _>>()?)
196 }
197
198 pub fn vault_details_kept_delete(&self, kept: &DetailsKept) -> Result<(), StoreError> {
200 let conn = self.conn.lock().unwrap();
201 conn.execute(
202 "DELETE FROM db_vault_details_kept WHERE entry_id = ?1 AND entry_created_at = ?2 AND changed_at = ?3 AND changed_by = ?4 AND what = ?5",
203 params![kept.entry_id, kept.entry_created_at, kept.changed_at, kept.changed_by, kept.what],
204 )?;
205 Ok(())
206 }
207
208 pub fn vault_details_prune(&self, before_ms: i64) -> Result<usize, StoreError> {
210 let conn = self.conn.lock().unwrap();
211 Ok(conn.execute("DELETE FROM db_vault_details_kept WHERE changed_at < ?1", params![before_ms])?)
212 }
213
214 pub fn vault_proposal_put(&self, p: &Proposal) -> Result<(), StoreError> {
216 let conn = self.conn.lock().unwrap();
217 conn.execute(
218 "INSERT OR REPLACE INTO db_vault_proposals (entry_id, field, entry_created_at, entry_updated_at, value, agent, reason, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
219 params![p.entry_id, p.field, p.entry_created_at, p.entry_updated_at, p.value, p.agent, p.reason, p.at],
220 )?;
221 Ok(())
222 }
223
224 pub fn vault_proposals(&self, entry_id: Option<&str>, since_ms: i64) -> Result<Vec<Proposal>, StoreError> {
226 let conn = self.conn.lock().unwrap();
227 let mut stmt = conn.prepare(
228 "SELECT entry_id, field, entry_created_at, entry_updated_at, value, agent, reason, at FROM db_vault_proposals WHERE at >= ?1 AND (?2 IS NULL OR entry_id = ?2) ORDER BY at, entry_id, field",
229 )?;
230 let rows = stmt.query_map(params![since_ms, entry_id], |r| {
231 Ok(Proposal { entry_id: r.get(0)?, field: r.get(1)?, entry_created_at: r.get(2)?, entry_updated_at: r.get(3)?, value: r.get(4)?, agent: r.get(5)?, reason: r.get(6)?, at: r.get(7)? })
232 })?;
233 Ok(rows.collect::<Result<_, _>>()?)
234 }
235
236 pub fn vault_proposal_delete(&self, entry_id: &str, field: &str) -> Result<bool, StoreError> {
238 let conn = self.conn.lock().unwrap();
239 Ok(conn.execute("DELETE FROM db_vault_proposals WHERE entry_id = ?1 AND field = ?2", params![entry_id, field])? > 0)
240 }
241
242 pub fn vault_change_seen(&self, seq: i64) -> Result<(), StoreError> {
244 let conn = self.conn.lock().unwrap();
245 conn.execute("INSERT OR IGNORE INTO db_vault_changes_seen (seq) VALUES (?1)", params![seq])?;
246 Ok(())
247 }
248
249 pub fn vault_changes_seen_all(&self, through_seq: i64) -> Result<(), StoreError> {
251 let mut conn = self.conn.lock().unwrap();
252 let tx = conn.transaction()?;
253 tx.execute(
254 "INSERT INTO db_vault_changes_seen_all (id, through_seq) VALUES (1, ?1) ON CONFLICT(id) DO UPDATE SET through_seq = MAX(through_seq, excluded.through_seq)",
255 params![through_seq],
256 )?;
257 tx.execute("DELETE FROM db_vault_changes_seen WHERE seq <= ?1", params![through_seq])?;
258 tx.commit()?;
259 Ok(())
260 }
261
262 pub fn vault_changes_seen(&self) -> Result<(i64, std::collections::HashSet<i64>), StoreError> {
264 let conn = self.conn.lock().unwrap();
265 let through: i64 = conn.query_row("SELECT through_seq FROM db_vault_changes_seen_all WHERE id = 1", [], |r| r.get(0)).optional()?.unwrap_or(0);
266 let mut stmt = conn.prepare("SELECT seq FROM db_vault_changes_seen")?;
267 let seqs = stmt.query_map([], |r| r.get::<_, i64>(0))?.collect::<Result<_, _>>()?;
268 Ok((through, seqs))
269 }
270
271 pub fn vault_proposals_prune(&self, before_ms: i64) -> Result<usize, StoreError> {
273 let conn = self.conn.lock().unwrap();
274 Ok(conn.execute("DELETE FROM db_vault_proposals WHERE at < ?1", params![before_ms])?)
275 }
276}