second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
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
use std::sync::LazyLock;

use regex::{Captures, Regex};

use crate::schema::Memory;

mod assign;
mod keys;

use assign::redact_assignments;
use keys::redact_private_keys;

#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SecretKind {
    PrivateKey,
    AwsAccessKeyId,
    AwsSecretKey,
    GithubToken,
    ApiKey,
    SlackToken,
    SlackWebhook,
    GoogleApiKey,
    Jwt,
    BearerToken,
    BasicAuth,
    UrlCredentials,
    Secret,
}

impl SecretKind {
    /// The `<kind>` written into `[REDACTED:<kind>]`.
    pub fn as_str(self) -> &'static str {
        match self {
            SecretKind::PrivateKey => "private_key",
            SecretKind::AwsAccessKeyId => "aws_access_key_id",
            SecretKind::AwsSecretKey => "aws_secret_key",
            SecretKind::GithubToken => "github_token",
            SecretKind::ApiKey => "api_key",
            SecretKind::SlackToken => "slack_token",
            SecretKind::SlackWebhook => "slack_webhook",
            SecretKind::GoogleApiKey => "google_api_key",
            SecretKind::Jwt => "jwt",
            SecretKind::BearerToken => "bearer_token",
            SecretKind::BasicAuth => "basic_auth",
            SecretKind::UrlCredentials => "url_credentials",
            SecretKind::Secret => "secret",
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    pub kind: SecretKind,
    pub count: usize,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redacted {
    pub text: String,
    /// One entry per kind found, in the order the kinds were first replaced.
    pub findings: Vec<Finding>,
}

impl Redacted {
    pub fn changed(&self) -> bool {
        !self.findings.is_empty()
    }
}

/// Replaces every secret in `text` with `[REDACTED:<kind>]`. Pure and
/// idempotent: redacting already-redacted text returns it unchanged.
pub fn redact(text: &str) -> Redacted {
    let mut findings = Vec::new();
    let mut current = redact_private_keys(text, &mut findings);
    for rule in RULES.iter() {
        if let Some(next) = rule.apply(current.as_deref().unwrap_or(text), &mut findings) {
            current = Some(next);
        }
    }
    if let Some(next) = redact_assignments(current.as_deref().unwrap_or(text), &mut findings) {
        current = Some(next);
    }
    Redacted {
        text: current.unwrap_or_else(|| text.to_string()),
        findings,
    }
}

/// The text every entry path embeds and stores: `redact`, logging the kinds
/// found (never the values).
pub fn redact_for_store(text: &str) -> String {
    let redacted = redact(text);
    if redacted.changed() {
        let kinds = redacted
            .findings
            .iter()
            .map(|f| format!("{}={}", f.kind.as_str(), f.count))
            .collect::<Vec<_>>()
            .join(",");
        tracing::info!(%kinds, "redacted secrets before storing");
    }
    redacted.text
}

fn record(findings: &mut Vec<Finding>, kind: SecretKind, count: usize) {
    match findings.iter_mut().find(|f| f.kind == kind) {
        Some(f) => f.count += count,
        None => findings.push(Finding { kind, count }),
    }
}

fn marker(kind: SecretKind) -> String {
    format!("[REDACTED:{}]", kind.as_str())
}

/// Decides from the captures and the final value whether a match is a secret.
type Accept = fn(&Captures, &str) -> bool;

struct Rule {
    kind: SecretKind,
    re: Regex,
    accept: Accept,
}

impl Rule {
    fn new(kind: SecretKind, pattern: &str, accept: Accept) -> Self {
        Self {
            kind,
            re: Regex::new(pattern).expect("redaction pattern compiles"),
            accept,
        }
    }

    /// Replaces the `secret` group when the pattern has one, else the whole
    /// match. A value glued to a marker is what an earlier redaction left, so
    /// it is kept and a second pass changes nothing. `None` when nothing was
    /// replaced.
    ///
    /// A rejected match resumes at its `secret` group, which may hold the
    /// next match, but only when that group is at most `MAX_VALUE` bytes, so
    /// each byte is rescanned a bounded number of times.
    fn apply(&self, text: &str, findings: &mut Vec<Finding>) -> Option<String> {
        let mut out = String::new();
        let mut last = 0;
        let mut count = 0;
        let mut pos = 0;
        while let Some(caps) = self.re.captures_at(text, pos) {
            let whole = caps.get(0).expect("group 0 always matches");
            let span = caps.name("secret").unwrap_or(whole);
            let (start, end) = (span.start(), span.end());
            let accepted = start >= last
                && !text[end..].starts_with("[REDACTED:")
                && (self.accept)(&caps, span.as_str());
            if !accepted {
                pos = if start > whole.start() && span.len() <= MAX_VALUE {
                    start
                } else {
                    whole.end()
                };
                continue;
            }
            out.push_str(&text[last..start]);
            out.push_str(&marker(self.kind));
            last = end;
            pos = end.max(whole.end());
            count += 1;
        }
        if count == 0 {
            return None;
        }
        out.push_str(&text[last..]);
        record(findings, self.kind, count);
        Some(out)
    }
}

/// The longest value rescanned after a rejected match, extended over `&` or
/// scanned after a secret-like name, which keeps every pass linear.
const MAX_VALUE: usize = 512;

fn always(_: &Captures, _: &str) -> bool {
    true
}

fn group<'t>(caps: &Captures<'t>, name: &str) -> &'t str {
    caps.name(name).map_or("", |m| m.as_str())
}

