n8n-nodes-trusera 0.6.1 → 0.7.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/dist/index.d.ts CHANGED
@@ -9,4 +9,6 @@ export * from './lib/sidecar/pii';
9
9
  export * from './lib/sidecar/contentFilter';
10
10
  export * from './lib/sidecar/evaluator';
11
11
  export * from './lib/sidecar/reporter';
12
+ export * from './lib/sidecar/policyGate';
13
+ export * from './lib/sidecar/toolInterceptor';
12
14
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AAGpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AAGpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC"}
package/dist/index.js CHANGED
@@ -26,4 +26,6 @@ __exportStar(require("./lib/sidecar/pii"), exports);
26
26
  __exportStar(require("./lib/sidecar/contentFilter"), exports);
27
27
  __exportStar(require("./lib/sidecar/evaluator"), exports);
28
28
  __exportStar(require("./lib/sidecar/reporter"), exports);
29
+ __exportStar(require("./lib/sidecar/policyGate"), exports);
30
+ __exportStar(require("./lib/sidecar/toolInterceptor"), exports);
29
31
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA6B;AAC7B,+CAA6B;AAC7B,mDAAiC;AACjC,qDAAmC;AACnC,gDAA8B;AAC9B,sDAAoC;AAEpC,8BAA8B;AAC9B,sDAAoC;AACpC,oDAAkC;AAClC,8DAA4C;AAC5C,0DAAwC;AACxC,yDAAuC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA6B;AAC7B,+CAA6B;AAC7B,mDAAiC;AACjC,qDAAmC;AACnC,gDAA8B;AAC9B,sDAAoC;AAEpC,8BAA8B;AAC9B,sDAAoC;AACpC,oDAAkC;AAClC,8DAA4C;AAC5C,0DAAwC;AACxC,yDAAuC;AACvC,2DAAyC;AACzC,gEAA8C"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Policy Gate Evaluator for the Trusera Sidecar v2.
3
+ *
4
+ * Evaluates proposed tool calls against Cedar policies, PII detection,
5
+ * and optional AI-powered "brain mode" analysis.
6
+ *
7
+ * Key difference from SidecarEvaluator: the Cedar action is the TOOL NAME
8
+ * (e.g., "gmail_send_email") not generic "process_data", enabling
9
+ * tool-specific policies.
10
+ */
11
+ import type { PolicyGateConfig, PolicyGateResult, ToolCallProposal, BrainAnalysis, CheckResult } from './types';
12
+ export declare class PolicyGateEvaluator {
13
+ private config;
14
+ private sidecarEvaluator;
15
+ constructor(config: PolicyGateConfig);
16
+ /** Main entry: evaluate a proposed tool call. */
17
+ evaluateToolCall(proposal: ToolCallProposal): Promise<PolicyGateResult>;
18
+ /**
19
+ * Fetch policy summaries from the platform for tool description injection.
20
+ * Returns: ["Block PII Exfiltration: Prevents agents from exporting PII", ...]
21
+ */
22
+ fetchPolicySummaries(): Promise<string[]>;
23
+ /** Cedar evaluation with tool-call-specific context. */
24
+ private evaluateToolCedar;
25
+ /** Brain mode: LLM-powered contextual policy evaluation. */
26
+ runBrainAnalysis(proposal: ToolCallProposal, policySummaries: string[], priorChecks: CheckResult[]): Promise<BrainAnalysis>;
27
+ private brainFailOpen;
28
+ }
29
+ //# sourceMappingURL=policyGate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policyGate.d.ts","sourceRoot":"","sources":["../../../lib/sidecar/policyGate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACb,WAAW,EAGZ,MAAM,SAAS,CAAC;AAajB,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAmB;IACjC,OAAO,CAAC,gBAAgB,CAAmB;gBAE/B,MAAM,EAAE,gBAAgB;IAKpC,iDAAiD;IAC3C,gBAAgB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA6D7E;;;OAGG;IACG,oBAAoB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAgC/C,wDAAwD;YAC1C,iBAAiB;IAuD/B,4DAA4D;IACtD,gBAAgB,CACpB,QAAQ,EAAE,gBAAgB,EAC1B,eAAe,EAAE,MAAM,EAAE,EACzB,WAAW,EAAE,WAAW,EAAE,GACzB,OAAO,CAAC,aAAa,CAAC;IAwEzB,OAAO,CAAC,aAAa;CAStB"}
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ /**
3
+ * Policy Gate Evaluator for the Trusera Sidecar v2.
4
+ *
5
+ * Evaluates proposed tool calls against Cedar policies, PII detection,
6
+ * and optional AI-powered "brain mode" analysis.
7
+ *
8
+ * Key difference from SidecarEvaluator: the Cedar action is the TOOL NAME
9
+ * (e.g., "gmail_send_email") not generic "process_data", enabling
10
+ * tool-specific policies.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.PolicyGateEvaluator = void 0;
14
+ const evaluator_1 = require("./evaluator");
15
+ /** Max policy summaries to include in tool description. */
16
+ const MAX_POLICY_SUMMARIES = 8;
17
+ /** Max chars per policy summary. */
18
+ const MAX_SUMMARY_LENGTH = 200;
19
+ /** Max brain input size (chars). */
20
+ const MAX_BRAIN_INPUT = 4000;
21
+ /** Module-level policy summary cache. */
22
+ const policySummaryCache = new Map();
23
+ class PolicyGateEvaluator {
24
+ constructor(config) {
25
+ this.config = config;
26
+ this.sidecarEvaluator = new evaluator_1.SidecarEvaluator(config);
27
+ }
28
+ /** Main entry: evaluate a proposed tool call. */
29
+ async evaluateToolCall(proposal) {
30
+ const startTime = Date.now();
31
+ const checks = [];
32
+ const violations = [];
33
+ // 1. Run PII/injection checks on the tool args (reuse SidecarEvaluator)
34
+ const argsData = typeof proposal.toolArgs === 'string'
35
+ ? { raw: proposal.toolArgs }
36
+ : proposal.toolArgs;
37
+ const baseResult = await this.sidecarEvaluator.evaluate(argsData);
38
+ checks.push(...baseResult.checks.filter((c) => c.name !== 'cedar_policy'));
39
+ violations.push(...baseResult.violations.filter((v) => v.policyName !== 'cedar_policy'));
40
+ // 2. Cedar evaluation with tool-specific context
41
+ const cedarCheck = await this.evaluateToolCedar(proposal, checks);
42
+ checks.push(cedarCheck);
43
+ if (!cedarCheck.passed) {
44
+ violations.push({
45
+ policyName: 'cedar_policy',
46
+ reason: cedarCheck.details,
47
+ severity: 'high',
48
+ });
49
+ }
50
+ // 3. Optional brain mode
51
+ let brainAnalysis;
52
+ if (this.config.brainMode.enabled && this.config.brainApiKey) {
53
+ const summaries = await this.fetchPolicySummaries();
54
+ brainAnalysis = await this.runBrainAnalysis(proposal, summaries, checks);
55
+ checks.push({
56
+ name: 'brain_analysis',
57
+ passed: brainAnalysis.decision !== 'deny',
58
+ details: brainAnalysis.reasoning,
59
+ findings: brainAnalysis.flaggedConcerns,
60
+ });
61
+ if (brainAnalysis.decision === 'deny') {
62
+ violations.push({
63
+ policyName: 'brain_analysis',
64
+ reason: `AI evaluation: ${brainAnalysis.reasoning}`,
65
+ severity: 'high',
66
+ });
67
+ }
68
+ }
69
+ const durationMs = Date.now() - startTime;
70
+ const allowed = violations.length === 0 || this.config.enforcementMode !== 'block';
71
+ const policySummaries = await this.fetchPolicySummaries().catch(() => []);
72
+ return {
73
+ allowed: violations.length === 0 ? true : allowed,
74
+ enforcement: this.config.enforcementMode,
75
+ violations,
76
+ checks,
77
+ timestamp: new Date().toISOString(),
78
+ durationMs,
79
+ proposal,
80
+ brainAnalysis,
81
+ policySummaries,
82
+ };
83
+ }
84
+ /**
85
+ * Fetch policy summaries from the platform for tool description injection.
86
+ * Returns: ["Block PII Exfiltration: Prevents agents from exporting PII", ...]
87
+ */
88
+ async fetchPolicySummaries() {
89
+ const cacheKey = `${this.config.platformUrl}::${this.config.apiKey.slice(0, 8)}`;
90
+ const cached = policySummaryCache.get(cacheKey);
91
+ if (cached && Date.now() - cached.fetchedAt < this.config.policyCacheTtlMs) {
92
+ return cached.summaries;
93
+ }
94
+ try {
95
+ const res = await fetch(`${this.config.platformUrl}/api/v1/cedar/policies`, {
96
+ headers: { Authorization: `Bearer ${this.config.apiKey}` },
97
+ });
98
+ if (!res.ok)
99
+ return cached?.summaries ?? [];
100
+ const data = (await res.json());
101
+ const policies = (data.data ?? []).filter((p) => p.enabled);
102
+ const summaries = policies
103
+ .slice(0, MAX_POLICY_SUMMARIES)
104
+ .map((p) => {
105
+ const desc = p.description.length > MAX_SUMMARY_LENGTH
106
+ ? p.description.slice(0, MAX_SUMMARY_LENGTH) + '...'
107
+ : p.description;
108
+ return `${p.name}: ${desc}`;
109
+ });
110
+ policySummaryCache.set(cacheKey, { summaries, fetchedAt: Date.now() });
111
+ return summaries;
112
+ }
113
+ catch {
114
+ return cached?.summaries ?? [];
115
+ }
116
+ }
117
+ /** Cedar evaluation with tool-call-specific context. */
118
+ async evaluateToolCedar(proposal, priorChecks) {
119
+ try {
120
+ const piiCheck = priorChecks.find((c) => c.name === 'pii_detection');
121
+ const injectionCheck = priorChecks.find((c) => c.name === 'prompt_injection');
122
+ const context = {
123
+ tool_name: proposal.toolName,
124
+ tool_args_keys: Object.keys(proposal.toolArgs),
125
+ pii_detected: piiCheck ? !piiCheck.passed : false,
126
+ pii_types: piiCheck?.findings ?? [],
127
+ injection_detected: injectionCheck ? !injectionCheck.passed : false,
128
+ contains_pii_self_reported: proposal.containsPii,
129
+ data_summary: proposal.dataSummary.slice(0, 500),
130
+ reasoning: proposal.reasoning.slice(0, 500),
131
+ data_size: JSON.stringify(proposal.toolArgs).length,
132
+ };
133
+ const res = await fetch(`${this.config.platformUrl}/api/v1/cedar/evaluate`, {
134
+ method: 'POST',
135
+ headers: {
136
+ 'Content-Type': 'application/json',
137
+ Authorization: `Bearer ${this.config.apiKey}`,
138
+ },
139
+ body: JSON.stringify({
140
+ principal: { type: 'n8n::Agent', id: this.config.agentName },
141
+ action: { type: 'n8n::Action', id: proposal.toolName },
142
+ resource: { type: 'n8n::ToolCall', id: proposal.toolName },
143
+ context,
144
+ }),
145
+ });
146
+ if (!res.ok) {
147
+ return { name: 'cedar_policy', passed: true, details: `Platform returned ${res.status} — failing open` };
148
+ }
149
+ const result = (await res.json());
150
+ const decision = (result.decision ?? 'allow').toLowerCase();
151
+ if (decision === 'deny') {
152
+ const reasons = result.diagnostic?.reasons ?? [`Policy denied tool: ${proposal.toolName}`];
153
+ return { name: 'cedar_policy', passed: false, details: reasons.join('; '), findings: reasons };
154
+ }
155
+ return { name: 'cedar_policy', passed: true, details: 'Cedar policy passed for tool call' };
156
+ }
157
+ catch {
158
+ return { name: 'cedar_policy', passed: true, details: 'Platform unreachable — failing open' };
159
+ }
160
+ }
161
+ /** Brain mode: LLM-powered contextual policy evaluation. */
162
+ async runBrainAnalysis(proposal, policySummaries, priorChecks) {
163
+ const startTime = Date.now();
164
+ try {
165
+ const baseUrl = (this.config.brainBaseUrl ?? 'https://api.openai.com/v1').replace(/\/+$/, '');
166
+ const model = this.config.brainMode.model ?? 'gpt-4o-mini';
167
+ const checksText = priorChecks
168
+ .map((c) => `- ${c.name}: ${c.passed ? 'PASS' : 'FAIL'} — ${c.details}`)
169
+ .join('\n');
170
+ const policiesText = policySummaries.length > 0
171
+ ? policySummaries.map((s, i) => `${i + 1}. ${s}`).join('\n')
172
+ : 'No specific policies configured.';
173
+ const userPrompt = [
174
+ `Tool: ${proposal.toolName}`,
175
+ `Arguments: ${JSON.stringify(proposal.toolArgs).slice(0, MAX_BRAIN_INPUT)}`,
176
+ `Reasoning: ${proposal.reasoning}`,
177
+ `Contains PII (self-reported): ${proposal.containsPii}`,
178
+ `Data summary: ${proposal.dataSummary}`,
179
+ '',
180
+ `Prior automated checks:\n${checksText}`,
181
+ ].join('\n');
182
+ const res = await fetch(`${baseUrl}/chat/completions`, {
183
+ method: 'POST',
184
+ headers: {
185
+ 'Content-Type': 'application/json',
186
+ Authorization: `Bearer ${this.config.brainApiKey}`,
187
+ },
188
+ body: JSON.stringify({
189
+ model,
190
+ max_tokens: this.config.brainMode.maxTokens ?? 300,
191
+ temperature: this.config.brainMode.temperature ?? 0.1,
192
+ response_format: { type: 'json_object' },
193
+ messages: [
194
+ {
195
+ role: 'system',
196
+ content: `You are a security policy evaluator for AI agents. Evaluate whether the proposed action should be allowed based on active policies.\n\nActive policies:\n${policiesText}\n\nRespond with JSON: {"decision":"allow"|"deny"|"warn","reasoning":"...","confidence":0.0-1.0,"flagged_concerns":["..."]}`,
197
+ },
198
+ { role: 'user', content: userPrompt },
199
+ ],
200
+ }),
201
+ });
202
+ if (!res.ok) {
203
+ return this.brainFailOpen(Date.now() - startTime);
204
+ }
205
+ const data = (await res.json());
206
+ const content = data.choices?.[0]?.message?.content ?? '';
207
+ const parsed = JSON.parse(content);
208
+ return {
209
+ decision: parsed.decision ?? 'allow',
210
+ reasoning: parsed.reasoning ?? 'No reasoning provided',
211
+ confidence: parsed.confidence ?? 0.5,
212
+ flaggedConcerns: parsed.flagged_concerns ?? [],
213
+ durationMs: Date.now() - startTime,
214
+ };
215
+ }
216
+ catch {
217
+ return this.brainFailOpen(Date.now() - startTime);
218
+ }
219
+ }
220
+ brainFailOpen(durationMs) {
221
+ return {
222
+ decision: 'allow',
223
+ reasoning: 'Brain mode unavailable — failing open',
224
+ confidence: 0,
225
+ flaggedConcerns: [],
226
+ durationMs,
227
+ };
228
+ }
229
+ }
230
+ exports.PolicyGateEvaluator = PolicyGateEvaluator;
231
+ //# sourceMappingURL=policyGate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policyGate.js","sourceRoot":"","sources":["../../../lib/sidecar/policyGate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAWH,2CAA+C;AAE/C,2DAA2D;AAC3D,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,oCAAoC;AACpC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,oCAAoC;AACpC,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,yCAAyC;AACzC,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAsD,CAAC;AAEzF,MAAa,mBAAmB;IAI9B,YAAY,MAAwB;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,gBAAgB,GAAG,IAAI,4BAAgB,CAAC,MAAM,CAAC,CAAC;IACvD,CAAC;IAED,iDAAiD;IACjD,KAAK,CAAC,gBAAgB,CAAC,QAA0B;QAC/C,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC7B,MAAM,MAAM,GAAkB,EAAE,CAAC;QACjC,MAAM,UAAU,GAAgB,EAAE,CAAC;QAEnC,wEAAwE;QACxE,MAAM,QAAQ,GAAG,OAAO,QAAQ,CAAC,QAAQ,KAAK,QAAQ;YACp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AAQ,EAAG,MAAM,CAAC,QAAsC,IAAI,OAAO;gBACnE,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,uBAAuB;gBACtD,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,GAAG;gBACpC,eAAe,EAAE,MAAM,CAAC,gBAAgB,IAAI,EAAE;gBAC9C,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS;aACnC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,CAAC;QACpD,CAAC;IACH,CAAC;IAEO,aAAa,CAAC,UAAkB;QACtC,OAAO;YACL,QAAQ,EAAE,OAAO;YACjB,SAAS,EAAE,uCAAuC;YAClD,UAAU,EAAE,CAAC;YACb,eAAe,EAAE,EAAE;YACnB,UAAU;SACX,CAAC;IACJ,CAAC;CACF;AAzPD,kDAyPC"}
@@ -6,7 +6,7 @@
6
6
  * processes), this reporter flushes synchronously at the end of node execution
