-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.js
More file actions
215 lines (169 loc) · 6.11 KB
/
Copy pathsecurity.js
File metadata and controls
215 lines (169 loc) · 6.11 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
// ==========================================
// Security Module — Protects the AI Agent Network
// ==========================================
// Handles: allowlists, rate limiting, agent auth,
// message size caps, input sanitization, and audit logging.
import crypto from 'crypto';
import config from './config.js';
import { auditLog } from './audit-log.js';
import { checkJailbreak } from './jailbreak-defense.js';
const sec = config.security;
// ---- 1. Allowlist / Blocklist ----
export function isAllowed(sender) {
if (!sec.enableAllowlist) return true;
// Check blocklist first (always blocks even if allowlist is off)
if (sec.blocklist.length > 0) {
const normalized = normalizeSender(sender);
if (sec.blocklist.some(b => normalized.includes(normalizeSender(b)))) {
auditLog('BLOCK', 'blocklist-hit', { sender });
return false;
}
}
// If allowlist is enabled but empty, allow everyone (open mode)
if (sec.allowlist.length === 0) return true;
const normalized = normalizeSender(sender);
const allowed = sec.allowlist.some(a => normalized.includes(normalizeSender(a)));
if (!allowed) {
auditLog('BLOCK', 'not-on-allowlist', { sender });
}
return allowed;
}
function normalizeSender(s) {
// Strip WhatsApp suffixes like @s.whatsapp.net or @g.us for comparison
return s.replace(/@s\.whatsapp\.net$/, '').replace(/@g\.us$/, '').trim();
}
// ---- 2. Rate Limiting ----
const rateBuckets = new Map(); // sender -> { count, windowStart }
export function checkRateLimit(sender) {
if (!sec.enableRateLimit) return true;
const now = Date.now();
const bucket = rateBuckets.get(sender);
if (!bucket || (now - bucket.windowStart) > sec.rateLimitWindowMs) {
// New window
rateBuckets.set(sender, { count: 1, windowStart: now });
return true;
}
bucket.count++;
if (bucket.count > sec.rateLimitMaxMessages) {
auditLog('BLOCK', 'rate-limited', { sender, count: bucket.count, window: sec.rateLimitWindowMs });
return false;
}
return true;
}
// Cleanup stale buckets every 5 minutes
setInterval(() => {
const now = Date.now();
for (const [key, bucket] of rateBuckets) {
if (now - bucket.windowStart > sec.rateLimitWindowMs * 2) {
rateBuckets.delete(key);
}
}
}, 5 * 60 * 1000).unref();
// ---- 3. Message Size Limits ----
export function checkMessageSize(text) {
if (text.length > sec.maxMessageLength) {
auditLog('BLOCK', 'message-too-large', { length: text.length, max: sec.maxMessageLength });
return false;
}
return true;
}
// ---- 4. Agent Authentication (shared secret HMAC) ----
export function signAgentMessage(messageObj) {
if (!sec.agentSecret) return messageObj;
const payload = JSON.stringify({
from: messageObj.from,
to: messageObj.to,
timestamp: messageObj.timestamp,
conversationId: messageObj.conversationId,
payload: messageObj.payload,
});
const hmac = crypto.createHmac('sha256', sec.agentSecret).update(payload).digest('hex');
return { ...messageObj, auth: { hmac, algorithm: 'sha256' } };
}
export function verifyAgentMessage(messageObj) {
if (!sec.requireAgentAuth) return true;
if (!sec.agentSecret) return true; // no secret configured, skip
if (!messageObj.auth?.hmac) {
auditLog('BLOCK', 'missing-agent-auth', { from: messageObj.from?.agentName });
return false;
}
const payload = JSON.stringify({
from: messageObj.from,
to: messageObj.to,
timestamp: messageObj.timestamp,
conversationId: messageObj.conversationId,
payload: messageObj.payload,
});
const expected = crypto.createHmac('sha256', sec.agentSecret).update(payload).digest('hex');
const valid = crypto.timingSafeEqual(
Buffer.from(messageObj.auth.hmac, 'hex'),
Buffer.from(expected, 'hex')
);
if (!valid) {
auditLog('BLOCK', 'invalid-agent-hmac', { from: messageObj.from?.agentName });
}
return valid;
}
// ---- 5. Input Sanitization (prompt injection guards) ----
// Now delegates to the comprehensive jailbreak-defense module
export function sanitizeInput(text) {
if (!sec.enableInputSanitization) return { clean: true, text };
const result = checkJailbreak('security-gate', text);
if (result.blocked && sec.blockPromptInjection) {
auditLog('WARN', 'prompt-injection-attempt', {
threats: result.threats.map(t => `${t.layer}:${t.category || ''}`).join(', '),
snippet: text.slice(0, 100),
});
return { clean: false, text, reason: 'Suspicious input detected and blocked.' };
}
return { clean: true, text };
}
// ---- 6. Message Timestamp Validation (replay attack prevention) ----
export function checkMessageAge(messageObj) {
if (!sec.maxMessageAgeMs) return true;
if (!messageObj.timestamp) return true;
const age = Date.now() - new Date(messageObj.timestamp).getTime();
if (Math.abs(age) > sec.maxMessageAgeMs) {
auditLog('BLOCK', 'stale-or-future-message', {
from: messageObj.from?.agentName,
age: Math.round(age / 1000) + 's',
});
return false;
}
return true;
}
// ---- Master Gate — run all checks ----
export function securityGate(sender, text) {
// 1. Allowlist
if (!isAllowed(sender)) {
return { allowed: false, reason: 'You are not authorized to use this agent.' };
}
// 2. Rate limit
if (!checkRateLimit(sender)) {
return { allowed: false, reason: 'Too many messages. Please wait a moment.' };
}
// 3. Message size
if (!checkMessageSize(text)) {
return { allowed: false, reason: `Message too long (max ${sec.maxMessageLength} chars).` };
}
// 4. Input sanitization
const sanitized = sanitizeInput(text);
if (!sanitized.clean) {
return { allowed: false, reason: sanitized.reason };
}
return { allowed: true };
}
export function securityGateAgent(sender, text, agentMsg) {
// Run the base checks
const base = securityGate(sender, text);
if (!base.allowed) return base;
// 5. Agent HMAC auth
if (!verifyAgentMessage(agentMsg)) {
return { allowed: false, reason: 'Agent authentication failed.' };
}
// 6. Replay protection
if (!checkMessageAge(agentMsg)) {
return { allowed: false, reason: 'Message expired or from the future.' };
}
return { allowed: true };
}