/// A run of at least `min` `member` bytes mixing upper and lower case and
/// digits.
fn has_random_run(s: &[u8], min: usize, member: fn(u8) -> bool) -> bool {
    let (mut run, mut upper, mut lower, mut digit) = (0, false, false, false);
    for &b in s {
        if member(b) {
            run += 1;
            upper |= b.is_ascii_uppercase();
            lower |= b.is_ascii_lowercase();
            digit |= b.is_ascii_digit();
        } else {
            (run, upper, lower, digit) = (0, false, false, false);
        }
        if run >= min && upper && lower && digit {
            return true;
        }
    }
    false
}

/// Capitalised words, each ending in its digits (`Uint8Array`,
/// `Ed25519PrivateKey`, `GPT2Tokenizer`). Random strings almost never have
/// every capital followed by a lowercase letter.
static TYPE_NAME: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:[A-Z]{2,}[0-9]*)?(?:[A-Z][a-z]+[0-9]*)+$").expect("pattern compiles")
});

fn has_digit(s: &str) -> bool {
    s.bytes().any(|b| b.is_ascii_digit())
}

fn mixed_case_with_digit(s: &str) -> bool {
    s.bytes().any(|b| b.is_ascii_uppercase())
        && s.bytes().any(|b| b.is_ascii_lowercase())
        && has_digit(s)
}

fn is_placeholder(s: &str) -> bool {
    s.starts_with(['$', '{', '<', '*', '%'])
}

fn sk_key_body(caps: &Captures, _: &str) -> bool {
    let body = group(caps, "body");
    let lowercase_run = body
        .split(|c: char| !(c.is_ascii_lowercase() || c.is_ascii_digit()))
        .any(|run| {
            run.len() >= 32 && has_digit(run) && run.bytes().any(|b| b.is_ascii_lowercase())
        });
    mixed_case_with_digit(body) || lowercase_run || has_uuid(body)
}

/// A password up to the last `@` before the path, or else one holding `/`
/// up to the first `@`. A `host:443/@scope` port, a password equal to the
/// user and a stand-in such as `password` or `****` are not secrets.
fn url_credentials(caps: &Captures, _: &str) -> bool {
    let user = group(caps, "user");
    let pass = caps
        .name("pass")
        .or_else(|| caps.name("slashed"))
        .map_or("", |m| m.as_str());
    let port = caps.name("slashed").is_some_and(|m| {
        let digits = m.as_str().bytes().take_while(u8::is_ascii_digit).count();
        digits > 0 && m.as_str()[digits..].starts_with('/')
    });
    let stand_in = pass == user
        || ["password", "pass", "secret", "changeme"]
            .iter()
            .any(|word| pass.eq_ignore_ascii_case(word))
        || pass.bytes().all(|b| matches!(b, b'*' | b'x' | b'X'));
    let scp_path = caps.name("slashed").is_some() && user.contains('@');
    caps.name("digest").is_none()
        && !scp_path
        && !is_placeholder(user)
        && !is_placeholder(pass)
        && !port
        && !stand_in
}