7
7
  * since n8n nodes are short-lived.
8
8
  */
9
- import type { SidecarEvent, EvaluationResult } from './types';
9
+ import type { SidecarEvent, EvaluationResult, PolicyGateResult } from './types';
10
10
  export declare class SidecarReporter {
11
11
  private platformUrl;
12
12
  private apiKey;
@@ -24,5 +24,7 @@ export declare class SidecarReporter {
24
24
  flush(): Promise<void>;
25
25
  /** Create a structured event from an evaluation result. */
26
26
  createEvaluationEvent(result: EvaluationResult, inputData: Record<string, unknown>, nodeName: string, workflowId?: string): SidecarEvent;
27
+ /** Create a structured event from a policy gate (tool-call) result. */
28
+ createToolCallEvent(result: PolicyGateResult, nodeName: string, workflowId?: string): SidecarEvent;
27
29
  }
28
30
  //# sourceMappingURL=reporter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"reporter.d.ts","sourceRoot":"","sources":["../../../lib/sidecar/reporter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAA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B,2DAA2D;IAC3D,qBAAqB,CACnB,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,GAClB,YAAY;IAuCf,uEAAuE;IACvE,mBAAmB,CACjB,MAAM,EAAE,gBAAgB,EACxB,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,GAClB,YAAY;CA+ChB"}
@@ -10,6 +10,7 @@
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.SidecarReporter = void 0;
12
12
  const crypto_1 = require("crypto");
13
+ const types_1 = require("./types");
13
14
  const MAX_QUEUE_SIZE = 10_000;
14
15
  const BATCH_SIZE = 100;
15
16
  const MAX_EVENT_PAYLOAD_SIZE = 10_000; // 10 KB per event payload
@@ -138,6 +139,50 @@ class SidecarReporter {
138
139
  timestamp: result.timestamp,
139
140
  };
140
141
  }
