-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdb.rs
More file actions
5314 lines (4789 loc) · 203 KB
/
db.rs
File metadata and controls
5314 lines (4789 loc) · 203 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::graphql::graphql_types::{
AIModelLoadingStatus, EntanglementProof, ImportResult, LinkStatus, ModelInput,
NotificationInput, PerspectiveExpression, PerspectiveHandle, PerspectiveState, SentMessage,
};
use crate::types::{
AIPromptExamples, AITask, Expression, ExpressionProof, Link, LinkExpression, LocalModel, Model,
ModelApi, ModelApiType, ModelType, Notification, PerspectiveDiff, TokenizerSource, User,
UserInfo,
};
use crate::utils::constant_time_eq;
use argon2::{
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2,
};
use deno_core::anyhow::anyhow;
use deno_core::error::AnyError;
use rand::Rng;
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
use url::Url;
use uuid::Uuid;
#[derive(Serialize, Deserialize)]
struct LinkSchema {
perspective: String,
link_expression: JsonValue,
source: String,
predicate: String,
target: String,
author: String,
timestamp: String,
status: String,
}
#[derive(Serialize, Deserialize)]
struct ExpressionSchema {
url: String,
data: JsonValue,
}
pub type Ad4mDbResult<T> = Result<T, AnyError>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentRequest {
pub id: i64,
pub user_email: String,
pub amount_hot: String,
pub proposal_action_hash: Option<String>,
pub status: String,
pub created_at: String,
pub completed_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComputeLogEntry {
pub id: i64,
pub user_email: String,
pub timestamp: String,
pub operation: String,
pub summary: Option<String>,
pub cost: f64,
pub credits_after: f64,
}
use std::sync::{Arc, Mutex};
lazy_static! {
static ref AD4M_DB_INSTANCE: Arc<Mutex<Option<Ad4mDb>>> = Arc::new(Mutex::new(None));
}
pub struct Ad4mDb {
conn: Connection,
}
impl Ad4mDb {
pub fn init_global_instance(db_path: &str) -> Ad4mDbResult<()> {
let mut db_instance = AD4M_DB_INSTANCE.lock().unwrap();
*db_instance = Some(Ad4mDb::new(db_path)?);
Ok(())
}
pub fn global_instance() -> Arc<Mutex<Option<Ad4mDb>>> {
AD4M_DB_INSTANCE.clone()
}
fn new(db_path: &str) -> Ad4mDbResult<Self> {
let conn = Connection::open(db_path)?;
// Create tables if they don't exist
conn.execute(
"CREATE TABLE IF NOT EXISTS perspective_handle (
uuid TEXT PRIMARY KEY,
name TEXT,
neighbourhood TEXT,
shared_url TEXT,
state TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS link (
id INTEGER PRIMARY KEY,
perspective TEXT NOT NULL,
source TEXT NOT NULL,
predicate TEXT NOT NULL,
target TEXT NOT NULL,
author TEXT NOT NULL,
timestamp TEXT NOT NULL,
signature TEXT NOT NULL,
key TEXT NOT NULL,
status TEXT NOT NULL
)",
[],
)?;
// Ensure we don't have duplicate link expressions and enforce uniqueness going forward
conn.execute(
"DELETE FROM link
WHERE id NOT IN (
SELECT MIN(id) FROM link
GROUP BY perspective, source, predicate, target, author, timestamp
)",
[],
)?;
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS link_unique_idx
ON link (perspective, source, predicate, target, author, timestamp)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS expression (
id INTEGER PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
data TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS perspective_diff (
id INTEGER PRIMARY KEY,
perspective TEXT NOT NULL,
additions TEXT NOT NULL,
removals TEXT NOT NULL,
is_pending BOOLEAN NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS trusted_agent (
id INTEGER PRIMARY KEY,
agent TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS known_link_languages (
id INTEGER PRIMARY KEY,
language TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS friends (
id INTEGER PRIMARY KEY,
friend TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS perspective_link_migration (
id INTEGER PRIMARY KEY,
perspective_uuid TEXT NOT NULL UNIQUE,
migrated_at TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY,
message TEXT NOT NULL,
recipient TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS entanglement_proof (
id INTEGER PRIMARY KEY,
proof TEXT NOT NULL
)",
[],
)?;
// Start Generation Here
conn.execute(
"CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
granted BOOLEAN NOT NULL,
description TEXT NOT NULL,
appName TEXT NOT NULL,
appUrl TEXT NOT NULL,
appIconPath TEXT,
trigger TEXT NOT NULL,
perspective_ids TEXT NOT NULL,
webhookUrl TEXT NOT NULL,
webhookAuth TEXT NOT NULL,
user_email TEXT
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
model_id TEXT NOT NULL,
system_prompt TEXT NOT NULL,
prompt_examples TEXT NOT NULL,
metadata TEXT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS models (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
api_base_url TEXT,
api_key TEXT,
model TEXT,
api_type TEXT,
local_file_name TEXT,
local_tokenizer_repo TEXT,
local_tokenizer_revision TEXT,
local_tokenizer_file_name TEXT,
local_huggingface_repo TEXT,
local_revision TEXT,
type TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS model_status (
model TEXT PRIMARY KEY,
progress DOUBLE NOT NULL,
status TEXT NOT NULL,
downloaded BOOLEAN NOT NULL,
loaded BOOLEAN NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS default_models (
model_type TEXT PRIMARY KEY,
model_id TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
did TEXT NOT NULL,
password_hash TEXT NOT NULL,
last_seen INTEGER
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS email_verifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
code_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
verified BOOLEAN DEFAULT 0,
verification_type TEXT NOT NULL,
UNIQUE(email, verification_type)
)",
[],
)?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_email_verifications_email ON email_verifications(email)",
[],
)?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_email_verifications_expires ON email_verifications(expires_at)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS email_rate_limits (
email TEXT PRIMARY KEY,
last_sent_at INTEGER NOT NULL
)",
[],
)?;
// Add failed_attempts column to email_verifications table if it doesn't exist
// This column tracks failed verification attempts to prevent brute force attacks
let _ = conn.execute(
"ALTER TABLE email_verifications ADD COLUMN failed_attempts INTEGER DEFAULT 0",
[],
);
// Add owner_did column to existing perspective_handle table if it doesn't exist
let _ = conn.execute(
"ALTER TABLE perspective_handle ADD COLUMN owner_did TEXT",
[],
);
// Add owners column for multi-user neighbourhood support
let _ = conn.execute(
"ALTER TABLE perspective_handle ADD COLUMN owners TEXT DEFAULT '[]'",
[],
);
// Migrate existing owner_did values to owners array
let _ = conn.execute(
"UPDATE perspective_handle SET owners = json_array(owner_did) WHERE owner_did IS NOT NULL AND owners = '[]'",
[],
);
// Helper to run ALTER TABLE ADD COLUMN migrations, ignoring "duplicate column name"
// errors (column already exists from a previous migration) but propagating all others.
let alter_add_column = |sql: &str| -> Result<(), AnyError> {
match conn.execute(sql, []) {
Ok(_) => Ok(()),
Err(e) if e.to_string().contains("duplicate column name") => Ok(()),
Err(e) => Err(e.into()),
}
};
// Add user_email column to notifications table for multi-user support
// This column tracks which user created the notification (NULL for main agent)
alter_add_column("ALTER TABLE notifications ADD COLUMN user_email TEXT")?;
// Add hosting columns to users table
alter_add_column("ALTER TABLE users ADD COLUMN remaining_credits REAL DEFAULT 0")?;
alter_add_column("ALTER TABLE users ADD COLUMN hot_wallet_address TEXT")?;
// Clear duplicate hot_wallet_address bindings (keep account row intact)
conn.execute_batch(
"UPDATE users SET hot_wallet_address = NULL WHERE rowid NOT IN (SELECT MIN(rowid) FROM users WHERE hot_wallet_address IS NOT NULL GROUP BY hot_wallet_address) AND hot_wallet_address IS NOT NULL",
)?;
conn.execute_batch(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_users_hot_wallet_address ON users(hot_wallet_address) WHERE hot_wallet_address IS NOT NULL",
)?;
alter_add_column("ALTER TABLE users ADD COLUMN free_access BOOLEAN DEFAULT 0")?;
// Host rates table — stores per-item pricing used for credit deduction
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS host_rates (
description TEXT PRIMARY KEY,
price_in_hot REAL NOT NULL
)",
)?;
// Payment requests table for tracking mHOT payment proposals
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS payment_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
amount_hot TEXT NOT NULL,
proposal_action_hash TEXT UNIQUE,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT
)",
)?;
// Dedup before creating unique index to handle legacy duplicate rows
conn.execute_batch(
"DELETE FROM payment_requests WHERE id NOT IN (SELECT MIN(id) FROM payment_requests WHERE proposal_action_hash IS NOT NULL GROUP BY proposal_action_hash) AND proposal_action_hash IS NOT NULL",
)?;
// Add unique index for existing databases that already created the table without UNIQUE
conn.execute_batch(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_payment_requests_proposal_hash ON payment_requests(proposal_action_hash) WHERE proposal_action_hash IS NOT NULL",
)?;
// Pending outgoing sends (proposals we created to send funds)
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS pending_sends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recipient TEXT NOT NULL,
amount_hot TEXT NOT NULL,
proposal_action_hash TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
completed_at TEXT
)",
)?;
// Dedup before creating unique index to handle legacy duplicate rows
conn.execute_batch(
"DELETE FROM pending_sends WHERE id NOT IN (SELECT MIN(id) FROM pending_sends WHERE proposal_action_hash IS NOT NULL GROUP BY proposal_action_hash) AND proposal_action_hash IS NOT NULL",
)?;
// Add unique index for existing databases that already created the table without UNIQUE
conn.execute_batch(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_sends_proposal_hash ON pending_sends(proposal_action_hash)",
)?;
// Compute activity log — one row per billing event
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS compute_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
timestamp TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
operation TEXT NOT NULL,
summary TEXT,
cost REAL NOT NULL,
credits_after REAL NOT NULL
)",
)?;
conn.execute_batch(
"CREATE INDEX IF NOT EXISTS idx_compute_log_user_time ON compute_log(user_email, timestamp)",
)?;
Ok(Self { conn })
}
pub fn create_or_update_model_status(
&self,
model: &str,
progress: f64,
status: &str,
downloaded: bool,
loaded: bool,
) -> Result<(), rusqlite::Error> {
let conn = &self.conn;
conn.execute(
"INSERT INTO model_status (model, progress, status, downloaded, loaded)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(model) DO UPDATE SET
progress = excluded.progress,
status = excluded.status,
downloaded = excluded.downloaded,
loaded = excluded.loaded",
params![model, progress, status, downloaded, loaded],
)?;
Ok(())
}
pub fn get_model_status(
&self,
model: &str,
) -> Result<Option<AIModelLoadingStatus>, rusqlite::Error> {
let conn = &self.conn;
let mut stmt = conn.prepare(
"SELECT model, progress, status, downloaded, loaded FROM model_status WHERE model = ?1",
)?;
let mut rows = stmt.query(params![model])?;
if let Some(row) = rows.next()? {
let model = AIModelLoadingStatus {
model: row.get(0)?,
progress: row.get(1)?,
status: row.get(2)?,
downloaded: row.get(3)?,
loaded: row.get(4)?,
};
Ok(Some(model))
} else {
Ok(None)
}
}
pub fn add_task(
&self,
name: String,
model_id: String,
system_prompt: String,
prompt_examples: Vec<AIPromptExamples>,
metadata: Option<String>,
) -> Result<String, rusqlite::Error> {
let created_at = chrono::Utc::now().to_string();
let updated_at = created_at.clone();
let id = uuid::Uuid::new_v4().to_string();
self.conn.execute(
"INSERT INTO tasks (id, name, model_id, system_prompt, prompt_examples, metadata, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![id, name, model_id, system_prompt, serde_json::to_string(&prompt_examples).unwrap(), metadata, created_at, updated_at],
)?;
Ok(id)
}
pub fn remove_task(&self, id: String) -> Result<(), rusqlite::Error> {
self.conn.execute("DELETE FROM tasks WHERE id = ?", [id])?;
Ok(())
}
pub fn get_task(&self, id: String) -> Result<Option<AITask>, rusqlite::Error> {
let mut stmt = self.conn.prepare("SELECT * FROM tasks WHERE id = ?")?;
let mut rows = stmt.query(params![id])?;
if let Some(row) = rows.next()? {
let prompt_examples: Vec<AIPromptExamples> =
serde_json::from_str(&row.get::<_, String>(4)?).unwrap();
Ok(Some(AITask {
task_id: row.get(0)?,
name: row.get(1)?,
model_id: row.get(2)?,
system_prompt: row.get(3)?,
prompt_examples,
meta_data: row.get(5)?,
created_at: row.get(6)?,
updated_at: row.get(7)?,
}))
} else {
Ok(None)
}
}
pub fn get_tasks(&self) -> Result<Vec<AITask>, rusqlite::Error> {
let mut stmt = self.conn.prepare("SELECT * FROM tasks")?;
let task_iter = stmt.query_map([], |row| {
let prompt_examples: Vec<AIPromptExamples> =
serde_json::from_str(&row.get::<_, String>(4)?).unwrap();
let task = AITask {
task_id: row.get(0)?,
name: row.get(1)?,
model_id: row.get(2)?,
system_prompt: row.get(3)?,
prompt_examples,
meta_data: row.get(5)?,
created_at: row.get(6)?,
updated_at: row.get(7)?,
};
Ok(task)
})?;
let mut tasks = Vec::new();
for task in task_iter {
tasks.push(task?);
}
Ok(tasks)
}
pub fn update_task(
&self,
id: String,
name: String,
model_id: String,
system_prompt: String,
prompt_examples: Vec<AIPromptExamples>,
metadata: Option<String>,
) -> Result<bool, rusqlite::Error> {
let updated_at = chrono::Utc::now().to_string();
let result = self.conn.execute(
"UPDATE tasks SET name = ?2, model_id = ?3, system_prompt = ?4, prompt_examples = ?5, metadata = ?6, updated_at = ?7 WHERE id = ?1",
params![id, name, model_id, system_prompt, serde_json::to_string(&prompt_examples).unwrap(), metadata, updated_at],
)?;
Ok(result > 0)
}
/// Validates that a notification query is safe and well-formed
fn validate_notification_query(query: &str) -> Result<(), String> {
let query_trimmed = query.trim();
let query_upper = query_trimmed.to_uppercase();
// Check for empty query
if query_trimmed.is_empty() {
return Err("Query cannot be empty".to_string());
}
// Check query length (prevent extremely long queries)
if query_trimmed.len() > 10000 {
return Err("Query is too long (max 10000 characters)".to_string());
}
// Validate that query starts with SELECT, RETURN, LET, or WITH
let first_word = query_upper.split_whitespace().next().unwrap_or("");
if !matches!(first_word, "SELECT" | "RETURN" | "LET" | "WITH") {
return Err(format!(
"Query must start with SELECT, RETURN, LET, or WITH. Got: {}",
first_word
));
}
// Check for mutating operations
// Use a single pass that tracks string literals to avoid false positives
let mutating_operations = [
"INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "REMOVE", "DEFINE", "ALTER", "RELATE",
"BEGIN", "COMMIT", "CANCEL",
];
let query_bytes = query_upper.as_bytes();
for operation in &mutating_operations {
let op_bytes = operation.as_bytes();
let mut search_pos = 0;
while let Some(pos) = query_upper[search_pos..].find(operation) {
let absolute_pos = search_pos + pos;
// Re-track string state up to this position
let mut in_string = false;
let mut escaped = false;
let mut string_char: u8 = 0;
for i in 0..absolute_pos {
let byte = query_bytes[i];
match byte {
b'\\' if in_string => {
escaped = !escaped;
}
b'\'' | b'"' => {
if !escaped {
if in_string {
if byte == string_char {
in_string = false;
}
} else {
in_string = true;
string_char = byte;
}
}
if escaped {
escaped = false;
}
}
_ => {
if escaped {
escaped = false;
}
}
}
}
// Skip if inside a string literal
if in_string {
search_pos = absolute_pos + 1;
continue;
}
// Check what comes before (byte-based)
let before_ok = if absolute_pos == 0 {
true
} else {
let before_byte = query_bytes[absolute_pos - 1];
matches!(before_byte, b' ' | b'\t' | b'\n' | b'\r' | b';' | b'(')
};
// Check what comes after (byte-based)
let after_pos = absolute_pos + op_bytes.len();
let after_ok = if after_pos >= query_bytes.len() {
true
} else {
let after_byte = query_bytes[after_pos];
matches!(after_byte, b' ' | b'\t' | b'\n' | b'\r' | b';' | b'(')
};
if before_ok && after_ok {
return Err(format!(
"Query contains mutating operation '{}' which is not allowed",
operation
));
}
search_pos = absolute_pos + 1;
}
}
// Basic syntax check - ensure balanced parentheses
// Skip counting parentheses inside string literals
let mut paren_count = 0;
let mut in_string = false;
let mut string_char = ' '; // Track which quote character started the string
let mut escaped = false;
for c in query_trimmed.chars() {
match c {
'\\' if in_string => {
// Toggle escaped state for backslashes inside strings
// If already escaped, this is a literal backslash (\\)
// If not escaped, next char will be escaped
escaped = !escaped;
}
'\'' | '"' => {
if !escaped {
if in_string {
// Check if this closes the current string
if c == string_char {
in_string = false;
}
} else {
// Start a new string
in_string = true;
string_char = c;
}
}
// Clear escaped state after processing
if escaped {
escaped = false;
}
}
'(' if !in_string => paren_count += 1,
')' if !in_string => paren_count -= 1,
_ => {
// Any other character clears the escaped state
if escaped {
escaped = false;
}
}
}
if paren_count < 0 {
return Err("Unbalanced parentheses in query".to_string());
}
}
if paren_count != 0 {
return Err("Unbalanced parentheses in query".to_string());
}
Ok(())
}
pub fn add_notification(
&self,
notification: NotificationInput,
user_email: Option<String>,
) -> Result<String, rusqlite::Error> {
// Validate the trigger query before storing
if let Err(e) = Self::validate_notification_query(¬ification.trigger) {
return Err(rusqlite::Error::InvalidParameterName(format!(
"Invalid notification query: {}",
e
)));
}
let id = uuid::Uuid::new_v4().to_string();
self.conn.execute(
"INSERT INTO notifications (id, granted, description, appName, appUrl, appIconPath, trigger, perspective_ids, webhookUrl, webhookAuth, user_email) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
id,
false,
notification.description,
notification.app_name,
notification.app_url,
notification.app_icon_path,
notification.trigger,
serde_json::to_string(¬ification.perspective_ids).unwrap(),
notification.webhook_url,
notification.webhook_auth,
user_email,
],
)?;
Ok(id)
}
pub fn get_notifications(&self) -> Result<Vec<Notification>, rusqlite::Error> {
let mut stmt = self.conn.prepare("SELECT * FROM notifications")?;
let notification_iter = stmt.query_map([], |row| {
Ok(Notification {
id: row.get(0)?,
granted: row.get(1)?,
description: row.get(2)?,
app_name: row.get(3)?,
app_url: row.get(4)?,
app_icon_path: row.get(5)?,
trigger: row.get(6)?,
perspective_ids: serde_json::from_str(&row.get::<_, String>(7)?).unwrap(),
webhook_url: row.get(8)?,
webhook_auth: row.get(9)?,
user_email: row.get(10)?,
})
})?;
let mut notifications = Vec::new();
for notification in notification_iter {
notifications.push(notification?);
}
Ok(notifications)
}
pub fn get_notifications_for_user(
&self,
user_email: Option<String>,
) -> Result<Vec<Notification>, rusqlite::Error> {
let notifications = if let Some(email) = user_email {
// Query for specific user's notifications
let mut stmt = self
.conn
.prepare("SELECT * FROM notifications WHERE user_email = ?1")?;
let notification_iter = stmt.query_map(params![email], |row| {
Ok(Notification {
id: row.get(0)?,
granted: row.get(1)?,
description: row.get(2)?,
app_name: row.get(3)?,
app_url: row.get(4)?,
app_icon_path: row.get(5)?,
trigger: row.get(6)?,
perspective_ids: serde_json::from_str(&row.get::<_, String>(7)?).unwrap(),
webhook_url: row.get(8)?,
webhook_auth: row.get(9)?,
user_email: row.get(10)?,
})
})?;
let mut result = Vec::new();
for notification in notification_iter {
result.push(notification?);
}
result
} else {
// Query for main agent's notifications (user_email IS NULL)
let mut stmt = self
.conn
.prepare("SELECT * FROM notifications WHERE user_email IS NULL")?;
let notification_iter = stmt.query_map([], |row| {
Ok(Notification {
id: row.get(0)?,
granted: row.get(1)?,
description: row.get(2)?,
app_name: row.get(3)?,
app_url: row.get(4)?,
app_icon_path: row.get(5)?,
trigger: row.get(6)?,
perspective_ids: serde_json::from_str(&row.get::<_, String>(7)?).unwrap(),
webhook_url: row.get(8)?,
webhook_auth: row.get(9)?,
user_email: row.get(10)?,
})
})?;
let mut result = Vec::new();
for notification in notification_iter {
result.push(notification?);
}
result
};
Ok(notifications)
}
pub fn get_notification(&self, id: String) -> Result<Option<Notification>, rusqlite::Error> {
let mut stmt = self
.conn
.prepare("SELECT * FROM notifications WHERE id = ?")?;
let mut rows = stmt.query(params![id])?;
if let Some(row) = rows.next()? {
Ok(Some(Notification {
id: row.get(0)?,
granted: row.get(1)?,
description: row.get(2)?,
app_name: row.get(3)?,
app_url: row.get(4)?,
app_icon_path: row.get(5)?,
trigger: row.get(6)?,
perspective_ids: serde_json::from_str(&row.get::<_, String>(7)?).unwrap(),
webhook_url: row.get(8)?,
webhook_auth: row.get(9)?,
user_email: row.get(10)?,
}))
} else {
Ok(None)
}
}
pub fn remove_notification(&self, id: String) -> Result<(), rusqlite::Error> {
self.conn
.execute("DELETE FROM notifications WHERE id = ?", [id])?;
Ok(())
}
pub fn update_notification(
&self,
id: String,
updated_notification: &Notification,
) -> Result<bool, rusqlite::Error> {
// Validate the trigger query before updating
if let Err(e) = Self::validate_notification_query(&updated_notification.trigger) {
return Err(rusqlite::Error::InvalidParameterName(format!(
"Invalid notification query: {}",
e
)));
}
let result = self.conn.execute(
"UPDATE notifications SET description = ?2, appName = ?3, appUrl = ?4, appIconPath = ?5, trigger = ?6, perspective_ids = ?7, webhookUrl = ?8, webhookAuth = ?9, granted = ?10, user_email = ?11 WHERE id = ?1",
params![
id,
updated_notification.description,
updated_notification.app_name,
updated_notification.app_url,
updated_notification.app_icon_path,
updated_notification.trigger,
serde_json::to_string(&updated_notification.perspective_ids).unwrap(),
updated_notification.webhook_url,
updated_notification.webhook_auth,
updated_notification.granted,
updated_notification.user_email,
],
)?;
Ok(result > 0)
}
pub fn add_entanglement_proofs(
&self,
proofs: Vec<EntanglementProof>,
) -> Result<(), rusqlite::Error> {
for proof in proofs {
let proof = serde_json::to_string(&proof).unwrap();
self.conn
.execute("INSERT INTO entanglement_proof (proof) VALUES (?)", [proof])?;
}
Ok(())
}
pub fn get_all_entanglement_proofs(&self) -> Result<Vec<EntanglementProof>, rusqlite::Error> {
let mut stmt = self.conn.prepare("SELECT proof FROM entanglement_proof")?;
let proof_iter = stmt.query_map([], |row| {
let proof_json: String = row.get(0)?;
let proof: EntanglementProof = serde_json::from_str(&proof_json).unwrap();
Ok(proof)
})?;
let mut proofs = Vec::new();
for proof in proof_iter {
proofs.push(proof?);
}
Ok(proofs)
}
pub fn remove_entanglement_proofs(
&self,
proofs: Vec<EntanglementProof>,
) -> Result<(), rusqlite::Error> {
for proof in proofs {
let proof_json = serde_json::to_string(&proof).unwrap();
self.conn.execute(
"DELETE FROM entanglement_proof WHERE proof = ?",
[proof_json],
)?;
}
Ok(())
}
pub fn add_to_outbox(
&self,
message: &PerspectiveExpression,
recipient: String,
) -> Result<(), rusqlite::Error> {
let message_json = serde_json::to_string(message).unwrap();
self.conn.execute(
"INSERT INTO outbox (message, recipient) VALUES (?, ?)",
[message_json, recipient],
)?;
Ok(())
}
pub fn get_all_from_outbox(&self) -> Result<Vec<SentMessage>, rusqlite::Error> {
let mut stmt = self.conn.prepare("SELECT message, recipient FROM outbox")?;
let outbox_iter = stmt.query_map([], |row| {
let message_json: String = row.get(0)?;
let message: PerspectiveExpression = serde_json::from_str(&message_json).unwrap();
let recipient: String = row.get(1)?;
Ok(SentMessage { message, recipient })
})?;
let mut outbox = Vec::new();
for message in outbox_iter {
outbox.push(message?);
}
Ok(outbox)
}
pub fn add_friends(&self, friends: Vec<String>) -> Result<(), rusqlite::Error> {
for friend in friends {
self.conn
.execute("INSERT INTO friends (friend) VALUES (?)", [friend])?;
}