/// Langfuse keys are `sk-lf-` and a UUID.
fn has_uuid(s: &str) -> bool {
    UUID.is_match(s)
}

static UUID: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
        .expect("pattern compiles")
});

/// `mysql` as the command: after a line start, a separator, a prompt, a JSON
/// string or an escaped newline, after a word that is not a flag (`sudo`,
/// `VAR=value`, `exec db`, `ssh host`, `--`), or after `sudo` and its own
/// options (`sudo -u admin -E`, where `arg_flags` take a value), so
/// `--name mysql` and `/var/lib/mysql` are not. A quoted command may end
/// its array element (`["CMD", "mysql", ...]`).
fn mysql_command() -> String {
    let arg_flags = "ugpChUrtDRT";
    format!(
        r#"(?m)(?:(?:^|[ \t])(?:[^\s\-]\S*|--)[ \t]+|\b(?:sudo|doas)(?:[ \t]+(?:-[{arg_flags}][ \t]+[^\s\-]\S*|-[{arg_flags}]\S+|-[^\s\-{arg_flags}]\S*|--\S+))*[ \t]+|(?:^|[;&|(`"']|\$|\\n)[ \t]*)(?:\S*bin/)?(?:mysql(?:dump|admin|import|check|show)?|mariadb)(?:[ \t]|["'][ \t]*,[ \t]*)"#
    )
}

/// The start of the text, a non-word byte, or an escape in JSON-escaped text
/// (`\nsk-...`). Never `]`: a token glued to the one before it gains a word
/// boundary once that one becomes a marker, and redacting again must not find
/// it.
const TOKEN_START: &str = r"(?:^|[^A-Za-z0-9_\]]|\\[nrt])";