142
+ /** Create a structured event from a policy gate (tool-call) result. */
143
+ createToolCallEvent(result, nodeName, workflowId) {
144
+ const hasViolations = result.violations.length > 0;
145
+ let eventType;
146
+ if (!hasViolations) {
147
+ eventType = types_1.SidecarEventType.TOOL_CALL_APPROVED;
148
+ }
149
+ else if (result.enforcement === 'block') {
150
+ eventType = types_1.SidecarEventType.TOOL_CALL_DENIED;
151
+ }
152
+ else {
153
+ eventType = types_1.SidecarEventType.TOOL_CALL_WARNED;
154
+ }
155
+ const payload = {
156
+ agent_name: this.agentName,
157
+ node_name: nodeName,
158
+ tool_name: result.proposal.toolName,
159
+ decision: hasViolations ? 'deny' : 'allow',
160
+ enforcement_mode: result.enforcement,
161
+ duration_ms: result.durationMs,
162
+ violations_count: result.violations.length,
163
+ violations: result.violations.map((v) => ({ policy: v.policyName, reason: v.reason, severity: v.severity })),
164
+ checks: Object.fromEntries(result.checks.map((c) => [c.name, { passed: c.passed }])),
165
+ };
166
+ if (result.brainAnalysis) {
167
+ payload.brain_analysis = {
168
+ decision: result.brainAnalysis.decision,
169
+ confidence: result.brainAnalysis.confidence,
170
+ reasoning: result.brainAnalysis.reasoning.slice(0, 500),
171
+ };
172
+ }
173
+ if (workflowId)
174
+ payload.workflow_id = workflowId;
175
+ return {
176
+ id: (0, crypto_1.randomUUID)(),
177
+ type: eventType,
178
+ agentName: this.agentName,
179
+ workflowId,
180
+ nodeName,
181
+ payload,
182
+ result: hasViolations ? 'deny' : 'allow',
183
+ timestamp: result.timestamp,
184
+ };
185
+ }
141
186
  }
142
187
  exports.SidecarReporter = SidecarReporter;
143
188
  //# sourceMappingURL=reporter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reporter.js","sourceRoot":"","sources":["../../../lib/sidecar/reporter.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAEH,mCAAoC;AAGpC,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,MAAM,sBAAsB,GAAG,MAAM,CAAC,CAAC,0BAA0B;AAEjE,wFAAwF;AACxF,MAAM,sBAAsB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEzD,MAAa,eAAe;IAM1B,YAAY,WAAmB,EAAE,MAAc,EAAE,SAAiB;QAF1D,eAAU,GAAmB,EAAE,CAAC;QAGtC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,gBAAgB;QACpB,MAAM,QAAQ,GAAG,GAAG,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC;QAC1D,MAAM,MAAM,GAAG,sBAAsB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACpD,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B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,mBAAU,GAAE;YAChB,IAAI,EAAE,SAAS;YACf,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,UAAU;YACV,QAAQ;YACR,OAAO;YACP,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;YACxC,SAAS,EAAE,MAAM,CAAC,SAAS;SAC5B,CAAC;IACJ,CAAC;CACF;AAjMD,0CAiMC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Trusera Tool Interceptor — prompt-injection-proof policy enforcement.
