@a13xu/lucid 1.1.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +221 -99
- package/build/config.d.ts +37 -0
- package/build/config.js +45 -0
- package/build/database.d.ts +54 -0
- package/build/database.js +175 -62
- package/build/guardian/checklist.js +66 -66
- package/build/guardian/coding-analyzer.d.ts +11 -0
- package/build/guardian/coding-analyzer.js +393 -0
- package/build/guardian/coding-rules.d.ts +1 -0
- package/build/guardian/coding-rules.js +97 -0
- package/build/index.js +241 -2
- package/build/indexer/ast.d.ts +9 -0
- package/build/indexer/ast.js +158 -0
- package/build/indexer/file.d.ts +15 -0
- package/build/indexer/file.js +100 -0
- package/build/indexer/project.d.ts +8 -0
- package/build/indexer/project.js +320 -0
- package/build/memory/experience.d.ts +11 -0
- package/build/memory/experience.js +85 -0
- package/build/retrieval/context.d.ts +29 -0
- package/build/retrieval/context.js +219 -0
- package/build/retrieval/qdrant.d.ts +16 -0
- package/build/retrieval/qdrant.js +135 -0
- package/build/retrieval/tfidf.d.ts +14 -0
- package/build/retrieval/tfidf.js +64 -0
- package/build/security/alerts.d.ts +44 -0
- package/build/security/alerts.js +228 -0
- package/build/security/env.d.ts +24 -0
- package/build/security/env.js +85 -0
- package/build/security/guard.d.ts +35 -0
- package/build/security/guard.js +133 -0
- package/build/security/ratelimit.d.ts +34 -0
- package/build/security/ratelimit.js +105 -0
- package/build/security/smtp.d.ts +26 -0
- package/build/security/smtp.js +125 -0
- package/build/security/ssrf.d.ts +18 -0
- package/build/security/ssrf.js +109 -0
- package/build/security/waf.d.ts +33 -0
- package/build/security/waf.js +174 -0
- package/build/store/content.d.ts +3 -0
- package/build/store/content.js +11 -0
- package/build/tools/coding-guard.d.ts +24 -0
- package/build/tools/coding-guard.js +82 -0
- package/build/tools/context.d.ts +39 -0
- package/build/tools/context.js +105 -0
- package/build/tools/grep.d.ts +17 -0
- package/build/tools/grep.js +65 -0
- package/build/tools/init.d.ts +51 -0
- package/build/tools/init.js +212 -0
- package/build/tools/remember.d.ts +4 -4
- package/build/tools/reward.d.ts +29 -0
- package/build/tools/reward.js +154 -0
- package/build/tools/sync.d.ts +18 -0
- package/build/tools/sync.js +76 -0
- package/package.json +55 -48
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Qdrant vector search — via direct REST API calls (no npm dependency)
|
|
2
|
+
// Only active when QDRANT_URL is set (via env var or lucid.config.json)
|
|
3
|
+
// Falls back silently to TF-IDF when unavailable
|
|
4
|
+
import { safeFetch } from "../security/ssrf.js";
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
// Embedding generation (OpenAI-compatible endpoint)
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
async function embed(texts, cfg) {
|
|
9
|
+
if (!cfg.embeddingApiKey) {
|
|
10
|
+
throw new Error("No embedding API key (set OPENAI_API_KEY or embeddingApiKey in lucid.config.json)");
|
|
11
|
+
}
|
|
12
|
+
const url = cfg.embeddingUrl ?? "https://api.openai.com/v1/embeddings";
|
|
13
|
+
const res = await safeFetch(url, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: {
|
|
16
|
+
"Content-Type": "application/json",
|
|
17
|
+
Authorization: `Bearer ${cfg.embeddingApiKey}`,
|
|
18
|
+
},
|
|
19
|
+
body: JSON.stringify({ model: cfg.embeddingModel ?? "text-embedding-3-small", input: texts }),
|
|
20
|
+
});
|
|
21
|
+
if (!res.ok) {
|
|
22
|
+
const body = await res.text();
|
|
23
|
+
throw new Error(`Embedding API ${res.status}: ${body.slice(0, 200)}`);
|
|
24
|
+
}
|
|
25
|
+
const json = await res.json();
|
|
26
|
+
return json.data.map((d) => d.embedding);
|
|
27
|
+
}
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Qdrant REST helpers
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
async function qdrantRequest(cfg, method, path, body) {
|
|
32
|
+
const url = `${cfg.url.replace(/\/$/, "")}${path}`;
|
|
33
|
+
const headers = { "Content-Type": "application/json" };
|
|
34
|
+
if (cfg.apiKey)
|
|
35
|
+
headers["api-key"] = cfg.apiKey;
|
|
36
|
+
const res = await safeFetch(url, {
|
|
37
|
+
method,
|
|
38
|
+
headers,
|
|
39
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
40
|
+
});
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
const text = await res.text();
|
|
43
|
+
throw new Error(`Qdrant ${method} ${path} → ${res.status}: ${text.slice(0, 200)}`);
|
|
44
|
+
}
|
|
45
|
+
return res.json();
|
|
46
|
+
}
|
|
47
|
+
async function ensureCollection(cfg) {
|
|
48
|
+
const col = cfg.collection;
|
|
49
|
+
try {
|
|
50
|
+
await qdrantRequest(cfg, "GET", `/collections/${col}`);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Create collection
|
|
54
|
+
await qdrantRequest(cfg, "PUT", `/collections/${col}`, {
|
|
55
|
+
vectors: { size: cfg.vectorDim ?? 1536, distance: "Cosine" },
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Chunking
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
const CHUNK_LINES = 80;
|
|
63
|
+
function chunkFile(filepath, text) {
|
|
64
|
+
const lines = text.split("\n");
|
|
65
|
+
const chunks = [];
|
|
66
|
+
for (let i = 0; i < lines.length; i += CHUNK_LINES) {
|
|
67
|
+
const chunkText = lines.slice(i, i + CHUNK_LINES).join("\n");
|
|
68
|
+
const chunkIndex = Math.floor(i / CHUNK_LINES);
|
|
69
|
+
// Deterministic integer ID from filepath + chunk index
|
|
70
|
+
const id = stableId(`${filepath}::${chunkIndex}`);
|
|
71
|
+
chunks.push({ id, text: chunkText, chunkIndex });
|
|
72
|
+
}
|
|
73
|
+
return chunks;
|
|
74
|
+
}
|
|
75
|
+
function stableId(s) {
|
|
76
|
+
let h = 0x811c9dc5;
|
|
77
|
+
for (let i = 0; i < s.length; i++) {
|
|
78
|
+
h ^= s.charCodeAt(i);
|
|
79
|
+
h = Math.imul(h, 0x01000193);
|
|
80
|
+
}
|
|
81
|
+
// Ensure positive 32-bit int
|
|
82
|
+
return (h >>> 0) % 2_000_000_000;
|
|
83
|
+
}
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
// Public API
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
/** Index one file into Qdrant (called by sync_file when Qdrant is configured). */
|
|
88
|
+
export async function indexFileInQdrant(filepath, text, cfg) {
|
|
89
|
+
await ensureCollection(cfg);
|
|
90
|
+
const chunks = chunkFile(filepath, text);
|
|
91
|
+
if (chunks.length === 0)
|
|
92
|
+
return;
|
|
93
|
+
// Batch embed (max 96 texts per request for most providers)
|
|
94
|
+
const BATCH = 32;
|
|
95
|
+
for (let b = 0; b < chunks.length; b += BATCH) {
|
|
96
|
+
const batch = chunks.slice(b, b + BATCH);
|
|
97
|
+
const vectors = await embed(batch.map((c) => c.text), cfg);
|
|
98
|
+
const points = batch.map((c, idx) => ({
|
|
99
|
+
id: c.id,
|
|
100
|
+
vector: vectors[idx],
|
|
101
|
+
payload: { filepath, chunkIndex: c.chunkIndex, text: c.text },
|
|
102
|
+
}));
|
|
103
|
+
await qdrantRequest(cfg, "PUT", `/collections/${cfg.collection}/points`, {
|
|
104
|
+
points,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Top-k semantic search across all indexed chunks. */
|
|
109
|
+
export async function searchQdrant(query, topK, cfg) {
|
|
110
|
+
const [queryVec] = await embed([query], cfg);
|
|
111
|
+
if (!queryVec)
|
|
112
|
+
return [];
|
|
113
|
+
const result = await qdrantRequest(cfg, "POST", `/collections/${cfg.collection}/points/search`, {
|
|
114
|
+
vector: queryVec,
|
|
115
|
+
limit: topK,
|
|
116
|
+
with_payload: true,
|
|
117
|
+
});
|
|
118
|
+
return result.result.map((r) => ({
|
|
119
|
+
id: r.id,
|
|
120
|
+
filepath: r.payload["filepath"],
|
|
121
|
+
chunkIndex: r.payload["chunkIndex"],
|
|
122
|
+
text: r.payload["text"],
|
|
123
|
+
score: r.score,
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
/** Check if Qdrant collection exists and is reachable. */
|
|
127
|
+
export async function pingQdrant(cfg) {
|
|
128
|
+
try {
|
|
129
|
+
await qdrantRequest(cfg, "GET", `/collections/${cfg.collection}`);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function tokenize(text: string): string[];
|
|
2
|
+
export interface ScoredFile {
|
|
3
|
+
filepath: string;
|
|
4
|
+
score: number;
|
|
5
|
+
matchedTerms: string[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Rank files by TF-IDF relevance to a query.
|
|
9
|
+
* Returns all files sorted by score descending (score=0 files included at bottom).
|
|
10
|
+
*/
|
|
11
|
+
export declare function rankByRelevance(query: string, files: Array<{
|
|
12
|
+
filepath: string;
|
|
13
|
+
text: string;
|
|
14
|
+
}>): ScoredFile[];
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// TF-IDF scoring — pure JS, no external deps
|
|
2
|
+
// Used as the default relevance engine when Qdrant is not configured
|
|
3
|
+
const STOPWORDS = new Set([
|
|
4
|
+
"the", "and", "for", "are", "but", "not", "you", "all", "can", "had",
|
|
5
|
+
"her", "was", "one", "our", "out", "day", "get", "has", "him", "his",
|
|
6
|
+
"how", "its", "let", "may", "new", "now", "old", "own", "say", "she",
|
|
7
|
+
"too", "use", "way", "who", "will", "with", "that", "this", "from",
|
|
8
|
+
"they", "been", "have", "their", "said", "each", "which", "what",
|
|
9
|
+
// code keywords (too common to be discriminative)
|
|
10
|
+
"return", "const", "import", "export", "function", "class", "type",
|
|
11
|
+
"interface", "string", "number", "boolean", "void", "null", "undefined",
|
|
12
|
+
"async", "await", "true", "false", "default", "module", "require",
|
|
13
|
+
"self", "def", "pass", "else", "elif", "then", "end", "var", "let",
|
|
14
|
+
]);
|
|
15
|
+
export function tokenize(text) {
|
|
16
|
+
return text
|
|
17
|
+
.toLowerCase()
|
|
18
|
+
.replace(/[^a-z0-9_]/g, " ")
|
|
19
|
+
.split(/\s+/)
|
|
20
|
+
.filter((t) => t.length >= 3 && !STOPWORDS.has(t));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Rank files by TF-IDF relevance to a query.
|
|
24
|
+
* Returns all files sorted by score descending (score=0 files included at bottom).
|
|
25
|
+
*/
|
|
26
|
+
export function rankByRelevance(query, files) {
|
|
27
|
+
if (files.length === 0)
|
|
28
|
+
return [];
|
|
29
|
+
const queryTerms = tokenize(query);
|
|
30
|
+
if (queryTerms.length === 0) {
|
|
31
|
+
return files.map((f) => ({ filepath: f.filepath, score: 0, matchedTerms: [] }));
|
|
32
|
+
}
|
|
33
|
+
const N = files.length;
|
|
34
|
+
// Compute per-doc term frequencies + document frequencies
|
|
35
|
+
const df = new Map();
|
|
36
|
+
const docTF = [];
|
|
37
|
+
for (const file of files) {
|
|
38
|
+
const tokens = tokenize(file.text);
|
|
39
|
+
const tf = new Map();
|
|
40
|
+
for (const t of tokens)
|
|
41
|
+
tf.set(t, (tf.get(t) ?? 0) + 1);
|
|
42
|
+
docTF.push(tf);
|
|
43
|
+
for (const term of tf.keys())
|
|
44
|
+
df.set(term, (df.get(term) ?? 0) + 1);
|
|
45
|
+
}
|
|
46
|
+
const results = [];
|
|
47
|
+
for (let i = 0; i < files.length; i++) {
|
|
48
|
+
const tf = docTF[i];
|
|
49
|
+
const totalTokens = Math.max([...tf.values()].reduce((a, b) => a + b, 0), 1);
|
|
50
|
+
let score = 0;
|
|
51
|
+
const matched = [];
|
|
52
|
+
for (const qt of queryTerms) {
|
|
53
|
+
const freq = tf.get(qt) ?? 0;
|
|
54
|
+
if (freq > 0) {
|
|
55
|
+
const tfScore = freq / totalTokens;
|
|
56
|
+
const idf = Math.log((N + 1) / ((df.get(qt) ?? 0) + 1)) + 1;
|
|
57
|
+
score += tfScore * idf;
|
|
58
|
+
matched.push(qt);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
results.push({ filepath: files[i].filepath, score, matchedTerms: matched });
|
|
62
|
+
}
|
|
63
|
+
return results.sort((a, b) => b.score - a.score);
|
|
64
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security alert dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* Channels (all optional, configured via lucid-admin.json + env vars):
|
|
5
|
+
* - Webhook (generic HTTP POST, HMAC-SHA256 signed)
|
|
6
|
+
* - Slack (incoming webhook)
|
|
7
|
+
* - Email (SMTP via smtp.ts)
|
|
8
|
+
*
|
|
9
|
+
* Sensitive values MUST come from environment variables:
|
|
10
|
+
* LUCID_SMTP_PASS — SMTP password
|
|
11
|
+
* LUCID_WEBHOOK_SECRET — HMAC signing secret for webhook
|
|
12
|
+
*
|
|
13
|
+
* Config is stored in <project>/.claude/lucid-admin.json (non-sensitive fields only).
|
|
14
|
+
*/
|
|
15
|
+
import type { Severity } from "./waf.js";
|
|
16
|
+
export interface AlertEvent {
|
|
17
|
+
severity: Severity;
|
|
18
|
+
rule: string;
|
|
19
|
+
tool: string;
|
|
20
|
+
detail: string;
|
|
21
|
+
timestamp: string;
|
|
22
|
+
projectDir?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface AdminConfig {
|
|
25
|
+
adminName?: string;
|
|
26
|
+
adminEmail?: string;
|
|
27
|
+
smtpHost?: string;
|
|
28
|
+
smtpPort?: number;
|
|
29
|
+
smtpUser?: string;
|
|
30
|
+
smtpFrom?: string;
|
|
31
|
+
webhookUrl?: string;
|
|
32
|
+
slackWebhookUrl?: string;
|
|
33
|
+
/** Severities that trigger an alert (default: ["critical", "high"]) */
|
|
34
|
+
alertOn?: Severity[];
|
|
35
|
+
projectName?: string;
|
|
36
|
+
}
|
|
37
|
+
export declare const ADMIN_CONFIG_FILE = "lucid-admin.json";
|
|
38
|
+
export declare function loadAdminConfig(projectDir: string): AdminConfig;
|
|
39
|
+
export declare function saveAdminConfig(projectDir: string, cfg: AdminConfig): void;
|
|
40
|
+
export declare function getAdminConfig(): AdminConfig;
|
|
41
|
+
export declare function isAdminConfigured(): boolean;
|
|
42
|
+
export declare function sendAlert(event: AlertEvent): Promise<void>;
|
|
43
|
+
/** Send a test alert to verify all configured channels work. */
|
|
44
|
+
export declare function sendTestAlert(projectDir: string): Promise<string[]>;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security alert dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* Channels (all optional, configured via lucid-admin.json + env vars):
|
|
5
|
+
* - Webhook (generic HTTP POST, HMAC-SHA256 signed)
|
|
6
|
+
* - Slack (incoming webhook)
|
|
7
|
+
* - Email (SMTP via smtp.ts)
|
|
8
|
+
*
|
|
9
|
+
* Sensitive values MUST come from environment variables:
|
|
10
|
+
* LUCID_SMTP_PASS — SMTP password
|
|
11
|
+
* LUCID_WEBHOOK_SECRET — HMAC signing secret for webhook
|
|
12
|
+
*
|
|
13
|
+
* Config is stored in <project>/.claude/lucid-admin.json (non-sensitive fields only).
|
|
14
|
+
*/
|
|
15
|
+
import { createHmac } from "crypto";
|
|
16
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
17
|
+
import { join } from "path";
|
|
18
|
+
import { safeFetch } from "./ssrf.js";
|
|
19
|
+
import { sendEmail } from "./smtp.js";
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// Config loader
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
let _config = null;
|
|
24
|
+
let _configDir = null;
|
|
25
|
+
export const ADMIN_CONFIG_FILE = "lucid-admin.json";
|
|
26
|
+
export function loadAdminConfig(projectDir) {
|
|
27
|
+
_configDir = join(projectDir, ".claude");
|
|
28
|
+
const path = join(_configDir, ADMIN_CONFIG_FILE);
|
|
29
|
+
if (existsSync(path)) {
|
|
30
|
+
try {
|
|
31
|
+
_config = JSON.parse(readFileSync(path, "utf-8"));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
_config = {};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
_config = {};
|
|
39
|
+
}
|
|
40
|
+
return _config;
|
|
41
|
+
}
|
|
42
|
+
export function saveAdminConfig(projectDir, cfg) {
|
|
43
|
+
const dir = join(projectDir, ".claude");
|
|
44
|
+
mkdirSync(dir, { recursive: true });
|
|
45
|
+
// Merge with existing
|
|
46
|
+
const existing = loadAdminConfig(projectDir);
|
|
47
|
+
const merged = { ...existing, ...cfg };
|
|
48
|
+
_config = merged;
|
|
49
|
+
// Strip any sensitive fields that shouldn't be persisted to disk
|
|
50
|
+
// (user might accidentally pass smtpPass — we silently drop it)
|
|
51
|
+
const safe = { ...merged };
|
|
52
|
+
delete safe["smtpPass"];
|
|
53
|
+
delete safe["webhookSecret"];
|
|
54
|
+
writeFileSync(join(dir, ADMIN_CONFIG_FILE), JSON.stringify(safe, null, 2) + "\n", "utf-8");
|
|
55
|
+
}
|
|
56
|
+
export function getAdminConfig() {
|
|
57
|
+
return _config ?? {};
|
|
58
|
+
}
|
|
59
|
+
export function isAdminConfigured() {
|
|
60
|
+
const c = _config ?? {};
|
|
61
|
+
return !!(c.adminEmail || c.webhookUrl || c.slackWebhookUrl);
|
|
62
|
+
}
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// HMAC webhook signature
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
function signPayload(body) {
|
|
67
|
+
const secret = process.env["LUCID_WEBHOOK_SECRET"];
|
|
68
|
+
if (!secret)
|
|
69
|
+
return null;
|
|
70
|
+
return "sha256=" + createHmac("sha256", secret).update(body, "utf-8").digest("hex");
|
|
71
|
+
}
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Channels
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
async function dispatchWebhook(url, event) {
|
|
76
|
+
const body = JSON.stringify({
|
|
77
|
+
source: "lucid-security",
|
|
78
|
+
...event,
|
|
79
|
+
});
|
|
80
|
+
const headers = { "Content-Type": "application/json" };
|
|
81
|
+
const sig = signPayload(body);
|
|
82
|
+
if (sig)
|
|
83
|
+
headers["X-Lucid-Signature"] = sig;
|
|
84
|
+
const res = await safeFetch(url, { method: "POST", headers, body });
|
|
85
|
+
if (!res.ok)
|
|
86
|
+
throw new Error(`Webhook HTTP ${res.status}`);
|
|
87
|
+
}
|
|
88
|
+
async function dispatchSlack(webhookUrl, event) {
|
|
89
|
+
const icon = event.severity === "critical" ? "🚨" : "⚠️";
|
|
90
|
+
const payload = {
|
|
91
|
+
text: `${icon} *Lucid Security Alert* — ${event.severity.toUpperCase()}`,
|
|
92
|
+
blocks: [
|
|
93
|
+
{
|
|
94
|
+
type: "section",
|
|
95
|
+
text: {
|
|
96
|
+
type: "mrkdwn",
|
|
97
|
+
text: `${icon} *[${event.severity.toUpperCase()}] ${event.rule}*\n` +
|
|
98
|
+
`*Tool:* \`${event.tool}\`\n` +
|
|
99
|
+
`*Detail:* ${event.detail}\n` +
|
|
100
|
+
`*Project:* ${_config?.projectName ?? "unknown"}\n` +
|
|
101
|
+
`*Time:* ${event.timestamp}`,
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
};
|
|
106
|
+
const res = await safeFetch(webhookUrl, {
|
|
107
|
+
method: "POST",
|
|
108
|
+
headers: { "Content-Type": "application/json" },
|
|
109
|
+
body: JSON.stringify(payload),
|
|
110
|
+
});
|
|
111
|
+
if (!res.ok)
|
|
112
|
+
throw new Error(`Slack HTTP ${res.status}`);
|
|
113
|
+
}
|
|
114
|
+
async function dispatchEmail(event) {
|
|
115
|
+
const cfg = _config ?? {};
|
|
116
|
+
const smtpPass = process.env["LUCID_SMTP_PASS"];
|
|
117
|
+
if (!smtpPass)
|
|
118
|
+
throw new Error("LUCID_SMTP_PASS env var not set");
|
|
119
|
+
if (!cfg.adminEmail)
|
|
120
|
+
throw new Error("adminEmail not configured");
|
|
121
|
+
if (!cfg.smtpHost)
|
|
122
|
+
throw new Error("smtpHost not configured");
|
|
123
|
+
const smtpCfg = {
|
|
124
|
+
host: cfg.smtpHost,
|
|
125
|
+
port: cfg.smtpPort ?? 587,
|
|
126
|
+
user: cfg.smtpUser ?? cfg.adminEmail,
|
|
127
|
+
pass: smtpPass,
|
|
128
|
+
from: cfg.smtpFrom ?? `Lucid Security <${cfg.smtpUser ?? cfg.adminEmail}>`,
|
|
129
|
+
secure: cfg.smtpPort === 465,
|
|
130
|
+
};
|
|
131
|
+
const icon = event.severity === "critical" ? "🚨" : "⚠️";
|
|
132
|
+
const subject = `${icon} [${event.severity.toUpperCase()}] Lucid Security Alert — ${event.rule}`;
|
|
133
|
+
const body = [
|
|
134
|
+
`Lucid Security Alert`,
|
|
135
|
+
`${"─".repeat(40)}`,
|
|
136
|
+
``,
|
|
137
|
+
`Severity : ${event.severity.toUpperCase()}`,
|
|
138
|
+
`Rule : ${event.rule}`,
|
|
139
|
+
`Tool : ${event.tool}`,
|
|
140
|
+
`Detail : ${event.detail}`,
|
|
141
|
+
`Project : ${cfg.projectName ?? "unknown"}`,
|
|
142
|
+
`Time : ${event.timestamp}`,
|
|
143
|
+
``,
|
|
144
|
+
`─────────────────────────────────────────`,
|
|
145
|
+
`This alert was sent automatically by lucid.`,
|
|
146
|
+
`Configure alerts in .claude/lucid-admin.json`,
|
|
147
|
+
].join("\n");
|
|
148
|
+
await sendEmail(smtpCfg, { to: cfg.adminEmail, subject, body });
|
|
149
|
+
}
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// Main dispatch — fire-and-forget safe
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
const SEVERITY_ORDER = { low: 0, medium: 1, high: 2, critical: 3 };
|
|
154
|
+
export async function sendAlert(event) {
|
|
155
|
+
const cfg = _config ?? {};
|
|
156
|
+
const alertOn = cfg.alertOn ?? ["critical", "high"];
|
|
157
|
+
// Check if this severity is configured to alert
|
|
158
|
+
const minSeverity = Math.min(...alertOn.map((s) => SEVERITY_ORDER[s]));
|
|
159
|
+
if (SEVERITY_ORDER[event.severity] < minSeverity)
|
|
160
|
+
return;
|
|
161
|
+
const errors = [];
|
|
162
|
+
// Dispatch to all configured channels concurrently
|
|
163
|
+
const dispatches = [];
|
|
164
|
+
if (cfg.webhookUrl) {
|
|
165
|
+
dispatches.push(dispatchWebhook(cfg.webhookUrl, event).catch((e) => {
|
|
166
|
+
errors.push(`webhook: ${e.message}`);
|
|
167
|
+
}));
|
|
168
|
+
}
|
|
169
|
+
if (cfg.slackWebhookUrl) {
|
|
170
|
+
dispatches.push(dispatchSlack(cfg.slackWebhookUrl, event).catch((e) => {
|
|
171
|
+
errors.push(`slack: ${e.message}`);
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
if (cfg.adminEmail && cfg.smtpHost) {
|
|
175
|
+
dispatches.push(dispatchEmail(event).catch((e) => {
|
|
176
|
+
errors.push(`email: ${e.message}`);
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
await Promise.all(dispatches);
|
|
180
|
+
if (errors.length > 0) {
|
|
181
|
+
console.error(`[lucid:alerts] ⚠️ Failed to deliver ${errors.length} alert(s): ${errors.join("; ")}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** Send a test alert to verify all configured channels work. */
|
|
185
|
+
export async function sendTestAlert(projectDir) {
|
|
186
|
+
loadAdminConfig(projectDir);
|
|
187
|
+
const event = {
|
|
188
|
+
severity: "low",
|
|
189
|
+
rule: "TEST",
|
|
190
|
+
tool: "init_project",
|
|
191
|
+
detail: "Lucid security alerts are correctly configured and working.",
|
|
192
|
+
timestamp: new Date().toISOString(),
|
|
193
|
+
projectDir,
|
|
194
|
+
};
|
|
195
|
+
const results = [];
|
|
196
|
+
const cfg = _config ?? {};
|
|
197
|
+
if (cfg.webhookUrl) {
|
|
198
|
+
try {
|
|
199
|
+
await dispatchWebhook(cfg.webhookUrl, event);
|
|
200
|
+
results.push("✅ Webhook: test alert delivered");
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
results.push(`❌ Webhook: ${e.message}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (cfg.slackWebhookUrl) {
|
|
207
|
+
try {
|
|
208
|
+
await dispatchSlack(cfg.slackWebhookUrl, event);
|
|
209
|
+
results.push("✅ Slack: test alert delivered");
|
|
210
|
+
}
|
|
211
|
+
catch (e) {
|
|
212
|
+
results.push(`❌ Slack: ${e.message}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (cfg.adminEmail && cfg.smtpHost) {
|
|
216
|
+
try {
|
|
217
|
+
await dispatchEmail(event);
|
|
218
|
+
results.push(`✅ Email: test alert sent to ${cfg.adminEmail}`);
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
results.push(`❌ Email: ${e.message}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (results.length === 0) {
|
|
225
|
+
results.push("⚠️ No alert channels configured yet");
|
|
226
|
+
}
|
|
227
|
+
return results;
|
|
228
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secure environment variable access.
|
|
3
|
+
*
|
|
4
|
+
* Rules:
|
|
5
|
+
* - Never expose raw values in error messages or logs
|
|
6
|
+
* - Always validate format before use
|
|
7
|
+
* - Mask secrets in any diagnostic output
|
|
8
|
+
*/
|
|
9
|
+
/** Get a required env var. Throws a safe error (no value leak) if missing. */
|
|
10
|
+
export declare function requireEnv(key: string): string;
|
|
11
|
+
/** Get an optional env var with a typed default. */
|
|
12
|
+
export declare function optionalEnv(key: string, defaultValue: string): string;
|
|
13
|
+
/** Get a numeric env var. Returns default if missing or non-numeric. */
|
|
14
|
+
export declare function numericEnv(key: string, defaultValue: number): number;
|
|
15
|
+
/** Get a boolean env var ("true"/"1"/"yes" → true, anything else → false). */
|
|
16
|
+
export declare function boolEnv(key: string, defaultValue: boolean): boolean;
|
|
17
|
+
/** Mask a value for safe logging. Shows first 4 and last 2 chars only. */
|
|
18
|
+
export declare function maskSecret(value: string): string;
|
|
19
|
+
/** Safe env dump for diagnostics — masks any key that looks sensitive. */
|
|
20
|
+
export declare function safeDump(keys: string[]): Record<string, string>;
|
|
21
|
+
/** Validate a URL-format env var. Throws with safe message on failure. */
|
|
22
|
+
export declare function requireEnvUrl(key: string): string;
|
|
23
|
+
/** Validate that an API key looks like a real key (non-trivial length). */
|
|
24
|
+
export declare function requireEnvApiKey(key: string, minLength?: number): string;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secure environment variable access.
|
|
3
|
+
*
|
|
4
|
+
* Rules:
|
|
5
|
+
* - Never expose raw values in error messages or logs
|
|
6
|
+
* - Always validate format before use
|
|
7
|
+
* - Mask secrets in any diagnostic output
|
|
8
|
+
*/
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
// Core getters
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
/** Get a required env var. Throws a safe error (no value leak) if missing. */
|
|
13
|
+
export function requireEnv(key) {
|
|
14
|
+
const val = process.env[key];
|
|
15
|
+
if (!val || val.trim() === "") {
|
|
16
|
+
throw new Error(`Missing required environment variable: ${key}`);
|
|
17
|
+
}
|
|
18
|
+
return val.trim();
|
|
19
|
+
}
|
|
20
|
+
/** Get an optional env var with a typed default. */
|
|
21
|
+
export function optionalEnv(key, defaultValue) {
|
|
22
|
+
const val = process.env[key];
|
|
23
|
+
return val && val.trim() !== "" ? val.trim() : defaultValue;
|
|
24
|
+
}
|
|
25
|
+
/** Get a numeric env var. Returns default if missing or non-numeric. */
|
|
26
|
+
export function numericEnv(key, defaultValue) {
|
|
27
|
+
const raw = process.env[key];
|
|
28
|
+
if (!raw)
|
|
29
|
+
return defaultValue;
|
|
30
|
+
const n = Number(raw.trim());
|
|
31
|
+
return Number.isFinite(n) ? n : defaultValue;
|
|
32
|
+
}
|
|
33
|
+
/** Get a boolean env var ("true"/"1"/"yes" → true, anything else → false). */
|
|
34
|
+
export function boolEnv(key, defaultValue) {
|
|
35
|
+
const raw = process.env[key];
|
|
36
|
+
if (!raw)
|
|
37
|
+
return defaultValue;
|
|
38
|
+
return /^(true|1|yes)$/i.test(raw.trim());
|
|
39
|
+
}
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// Masking for logs / diagnostics
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
const SECRET_PATTERNS = [
|
|
44
|
+
/key/i, /secret/i, /token/i, /password/i, /pwd/i, /auth/i, /credential/i,
|
|
45
|
+
];
|
|
46
|
+
/** Mask a value for safe logging. Shows first 4 and last 2 chars only. */
|
|
47
|
+
export function maskSecret(value) {
|
|
48
|
+
if (value.length <= 8)
|
|
49
|
+
return "***";
|
|
50
|
+
return `${value.slice(0, 4)}…${value.slice(-2)}`;
|
|
51
|
+
}
|
|
52
|
+
/** Safe env dump for diagnostics — masks any key that looks sensitive. */
|
|
53
|
+
export function safeDump(keys) {
|
|
54
|
+
const result = {};
|
|
55
|
+
for (const key of keys) {
|
|
56
|
+
const val = process.env[key];
|
|
57
|
+
if (!val) {
|
|
58
|
+
result[key] = "<not set>";
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const isSensitive = SECRET_PATTERNS.some((p) => p.test(key));
|
|
62
|
+
result[key] = isSensitive ? maskSecret(val) : val;
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Format validators (called before using values)
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
const URL_RE = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;
|
|
70
|
+
/** Validate a URL-format env var. Throws with safe message on failure. */
|
|
71
|
+
export function requireEnvUrl(key) {
|
|
72
|
+
const val = requireEnv(key);
|
|
73
|
+
if (!URL_RE.test(val)) {
|
|
74
|
+
throw new Error(`Environment variable ${key} must be a valid URL (got invalid format)`);
|
|
75
|
+
}
|
|
76
|
+
return val;
|
|
77
|
+
}
|
|
78
|
+
/** Validate that an API key looks like a real key (non-trivial length). */
|
|
79
|
+
export function requireEnvApiKey(key, minLength = 16) {
|
|
80
|
+
const val = requireEnv(key);
|
|
81
|
+
if (val.length < minLength) {
|
|
82
|
+
throw new Error(`Environment variable ${key} appears to be too short for an API key (min ${minLength} chars)`);
|
|
83
|
+
}
|
|
84
|
+
return val;
|
|
85
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security guard — orchestrates all security checks for every tool call.
|
|
3
|
+
*
|
|
4
|
+
* Pipeline per request:
|
|
5
|
+
* 1. Rate limit check
|
|
6
|
+
* 2. WAF input validation (size, injection, path traversal, ReDoS)
|
|
7
|
+
* 3. Output leakage scan (before returning to caller)
|
|
8
|
+
*
|
|
9
|
+
* Enabled by default. Disable per-check via lucid.config.json:
|
|
10
|
+
* { "security": { "rateLimiting": false, "waf": false } }
|
|
11
|
+
*/
|
|
12
|
+
import { type RateLimitConfig } from "./ratelimit.js";
|
|
13
|
+
import { type WafViolation } from "./waf.js";
|
|
14
|
+
export interface SecurityConfig {
|
|
15
|
+
/** Enable/disable rate limiting (default: true) */
|
|
16
|
+
rateLimiting?: boolean;
|
|
17
|
+
/** Enable/disable WAF input checks (default: true) */
|
|
18
|
+
waf?: boolean;
|
|
19
|
+
/** Enable/disable output leakage scan (default: true) */
|
|
20
|
+
outputScan?: boolean;
|
|
21
|
+
/** Per-tool rate limit overrides */
|
|
22
|
+
limits?: Record<string, Partial<RateLimitConfig>>;
|
|
23
|
+
/** Trusted hostnames for outbound requests */
|
|
24
|
+
trustedHosts?: string[];
|
|
25
|
+
}
|
|
26
|
+
export declare function configureGuard(cfg: SecurityConfig): void;
|
|
27
|
+
export interface GuardResult {
|
|
28
|
+
blocked: boolean;
|
|
29
|
+
reason?: string;
|
|
30
|
+
violations?: WafViolation[];
|
|
31
|
+
}
|
|
32
|
+
/** Run all security checks for an inbound tool call. */
|
|
33
|
+
export declare function guardRequest(tool: string, args: unknown): GuardResult;
|
|
34
|
+
/** Scan output for sensitive data leakage. Logs a warning; does not block. */
|
|
35
|
+
export declare function guardOutput(tool: string, text: string): string;
|