static RULES: LazyLock<Vec<Rule>> = LazyLock::new(|| {
    let token = |pattern: &str| format!("{TOKEN_START}(?P<secret>{pattern})");
    vec![
        Rule::new(
            SecretKind::Jwt,
            &token(r"eyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]*"),
            always,
        ),
        Rule::new(
            SecretKind::GithubToken,
            &token(r"gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}"),
            always,
        ),
        Rule::new(
            SecretKind::ApiKey,
            &token(r"sk-(?P<body>[A-Za-z0-9_\-]{20,})"),
            sk_key_body,
        ),
        Rule::new(
            SecretKind::ApiKey,
            &token(r"[rs]k_(?:live|test)_[A-Za-z0-9]{20,}"),
            always,
        ),
        Rule::new(
            SecretKind::ApiKey,
            &token(r"glpat-[A-Za-z0-9_\-]{20,}|npm_[A-Za-z0-9]{36,}|hf_[A-Za-z0-9]{34,}"),
            always,
        ),
        Rule::new(
            SecretKind::SlackToken,
            &token(
                r"xoxd-[A-Za-z0-9%+/=\-]{10,}|(?:xoxe\.)?(?:xox[abposrce]|xapp)-[A-Za-z0-9\-]{10,}",
            ),
            |_, value| {
                let digit_run = value
                    .split(|c: char| !c.is_ascii_digit())
                    .any(|run| run.len() >= 8);
                digit_run || has_random_run(value.as_bytes(), 16, |b| b.is_ascii_alphanumeric())
            },
        ),
        Rule::new(
            SecretKind::Secret,
            &token(r"tskey-[a-z]+-[A-Za-z0-9_\-]{16,}"),
            |_, value| has_digit(value),
        ),
        Rule::new(
            SecretKind::SlackWebhook,
            r"https://hooks\.slack\.com/services/[A-Za-z0-9/_\-]{20,}",
            always,
        ),
        Rule::new(
            SecretKind::GoogleApiKey,
            &token(r"AIza[0-9A-Za-z_\-]{35}"),
            always,
        ),
        Rule::new(
            SecretKind::AwsAccessKeyId,
            &token(
                r"(?:AKIA|ASIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|APKA|AROA|ASCA)[A-Z0-9]{16}\b",
            ),
            always,
        ),
        Rule::new(
            SecretKind::AwsSecretKey,
            r"\[REDACTED:aws_access_key_id\][ \t:,]+(?P<secret>[A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)",
            always,
        ),
        Rule::new(
            SecretKind::AwsSecretKey,
            r#"(?i)(?:aws[_ ]?)?secret[_ ]?(?:access[_ ]?)?key(?:\\?["'])?(?:[ \t]*\[[^\]\n]*\])?(?:[ \t]*(?:=|:=|:|=>)[ \t]*|[ \t]+)(?:\\?["'])?(?P<secret>[A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)"#,
            always,
        ),
        Rule::new(
            SecretKind::BearerToken,
            r#"(?i)\b(?:bearer|authorization(?:\\?["'])?\s*:\s*(?:\\?["'])?token)\s+(?P<secret>[A-Za-z0-9\-._~+/]{16,}=*)"#,
            |_, value| {
                has_digit(value)
                    || (value.len() >= 20
                        && value.bytes().any(|b| b.is_ascii_uppercase())
                        && value.bytes().any(|b| b.is_ascii_lowercase())
                        && !TYPE_NAME.is_match(value))
            },
        ),
        Rule::new(
            SecretKind::BasicAuth,
            r#"(?i)\bauthorization(?:\\?["'])?\s*:\s*(?:\\?["'])?basic\s+(?P<secret>[A-Za-z0-9+/]{8,}={0,2})"#,
            always,
        ),
        Rule::new(
            SecretKind::UrlCredentials,
            r#"\b[A-Za-z][A-Za-z0-9+.\-]*://(?P<secret>(?P<user>[^\s:/\[\]"'<>]*):(?:(?P<pass>[^\s/?#\[\]"'<>]+)|(?P<slashed>[^\s?#\[\]"'<>@]+)))@(?P<digest>sha(?:256|512):)?"#,
            url_credentials,
        ),
        Rule::new(
            SecretKind::BasicAuth,
            r#"\bcurl\b[^\n|;&]*?\s(?:-[A-Za-z0-9]*u|--user)[ \t]*["']?(?P<user>[^\s:'"]+):(?P<secret>[^\s'"\[]+)"#,
            |caps, value| !is_placeholder(group(caps, "user")) && !is_placeholder(value),
        ),
        Rule::new(
            SecretKind::Secret,
            &format!(
                r#"{}(?:[^\n|;&]*?[ \t,])?["']?-p["']?(?P<secret>[^\s'",\[][^\s'"\[]*)"#,
                mysql_command()
            ),
            |_, value| !is_placeholder(value),
        ),
        Rule::new(
            SecretKind::Secret,
            r#"\b(?:docker|podman|nerdctl|skopeo|buildah|oras|helm(?:[ \t]+registry)?)[ \t]+login\b[^\n|;&]*?\s-p[ \t]*["']?(?P<secret>[^\s'"\[]+)"#,
            |_, value| !is_placeholder(value),
        ),
        Rule::new(
            SecretKind::Secret,
            r#"\bsshpass(?:[ \t]+(?:-[fdP][ \t]+[^\s\-]\S*|-[^\s\-p]\S*))*[ \t]+-p[ \t]*["']?(?P<secret>[^\s'"\[]+)"#,
            |_, value| !is_placeholder(value),
        ),
        Rule::new(
            SecretKind::Secret,
            r"\b(?:machine\s+\S+|default)\s+login\s+\S+\s+password\s+(?P<secret>[^\s\[]+)",
            |_, value| !is_placeholder(value),
        ),
    ]
});

/// Redacts content and context in place; `true` when either changed.
pub fn redact_memory(memory: &mut Memory) -> bool {
    let content = redact_for_store(&memory.content);
    let mut changed = content != memory.content;
    memory.content = content;
    if let Some(context) = memory.context.as_deref() {
        let redacted = redact_for_store(context);
        changed |= redacted != context;
        memory.context = Some(redacted);
    }
    changed
}

#[cfg(test)]
mod tests;