3
+ *
4
+ * Monkey-patches BaseTool.prototype.invoke to intercept ALL tool calls
5
+ * before they execute. This runs at the JavaScript runtime level, so
6
+ * no LLM prompt injection can bypass it.
7
+ *
8
+ * Pattern ported from the Python SDK's TruseraLangChainInterceptor
9
+ * (which patches BaseTool._run).
10
+ */
11
+ import type { PolicyGateEvaluator } from './policyGate';
12
+ import type { SidecarReporter } from './reporter';
13
+ import type { EnforcementMode } from './types';
14
+ export declare class TruseraToolInterceptor {
15
+ private originalInvoke;
16
+ private installed;
17
+ /**
18
+ * Install the monkey-patch on BaseTool.prototype.invoke.
19
+ * After this, ALL tool calls go through policy evaluation before executing.
20
+ */
21
+ install(evaluator: PolicyGateEvaluator, reporter: SidecarReporter, enforcement: EnforcementMode): void;
22
+ /**
23
+ * Install on a specific target object (for testing without @langchain/core).
24
+ * @internal
25
+ */
26
+ _installOnTarget(target: {
27
+ prototype: {
28
+ invoke: Function;
29
+ };
30
+ }, evaluator: PolicyGateEvaluator, reporter: SidecarReporter, enforcement: EnforcementMode): void;
31
+ private _target;
32
+ /** Restore the original BaseTool.prototype.invoke. */
33
+ uninstall(): void;
34
+ /** Whether the interceptor is currently active. */
35
+ isInstalled(): boolean;
36
+ }
37
+ //# sourceMappingURL=toolInterceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolInterceptor.d.ts","sourceRoot":"","sources":["../../../lib/sidecar/toolInterceptor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAoB,MAAM,SAAS,CAAC;AAKjE,qBAAa,sBAAsB;IACjC,OAAO,CAAC,cAAc,CAAyB;IAC/C,OAAO,CAAC,SAAS,CAAS;IAE1B;;;OAGG;IACH,OAAO,CACL,SAAS,EAAE,mBAAmB,EAC9B,QAAQ,EAAE,eAAe,EACzB,WAAW,EAAE,eAAe,GAC3B,IAAI;IAcP;;;OAGG;IACH,gBAAgB,CACd,MAAM,EAAE;QAAE,SAAS,EAAE;YAAE,MAAM,EAAE,QAAQ,CAAA;SAAE,CAAA;KAAE,EAC3C,SAAS,EAAE,mBAAmB,EAC9B,QAAQ,EAAE,eAAe,EACzB,WAAW,EAAE,eAAe,GAC3B,IAAI;IA6DP,OAAO,CAAC,OAAO,CAAa;IAE5B,sDAAsD;IACtD,SAAS,IAAI,IAAI;IAgBjB,mDAAmD;IACnD,WAAW,IAAI,OAAO;CAGvB"}
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ /**
3
+ * Trusera Tool Interceptor — prompt-injection-proof policy enforcement.
4
+ *
5
+ * Monkey-patches BaseTool.prototype.invoke to intercept ALL tool calls
6
+ * before they execute. This runs at the JavaScript runtime level, so
7
+ * no LLM prompt injection can bypass it.
8
+ *
9
+ * Pattern ported from the Python SDK's TruseraLangChainInterceptor
10
+ * (which patches BaseTool._run).
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.TruseraToolInterceptor = void 0;
14
+ /** The name of our own gate tool — skip intercepting it to avoid infinite loops. */
15
+ const GATE_TOOL_NAME = 'trusera_policy_gate';
16
+ class TruseraToolInterceptor {
17
+ constructor() {
18
+ this.originalInvoke = null;
19
+ this.installed = false;
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ this._target = null;
22
+ }
23
+ /**
24
+ * Install the monkey-patch on BaseTool.prototype.invoke.
25
+ * After this, ALL tool calls go through policy evaluation before executing.
26
+ */
27
+ install(evaluator, reporter, enforcement) {
28
+ if (this.installed)
29
+ return;
30
+ let BaseTool;
31
+ try {
32
+ BaseTool = require('@langchain/core/tools').BaseTool;
33
+ }
34
+ catch {
35
+ // @langchain/core not available — skip installation silently
36
+ return;
37
+ }
38
+ this._installOnTarget(BaseTool, evaluator, reporter, enforcement);
39
+ }
40
+ /**
41
+ * Install on a specific target object (for testing without @langchain/core).
42
+ * @internal
43
+ */
44
+ _installOnTarget(target, evaluator, reporter, enforcement) {
45
+ if (this.installed)
46
+ return;
47
+ this._target = target;
48
+ this.originalInvoke = target.prototype.invoke;
49
+ const self = this;
50
+ target.prototype.invoke = async function (input, config) {
51
+ const toolName = this.name ?? 'unknown';
52
+ // Don't intercept our own policy gate tool
53
+ if (toolName === GATE_TOOL_NAME) {
54
+ return self.originalInvoke.call(this, input, config);
55
+ }
56
+ // Build a proposal from the tool call
57
+ const toolArgs = typeof input === 'object' && input !== null
58
+ ? input
59
+ : { raw: String(input) };
60
+ const proposal = {
61
+ toolName,
62
+ toolArgs,
63
+ reasoning: '',
64
+ containsPii: false,
65
+ dataSummary: JSON.stringify(toolArgs).slice(0, 500),
66
+ };
67
+ // Evaluate against policies
68
+ const result = await evaluator.evaluateToolCall(proposal);
69
+ // Report the event (fire-and-forget)
70
+ reporter.track(reporter.createToolCallEvent(result, 'TruseraInterceptor'));
71
+ reporter.flush().catch(() => { });
72
+ // Enforce
73
+ if (result.violations.length > 0) {
74
+ const reasons = result.violations.map((v) => v.reason).join('; ');
75
+ if (enforcement === 'block') {
76
+ throw new Error(`[Trusera] BLOCKED: ${toolName} — ${reasons}`);
77
+ }
78
+ if (enforcement === 'warn') {
79
+ console.warn(`[Trusera] WARNING on ${toolName}: ${reasons}`);
80
+ }
81
+ // log mode: continue silently
82
+ }
83
+ // Call the original invoke
84
+ return self.originalInvoke.call(this, input, config);
85
+ };
86
+ this.installed = true;
87
+ }
88
+ /** Restore the original BaseTool.prototype.invoke. */
89
+ uninstall() {
90
+ if (!this.installed || !this.originalInvoke)
91
+ return;
92
+ const target = this._target ?? (() => {
93
+ try {
94
+ return require('@langchain/core/tools').BaseTool;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ })();
100
+ if (target) {
101
+ target.prototype.invoke = this.originalInvoke;
102
+ }
103
+ this.originalInvoke = null;
104
+ this._target = null;
105
+ this.installed = false;
106
+ }
107
+ /** Whether the interceptor is currently active. */
108
+ isInstalled() {
109
+ return this.installed;
110
+ }
111
+ }
112
+ exports.TruseraToolInterceptor = TruseraToolInterceptor;
113
+ //# sourceMappingURL=toolInterceptor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolInterceptor.js","sourceRoot":"","sources":["../../../lib/sidecar/toolInterceptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAMH,oFAAoF;AACpF,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAE7C,MAAa,sBAAsB;IAAnC;QACU,mBAAc,GAAoB,IAAI,CAAC;QACvC,cAAS,GAAG,KAAK,CAAC;QA6F1B,8DAA8D;QACtD,YAAO,GAAQ,IAAI,CAAC;IAuB9B,CAAC;IAnHC;;;OAGG;IACH,OAAO,CACL,SAA8B,EAC9B,QAAyB,EACzB,WAA4B;QAE5B,IAAI,IAAI,CAAC,SAAS;YAAE,OAAO;QAE3B,IAAI,QAAa,CAAC;QAClB,IAAI,CAAC;YACH,QAAQ,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC,QAAQ,CAAC;QACvD,CAAC;QAAC,MAAM,CAAC;YACP,6DAA6D;YAC7D,OAAO;QACT,CAAC;QAED,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;IACpE,CAAC;IAED;;;OAGG;IACH,gBAAgB,CACd,MAA2C,EAC3C,SAA8B,EA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,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;IAED,mDAAmD;IACnD,WAAW;QACT,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CACF;AAvHD,wDAuHC"}
@@ -36,7 +36,10 @@ export declare enum SidecarEventType {
36
36
  CONTENT_FILTERED = "content_filtered",
37
37
  PROMPT_INJECTION = "prompt_injection",
38
38
  WORKFLOW_BLOCKED = "workflow_blocked",
39
- TOOL_VALIDATION = "tool_validation"
39
+ TOOL_VALIDATION = "tool_validation",
40
+ TOOL_CALL_APPROVED = "tool_call_approved",
41
+ TOOL_CALL_DENIED = "tool_call_denied",
42
+ TOOL_CALL_WARNED = "tool_call_warned"
40
43
  }
41
44
  /** A single event sent to the platform via /api/v1/events/batch. */
42
45
  export interface SidecarEvent {
@@ -71,4 +74,39 @@ export interface EvaluatorConfig {
71
74
  inlineCedarDsl?: string;
72
75
  policyCacheTtlMs: number;
73
76
  }
77
+ /** A proposed tool call submitted to the policy gate. */
78
+ export interface ToolCallProposal {
79
+ toolName: string;
80
+ toolArgs: Record<string, unknown>;
81
+ reasoning: string;
82
+ containsPii: boolean;
83
+ dataSummary: string;
84
+ }
85
+ /** Result of a policy gate evaluation. */
86
+ export interface PolicyGateResult extends EvaluationResult {
87
+ proposal: ToolCallProposal;
88
+ brainAnalysis?: BrainAnalysis;
89
+ policySummaries: string[];
90
+ }
91
+ /** Result from the AI-powered brain mode evaluation. */
92
+ export interface BrainAnalysis {
93
+ decision: 'allow' | 'deny' | 'warn';
94
+ reasoning: string;
95
+ confidence: number;
96
+ flaggedConcerns: string[];
97
+ durationMs: number;
98
+ }
99
+ /** Configuration for brain mode. */
100
+ export interface BrainModeConfig {
101
+ enabled: boolean;
102
+ model?: string;
103
+ maxTokens?: number;
104
+ temperature?: number;
105
+ }
106
+ /** Extended evaluator config for the policy gate. */
107
+ export interface PolicyGateConfig extends EvaluatorConfig {
108
+ brainMode: BrainModeConfig;
109
+ brainApiKey?: string;
110
+ brainBaseUrl?: string;
111
+ }
74
112
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../lib/sidecar/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,2EAA2E;AAC3E,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAEvD,yCAAyC;AACzC,MAAM,MAAM,YAAY,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEjD,6CAA6C;AAC7C,MAAM,MAAM,iBAAiB,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEvE,iCAAiC;AACjC,MAAM,WAAW,SAAS;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,iBAAiB,CAAC;CAC7B;AAED,mEAAmE;AACnE,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,6DAA6D;AAC7D,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,eAAe,CAAC;IAC7B,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,oDAAoD;AACpD,oBAAY,gBAAgB;IAC1B,iBAAiB,sBAAsB;IACvC,YAAY,iBAAiB;IAC7B,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,gBAAgB,qBAAqB;IACrC,eAAe,oBAAoB;CACpC;AAED,oEAAoE;AACpE,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,gBAAgB,CAAC;IACv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,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,qDAAqD;AACrD,MAAM,WAAW,gBAAiB,SAAQ,eAAe;IACvD,SAAS,EAAE,eAAe,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB"}
@@ -13,5 +13,8 @@ var SidecarEventType;
13
13
  SidecarEventType["PROMPT_INJECTION"] = "prompt_injection";
14
14
  SidecarEventType["WORKFLOW_BLOCKED"] = "workflow_blocked";
15
15
  SidecarEventType["TOOL_VALIDATION"] = "tool_validation";
16
+ SidecarEventType["TOOL_CALL_APPROVED"] = "tool_call_approved";
17
+ SidecarEventType["TOOL_CALL_DENIED"] = "tool_call_denied";
18
+ SidecarEventType["TOOL_CALL_WARNED"] = "tool_call_warned";
16
19
  })(SidecarEventType || (exports.SidecarEventType = SidecarEventType = {}));
17
20
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/sidecar/types.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAoCH,oDAAoD;AACpD,IAAY,gBAOX;AAPD,WAAY,gBAAgB;IAC1B,2DAAuC,CAAA;IACvC,iDAA6B,CAAA;IAC7B,yDAAqC,CAAA;IACrC,yDAAqC,CAAA;IACrC,yDAAqC,CAAA;IACrC,uDAAmC,CAAA;AACrC,CAAC,EAPW,gBAAgB,gCAAhB,gBAAgB,QAO3B"}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/sidecar/types.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAoCH,oDAAoD;AACpD,IAAY,gBAUX;AAVD,WAAY,gBAAgB;IAC1B,2DAAuC,CAAA;IACvC,iDAA6B,CAAA;IAC7B,yDAAqC,CAAA;IACrC,yDAAqC,CAAA;IACrC,yDAAqC,CAAA;IACrC,uDAAmC,CAAA;IACnC,6DAAyC,CAAA;IACzC,yDAAqC,CAAA;IACrC,yDAAqC,CAAA;AACvC,CAAC,EAVW,gBAAgB,gCAAhB,gBAAgB,QAU3B"}
@@ -1 +1 @@
1
- {"version":3,"file":"TruseraSidecarTool.node.d.ts","sourceRoot":"","sources":["../../../nodes/TruseraSidecarTool/TruseraSidecarTool.node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,oBAAoB,EACpB,oBAAoB,EACpB,UAAU,EACX,MAAM,cAAc,CAAC;AAOtB,qBAAa,kBAAmB,YAAW,SAAS;IAClD,WAAW,EAAE,oBAAoB,CA0F/B;IAEI,UAAU,CACd,IAAI,EAAE,oBAAoB,EAC1B,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,UAAU,CAAC;CAwGvB"}
1
+ {"version":3,"file":"TruseraSidecarTool.node.d.ts","sourceRoot":"","sources":["../../../nodes/TruseraSidecarTool/TruseraSidecarTool.node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,oBAAoB,EACpB,oBAAoB,EACpB,UAAU,EACX,MAAM,cAAc,CAAC;AAQtB,qBAAa,kBAAmB,YAAW,SAAS;IAClD,WAAW,EAAE,oBAAoB,CAgH/B;IAEI,UAAU,CACd,IAAI,EAAE,oBAAoB,EAC1B,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,UAAU,CAAC;CAuKvB"}
@@ -2,7 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TruseraSidecarTool = void 0;
4
4
  const n8n_workflow_1 = require("n8n-workflow");
5
- const evaluator_1 = require("../../lib/sidecar/evaluator");
5
+ const policyGate_1 = require("../../lib/sidecar/policyGate");
6
+ const toolInterceptor_1 = require("../../lib/sidecar/toolInterceptor");
6
7
  const reporter_1 = require("../../lib/sidecar/reporter");
7
8
  class TruseraSidecarTool {
8
9
  constructor() {
@@ -12,8 +13,8 @@ class TruseraSidecarTool {
12
13
  icon: 'file:trusera.png',
13
14
  group: ['transform'],
14
15
  version: 1,
15
- subtitle: 'AI Agent Security Tool',
16
- description: 'Tool for AI Agents to validate actions against Trusera security policies before executing them',
16
+ subtitle: 'AI Agent Policy Gate',
17
+ description: 'Intercepts ALL agent tool calls and enforces Cedar policies from the Trusera platform. Prompt-injection proof.',
17
18
  defaults: {
18
19
  name: 'Trusera Sidecar Tool',
19
20
  },
@@ -39,9 +40,9 @@ class TruseraSidecarTool {
39
40
  name: 'enforcementMode',
40
41
  type: 'options',
41
42
  options: [
42
- { name: 'Log Only', value: 'log', description: 'Always return info, never throw' },
43
- { name: 'Warn', value: 'warn', description: 'Return info with warning, never throw' },
44
- { name: 'Block', value: 'block', description: 'Throw error on violation (stops agent)' },
43
+ { name: 'Log Only', value: 'log', description: 'Record all tool calls, never block' },
44
+ { name: 'Warn', value: 'warn', description: 'Log warnings but allow tool calls' },
45
+ { name: 'Block', value: 'block', description: 'Block tool calls that violate policies (stops agent)' },
45
46
  ],
46
47
  default: 'warn',
47
48
  description: 'What happens when a policy violation is detected',
@@ -68,29 +69,53 @@ class TruseraSidecarTool {
68
69
  policySource: ['inline'],
69
70
  },
70
71
  },
71
- description: 'Cedar policy DSL to evaluate',
72
+ description: 'Cedar policy DSL to evaluate against tool calls',
72
73
  },
73
74
  {
74
75
  displayName: 'Enable PII Detection',
75
76
  name: 'enablePiiDetection',
76
77
  type: 'boolean',
77
78
  default: true,
78
- description: 'Whether to scan for personally identifiable information',
79
+ description: 'Whether to scan tool arguments for personally identifiable information',
79
80
  },
80
81
  {
81
82
  displayName: 'Enable Prompt Injection Detection',
82
83
  name: 'enablePromptInjection',
83
84
  type: 'boolean',
84
85
  default: true,
85
- description: 'Whether to detect prompt injection patterns',
86
+ description: 'Whether to detect prompt injection patterns in tool arguments',
86
87
  },
87
88
  {
88
- displayName: 'Tool Description',
89
- name: 'toolDescription',
89
+ displayName: 'Enable Brain Mode',
90
+ name: 'enableBrainMode',
91
+ type: 'boolean',
92
+ default: false,
93
+ description: 'Whether to use an LLM to evaluate complex policies contextually',
94
+ },
95
+ {
96
+ displayName: 'Brain Mode API Key',
97
+ name: 'brainApiKey',
98
+ type: 'string',
99
+ typeOptions: { password: true },
100
+ default: '',
101
+ displayOptions: { show: { enableBrainMode: [true] } },
102
+ description: 'API key for the LLM used in brain mode (OpenAI-compatible)',
103
+ },
104
+ {
105
+ displayName: 'Brain Mode Base URL',
106
+ name: 'brainBaseUrl',
90
107
  type: 'string',
91
- typeOptions: { rows: 3 },
92
- default: 'Check if an action or text complies with security policies. Use this before performing sensitive operations, sending data externally, or when handling user input.',
93
- description: 'Description the AI agent sees — controls when the agent decides to call this tool',
108
+ default: 'https://api.openai.com/v1',
109
+ displayOptions: { show: { enableBrainMode: [true] } },
110
+ description: 'Base URL for the brain mode LLM API',
111
+ },
112
+ {
113
+ displayName: 'Brain Mode Model',
114
+ name: 'brainModel',
115
+ type: 'string',
116
+ default: 'gpt-4o-mini',
117
+ displayOptions: { show: { enableBrainMode: [true] } },
118
+ description: 'Model to use for AI-powered policy evaluation',
94
119
  },
95
120
  ],
96
121
  };
@@ -103,9 +128,13 @@ class TruseraSidecarTool {
103
128
  const inlineCedarDsl = this.getNodeParameter('inlineCedarDsl', itemIndex, '');
104
129
  const enablePiiDetection = this.getNodeParameter('enablePiiDetection', itemIndex, true);
105
130
  const enablePromptInjection = this.getNodeParameter('enablePromptInjection', itemIndex, true);
106
- const toolDescription = this.getNodeParameter('toolDescription', itemIndex, 'Check if an action or text complies with security policies.');
107
- const evaluator = new evaluator_1.SidecarEvaluator({
108
- platformUrl: credentials.platformUrl,
131
+ const enableBrainMode = this.getNodeParameter('enableBrainMode', itemIndex, false);
132
+ const brainApiKey = this.getNodeParameter('brainApiKey', itemIndex, '');
133
+ const brainBaseUrl = this.getNodeParameter('brainBaseUrl', itemIndex, 'https://api.openai.com/v1');
134
+ const brainModel = this.getNodeParameter('brainModel', itemIndex, 'gpt-4o-mini');
135
+ const platformUrl = credentials.platformUrl.replace(/\/+$/, '');
136
+ const gateEvaluator = new policyGate_1.PolicyGateEvaluator({
137
+ platformUrl,
109
138
  apiKey: credentials.apiKey,
110
139
  enforcementMode,
111
140
  policySource,
@@ -115,10 +144,36 @@ class TruseraSidecarTool {
115
144
  enableContentFilter: false,
116
145
  inlineCedarDsl,
117
146
  policyCacheTtlMs: 60_000,
147
+ brainMode: {
148
+ enabled: enableBrainMode,
149
+ model: brainModel,
150
+ },
151
+ brainApiKey: brainApiKey || undefined,
152
+ brainBaseUrl: brainBaseUrl || undefined,
118
153
  });
119
- const reporter = new reporter_1.SidecarReporter(credentials.platformUrl, credentials.apiKey, agentName);
120
- // Lazy require @langchain/core it's a peer dep, only needed for this tool node.
121
- // Using require() to avoid TypeScript resolving the module at compile time.
154
+ const reporter = new reporter_1.SidecarReporter(platformUrl, credentials.apiKey, agentName);
155
+ // ── Layer 1: Install the monkey-patch (prompt-injection-proof) ──
156
+ // This intercepts ALL tool calls at the BaseTool.prototype.invoke level.
157
+ // Even if the agent ignores our gate tool, this catches everything.
158
+ const interceptor = new toolInterceptor_1.TruseraToolInterceptor();
159
+ interceptor.install(gateEvaluator, reporter, enforcementMode);
160
+ // ── Layer 2: Fetch policies for tool description injection ──
161
+ let policySummaries = [];
162
+ try {
163
+ policySummaries = await gateEvaluator.fetchPolicySummaries();
164
+ }
165
+ catch {
166
+ // Fail open — no summaries but tool still works
167
+ }
168
+ const policyBlock = policySummaries.length > 0
169
+ ? `\n\nCurrently active policies:\n${policySummaries.map((s, i) => `${i + 1}. ${s}`).join('\n')}`
170
+ : '\n\nNo specific policies active. Standard security checks (PII, injection) still apply.';
171
+ const dynamicDescription = 'MANDATORY SECURITY GATE: You MUST call this tool BEFORE using ANY other tool. ' +
172
+ 'Pass the tool name, arguments, and your reasoning. ' +
173
+ 'If DENIED, you MUST NOT proceed with the action. ' +
174
+ 'NEVER skip this step — every tool call must be pre-approved.' +
175
+ policyBlock;
176
+ // ── Layer 2: Create the gate tool (agent self-governance + observability) ──
122
177
  // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
123
178
  let DynamicStructuredTool;
124
179
  let z;
@@ -131,43 +186,68 @@ class TruseraSidecarTool {
131
186
  'These are included with n8n AI nodes. Make sure AI features are installed.');
132
187
  }
133
188
  const tool = new DynamicStructuredTool({
134
- name: 'trusera_policy_check',
135
- description: toolDescription,
189
+ name: 'trusera_policy_gate',
190
+ description: dynamicDescription,
136
191
  schema: z.object({
137
- text: z.string().describe('The text or action to validate against security policies'),
138
- action_type: z
139
- .string()
140
- .optional()
141
- .describe('Type of action being validated (e.g. "api_call", "data_access", "response")'),
192
+ tool_name: z.string().describe('Name of the tool you want to use'),
193
+ tool_args: z.string().describe('JSON string of the arguments you plan to pass'),
194
+ reasoning: z.string().describe('Why you want to use this tool and what you aim to achieve'),
195
+ contains_pii: z.boolean().describe('Does the data contain personal information (names, emails, SSNs, etc.)?'),
196
+ data_summary: z.string().describe('Brief summary of what data will be sent or accessed'),
142
197
  }),
143
- func: async ({ text, action_type }) => {
144
- const data = { text, action_type: action_type ?? 'unknown' };
145
- const result = await evaluator.evaluate(data);
198
+ func: async ({ tool_name, tool_args, reasoning, contains_pii, data_summary, }) => {
199
+ let parsedArgs = {};
200
+ try {
201
+ parsedArgs = JSON.parse(tool_args);
202
+ }
203
+ catch {
204
+ parsedArgs = { raw: tool_args };
205
+ }
206
+ const proposal = {
207
+ toolName: tool_name,
208
+ toolArgs: parsedArgs,
209
+ reasoning,
210
+ containsPii: contains_pii,
211
+ dataSummary: data_summary,
212
+ };
213
+ const result = await gateEvaluator.evaluateToolCall(proposal);
146
214
  // Report event
147
- reporter.track(reporter.createEvaluationEvent(result, data, 'TruseraSidecarTool'));
215
+ reporter.track(reporter.createToolCallEvent(result, 'TruseraSidecarTool'));
148
216
  try {
149
217
  await reporter.flush();
150
218
  }
151
219
  catch {
152
220
  // fire and forget
153
221
  }
222
+ // No violations — approved
154
223
  if (result.violations.length === 0) {
155
224
  return JSON.stringify({
156
- decision: 'allow',
157
- message: 'Action complies with security policies.',
225
+ decision: 'approved',
226
+ message: `Approved. Proceed with ${proposal.toolName}.`,
158
227
  checks: result.checks.map((c) => ({ name: c.name, passed: c.passed })),
228
+ ...(result.brainAnalysis
229
+ ? { brain: { decision: result.brainAnalysis.decision, reasoning: result.brainAnalysis.reasoning } }
230
+ : {}),
159
231
  });
160
232
  }
161
- const violationResponse = {
162
- decision: 'deny',
163
- message: `Policy violation: ${result.violations.map((v) => v.reason).join('; ')}`,
164
- violations: result.violations,
165
- recommendation: 'Do not proceed with this action. Modify the content to comply with policies.',
166
- };
233
+ // Has violations
234
+ const violationSummary = result.violations.map((v) => v.reason).join('; ');
167
235
  if (enforcementMode === 'block') {
168
- throw new Error(`[Trusera] Policy violation — action blocked: ${result.violations.map((v) => v.reason).join('; ')}`);
236
+ throw new Error(`[Trusera Policy Gate] BLOCKED: ${tool_name} ${violationSummary}`);
237
+ }
238
+ if (enforcementMode === 'warn') {
239
+ return JSON.stringify({
240
+ decision: 'warning',
241
+ message: `WARNING: ${violationSummary}. Do NOT proceed with this action.`,
242
+ violations: result.violations,
243
+ });
169
244
  }
170
- return JSON.stringify(violationResponse);
245
+ // Log mode — allow with findings
246
+ return JSON.stringify({
247
+ decision: 'approved_with_findings',
248
+ message: `Approved (findings logged): ${violationSummary}`,
249
+ violations: result.violations,
250
+ });
171
251
  },
172
252
  });
173
253
  return { response: tool };
@@ -1 +1 @@
1
- {"version":3,"file":"TruseraSidecarTool.node.js","sourceRoot":"","sources":["../../../nodes/TruseraSidecarTool/TruseraSidecarTool.node.ts"],"names":[],"mappings":";;;AAMA,+CAAmD;AAEnD,2DAA+D;AAC/D,yDAA6D;AAG7D,MAAa,kBAAkB;IAA/B;QACE,gBAAW,GAAyB;YAClC,WAAW,EAAE,sBAAsB;YACnC,IAAI,EAAE,oBAAoB;YAC1B,IAAI,EAAE,kBAAkB;YACxB,KAAK,EAAE,CAAC,WAAW,CAAC;YACpB,OAAO,EAAE,CAAC;YACV,QAAQ,EAAE,wBAAwB;YAClC,WAAW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I,eAAe,KAAK,OAAO,EAAE,CAAC;oBAChC,MAAM,IAAI,KAAK,CACb,gDAAgD,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACpG,CAAC;gBACJ,CAAC;gBAED,OAAO,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC;YAC3C,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;CACF;AAxMD,gDAwMC"}
1
+ {"version":3,"file":"TruseraSidecarTool.node.js","sourceRoot":"","sources":["../../../nodes/TruseraSidecarTool/TruseraSidecarTool.node.ts"],"names":[],"mappings":";;;AAMA,+CAAmD;AAEnD,6DAAmE;AACnE,uEAA2E;AAC3E,yDAA6D;AAG7D,MAAa,kBAAkB;IAA/B;QACE,gBAAW,GAAyB;YAClC,WAAW,EAAE,sBAAsB;YACnC,IAAI,EAAE,oBAAoB;YAC1B,IAAI,EAAE,kBAAkB;YACxB,KAAK,EAAE,CAAC,WAAW,CAAC;YACpB,OAAO,EAAE,CAAC;YACV,QAAQ,EAAE,sBAAsB;YAChC,WAAW,EACT,gHAAgH;YAClH,QAAQ,EAAE;gBACR,IAAI,EAAE,sBAAsB;aAC7B;YACD,MAAM,EAAE,EAAE;YACV,OAAO,EAAE,CAAC,kCAAmB,CAAC,MAAM,CAAC;YACrC,WAAW,EAAE;gBACX;oBACE,IAAI,EAAE,oBAAoB;oBAC1B,QAAQ,EAAE,IAAI;iBACf;aACF;YACD,UAAU,EAAE;gBACV;oBACE,WAAW,EAAE,YAAY;oBACzB,IAAI,EAAE,WAAW;oBACjB,IAAI,EAAE,QAAQ;oBACd,OAAO,EAAE,EAAE;oBACX,QAAQ,EAAE,IAAI;oBACd,WAAW,EAAE,6CAA6C;iBAC3D;gBACD;oBACE,WAAW,EAAE,kBAAkB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,IAAI,CAAC,SAAS,CAAC;oBACpB,QAAQ,EAAE,wBAAwB;oBAClC,OAAO,EAAE,+BAA+B,gBAAgB,EAAE;oBAC1D,UAAU,EAAE,MAAM,CAAC,UAAU;iBAC9B,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;CACF;AA7RD,gDA6RC"}
@@ -6,9 +6,10 @@ import type {
6
6
  } from 'n8n-workflow';
7
7
  import { NodeConnectionTypes } from 'n8n-workflow';
8
8
 
9
- import { SidecarEvaluator } from '../../lib/sidecar/evaluator';
9
+ import { PolicyGateEvaluator } from '../../lib/sidecar/policyGate';
10
+ import { TruseraToolInterceptor } from '../../lib/sidecar/toolInterceptor';
10
11
  import { SidecarReporter } from '../../lib/sidecar/reporter';
11
- import type { EnforcementMode, PolicySource } from '../../lib/sidecar/types';
12
+ import type { EnforcementMode, PolicySource, ToolCallProposal } from '../../lib/sidecar/types';
12
13
 
13
14
  export class TruseraSidecarTool implements INodeType {
14
15
  description: INodeTypeDescription = {
@@ -17,9 +18,9 @@ export class TruseraSidecarTool implements INodeType {
17
18
  icon: 'file:trusera.png',
18
19
  group: ['transform'],
19
20
  version: 1,
20
- subtitle: 'AI Agent Security Tool',
21
+ subtitle: 'AI Agent Policy Gate',
21
22
  description:
22
- 'Tool for AI Agents to validate actions against Trusera security policies before executing them',
23
+ 'Intercepts ALL agent tool calls and enforces Cedar policies from the Trusera platform. Prompt-injection proof.',
23
24
  defaults: {
24
25
  name: 'Trusera Sidecar Tool',
25
26
  },
@@ -45,9 +46,9 @@ export class TruseraSidecarTool implements INodeType {
45
46
  name: 'enforcementMode',
46
47
  type: 'options',
47
48
  options: [
48
- { name: 'Log Only', value: 'log', description: 'Always return info, never throw' },
49
- { name: 'Warn', value: 'warn', description: 'Return info with warning, never throw' },
50
- { name: 'Block', value: 'block', description: 'Throw error on violation (stops agent)' },
49
+ { name: 'Log Only', value: 'log', description: 'Record all tool calls, never block' },
50
+ { name: 'Warn', value: 'warn', description: 'Log warnings but allow tool calls' },
51
+ { name: 'Block', value: 'block', description: 'Block tool calls that violate policies (stops agent)' },
51
52
  ],
52
53
  default: 'warn',
53
54
  description: 'What happens when a policy violation is detected',
@@ -74,31 +75,53 @@ export class TruseraSidecarTool implements INodeType {
74
75
  policySource: ['inline'],
75
76
  },
76
77
  },
77
- description: 'Cedar policy DSL to evaluate',
78
+ description: 'Cedar policy DSL to evaluate against tool calls',
78
79
  },
79
80
  {
80
81
  displayName: 'Enable PII Detection',
81
82
  name: 'enablePiiDetection',
82
83
  type: 'boolean',
83
84
  default: true,
84
- description: 'Whether to scan for personally identifiable information',
85
+ description: 'Whether to scan tool arguments for personally identifiable information',
85
86
  },
86
87
  {
87
88
  displayName: 'Enable Prompt Injection Detection',
88
89
  name: 'enablePromptInjection',
89
90
  type: 'boolean',
90
91
  default: true,
91
- description: 'Whether to detect prompt injection patterns',
92
+ description: 'Whether to detect prompt injection patterns in tool arguments',
92
93
  },
93
94
  {
94
- displayName: 'Tool Description',
95
- name: 'toolDescription',
95
+ displayName: 'Enable Brain Mode',
96
+ name: 'enableBrainMode',
97
+ type: 'boolean',
98
+ default: false,
99
+ description: 'Whether to use an LLM to evaluate complex policies contextually',
100
+ },
101
+ {
102
+ displayName: 'Brain Mode API Key',
103
+ name: 'brainApiKey',
96
104
  type: 'string',
97
- typeOptions: { rows: 3 },
98
- default:
99
- 'Check if an action or text complies with security policies. Use this before performing sensitive operations, sending data externally, or when handling user input.',
100
- description:
101
- 'Description the AI agent sees — controls when the agent decides to call this tool',
105
+ typeOptions: { password: true },
106
+ default: '',
107
+ displayOptions: { show: { enableBrainMode: [true] } },
108
+ description: 'API key for the LLM used in brain mode (OpenAI-compatible)',
109
+ },
110
+ {
111
+ displayName: 'Brain Mode Base URL',
112
+ name: 'brainBaseUrl',
113
+ type: 'string',
114
+ default: 'https://api.openai.com/v1',
115
+ displayOptions: { show: { enableBrainMode: [true] } },
116
+ description: 'Base URL for the brain mode LLM API',
117
+ },
118
+ {
119
+ displayName: 'Brain Mode Model',
120
+ name: 'brainModel',
121
+ type: 'string',
122
+ default: 'gpt-4o-mini',
123
+ displayOptions: { show: { enableBrainMode: [true] } },
124
+ description: 'Model to use for AI-powered policy evaluation',
102
125
  },
103
126
  ],
104
127
  };
@@ -118,14 +141,15 @@ export class TruseraSidecarTool implements INodeType {
118
141
  const inlineCedarDsl = this.getNodeParameter('inlineCedarDsl', itemIndex, '') as string;
119
142
  const enablePiiDetection = this.getNodeParameter('enablePiiDetection', itemIndex, true) as boolean;
120
143
  const enablePromptInjection = this.getNodeParameter('enablePromptInjection', itemIndex, true) as boolean;
121
- const toolDescription = this.getNodeParameter(
122
- 'toolDescription',
123
- itemIndex,
124
- 'Check if an action or text complies with security policies.',
125
- ) as string;
126
-
127
- const evaluator = new SidecarEvaluator({
128
- platformUrl: credentials.platformUrl,
144
+ const enableBrainMode = this.getNodeParameter('enableBrainMode', itemIndex, false) as boolean;
145
+ const brainApiKey = this.getNodeParameter('brainApiKey', itemIndex, '') as string;
146
+ const brainBaseUrl = this.getNodeParameter('brainBaseUrl', itemIndex, 'https://api.openai.com/v1') as string;
147
+ const brainModel = this.getNodeParameter('brainModel', itemIndex, 'gpt-4o-mini') as string;
148
+
149
+ const platformUrl = credentials.platformUrl.replace(/\/+$/, '');
150
+
151
+ const gateEvaluator = new PolicyGateEvaluator({
152
+ platformUrl,
129
153
  apiKey: credentials.apiKey,
130
154
  enforcementMode,
131
155
  policySource,
@@ -135,16 +159,42 @@ export class TruseraSidecarTool implements INodeType {
135
159
  enableContentFilter: false,
136
160
  inlineCedarDsl,
137
161
  policyCacheTtlMs: 60_000,
162
+ brainMode: {
163
+ enabled: enableBrainMode,
164
+ model: brainModel,
165
+ },
166
+ brainApiKey: brainApiKey || undefined,
167
+ brainBaseUrl: brainBaseUrl || undefined,
138
168
  });
139
169
 
140
- const reporter = new SidecarReporter(
141
- credentials.platformUrl,
142
- credentials.apiKey,
143
- agentName,
144
- );
170
+ const reporter = new SidecarReporter(platformUrl, credentials.apiKey, agentName);
171
+
172
+ // ── Layer 1: Install the monkey-patch (prompt-injection-proof) ──
173
+ // This intercepts ALL tool calls at the BaseTool.prototype.invoke level.
174
+ // Even if the agent ignores our gate tool, this catches everything.
175
+ const interceptor = new TruseraToolInterceptor();
176
+ interceptor.install(gateEvaluator, reporter, enforcementMode);
177
+
178
+ // ── Layer 2: Fetch policies for tool description injection ──
179
+ let policySummaries: string[] = [];
180
+ try {
181
+ policySummaries = await gateEvaluator.fetchPolicySummaries();
182
+ } catch {
183
+ // Fail open — no summaries but tool still works
184
+ }
185
+
186
+ const policyBlock = policySummaries.length > 0
187
+ ? `\n\nCurrently active policies:\n${policySummaries.map((s, i) => `${i + 1}. ${s}`).join('\n')}`
188
+ : '\n\nNo specific policies active. Standard security checks (PII, injection) still apply.';
145
189
 
146
- // Lazy require @langchain/core — it's a peer dep, only needed for this tool node.
147
- // Using require() to avoid TypeScript resolving the module at compile time.
190
+ const dynamicDescription =
191
+ 'MANDATORY SECURITY GATE: You MUST call this tool BEFORE using ANY other tool. ' +
192
+ 'Pass the tool name, arguments, and your reasoning. ' +
193
+ 'If DENIED, you MUST NOT proceed with the action. ' +
194
+ 'NEVER skip this step — every tool call must be pre-approved.' +
195
+ policyBlock;
196
+
197
+ // ── Layer 2: Create the gate tool (agent self-governance + observability) ──
148
198
  // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
149
199
  let DynamicStructuredTool: any;
150
200
  let z: any;
@@ -159,52 +209,88 @@ export class TruseraSidecarTool implements INodeType {
159
209
  }
160
210
 
161
211
  const tool = new DynamicStructuredTool({
162
- name: 'trusera_policy_check',
163
- description: toolDescription,
212
+ name: 'trusera_policy_gate',
213
+ description: dynamicDescription,
164
214
  schema: z.object({
165
- text: z.string().describe('The text or action to validate against security policies'),
166
- action_type: z
167
- .string()
168
- .optional()
169
- .describe('Type of action being validated (e.g. "api_call", "data_access", "response")'),
215
+ tool_name: z.string().describe('Name of the tool you want to use'),
216
+ tool_args: z.string().describe('JSON string of the arguments you plan to pass'),
217
+ reasoning: z.string().describe('Why you want to use this tool and what you aim to achieve'),
218
+ contains_pii: z.boolean().describe('Does the data contain personal information (names, emails, SSNs, etc.)?'),
219
+ data_summary: z.string().describe('Brief summary of what data will be sent or accessed'),
170
220
  }),
171
- func: async ({ text, action_type }: { text: string; action_type?: string }) => {
172
- const data = { text, action_type: action_type ?? 'unknown' };
173
- const result = await evaluator.evaluate(data);
221
+ func: async ({
222
+ tool_name,
223
+ tool_args,
224
+ reasoning,
225
+ contains_pii,
226
+ data_summary,
227
+ }: {
228
+ tool_name: string;
229
+ tool_args: string;
230
+ reasoning: string;
231
+ contains_pii: boolean;
232
+ data_summary: string;
233
+ }) => {
234
+ let parsedArgs: Record<string, unknown> = {};
235
+ try {
236
+ parsedArgs = JSON.parse(tool_args);
237
+ } catch {
238
+ parsedArgs = { raw: tool_args };
239
+ }
240
+
241
+ const proposal: ToolCallProposal = {
242
+ toolName: tool_name,
243
+ toolArgs: parsedArgs,
244
+ reasoning,
245
+ containsPii: contains_pii,
246
+ dataSummary: data_summary,
247
+ };
248
+
249
+ const result = await gateEvaluator.evaluateToolCall(proposal);
174
250
 
175
251
  // Report event
176
- reporter.track(
177
- reporter.createEvaluationEvent(result, data, 'TruseraSidecarTool'),
178
- );
252
+ reporter.track(reporter.createToolCallEvent(result, 'TruseraSidecarTool'));
179
253
  try {
180
254
  await reporter.flush();
181
255
  } catch {
182
256
  // fire and forget
183
257
  }
184
258
 
259
+ // No violations — approved
185
260
  if (result.violations.length === 0) {
186
261
  return JSON.stringify({
187
- decision: 'allow',
188
- message: 'Action complies with security policies.',
262
+ decision: 'approved',
263
+ message: `Approved. Proceed with ${proposal.toolName}.`,
189
264
  checks: result.checks.map((c) => ({ name: c.name, passed: c.passed })),
265
+ ...(result.brainAnalysis
266
+ ? { brain: { decision: result.brainAnalysis.decision, reasoning: result.brainAnalysis.reasoning } }
267
+ : {}),
190
268
  });
191
269
  }
192
270
 
193
- const violationResponse = {
194
- decision: 'deny',
195
- message: `Policy violation: ${result.violations.map((v) => v.reason).join('; ')}`,
196
- violations: result.violations,
197
- recommendation:
198
- 'Do not proceed with this action. Modify the content to comply with policies.',
199
- };
271
+ // Has violations
272
+ const violationSummary = result.violations.map((v) => v.reason).join('; ');
200
273
 
201
274
  if (enforcementMode === 'block') {
202
275
  throw new Error(
203
- `[Trusera] Policy violation — action blocked: ${result.violations.map((v) => v.reason).join('; ')}`,
276
+ `[Trusera Policy Gate] BLOCKED: ${tool_name} ${violationSummary}`,
204
277
  );
205
278
  }
206
279
 
207
- return JSON.stringify(violationResponse);
280
+ if (enforcementMode === 'warn') {
281
+ return JSON.stringify({
282
+ decision: 'warning',
283
+ message: `WARNING: ${violationSummary}. Do NOT proceed with this action.`,
284
+ violations: result.violations,
285
+ });
286
+ }
287
+
288
+ // Log mode — allow with findings
289
+ return JSON.stringify({
290
+ decision: 'approved_with_findings',
291
+ message: `Approved (findings logged): ${violationSummary}`,
292
+ violations: result.violations,
293
+ });
208
294
  },
209
295
  });
210
296
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-nodes-trusera",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "n8n community node for AI security: static scanning + runtime policy enforcement via Trusera",
5
5
  "keywords": [
6
6
  "n8n-community-node-package",