nexus-agents 2.90.0 → 2.92.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.
Files changed (28) hide show
  1. package/dist/{chunk-EUR32RSL.js → chunk-HPV2D4HN.js} +7 -5
  2. package/dist/{chunk-EUR32RSL.js.map → chunk-HPV2D4HN.js.map} +1 -1
  3. package/dist/{chunk-L3S7HOAS.js → chunk-L6JZCAFH.js} +146 -620
  4. package/dist/chunk-L6JZCAFH.js.map +1 -0
  5. package/dist/{chunk-IBRZK662.js → chunk-LOBVTRQQ.js} +3 -3
  6. package/dist/chunk-NR4NSTJH.js +547 -0
  7. package/dist/chunk-NR4NSTJH.js.map +1 -0
  8. package/dist/{chunk-3RZWLQSC.js → chunk-RS6RGSYG.js} +31 -2
  9. package/dist/chunk-RS6RGSYG.js.map +1 -0
  10. package/dist/{chunk-X2M7OF27.js → chunk-S4UF577T.js} +3 -1
  11. package/dist/chunk-S4UF577T.js.map +1 -0
  12. package/dist/{chunk-3NNVITJF.js → chunk-VW2LBC7B.js} +2 -2
  13. package/dist/cli.js +58 -18
  14. package/dist/cli.js.map +1 -1
  15. package/dist/index.js +19 -17
  16. package/dist/index.js.map +1 -1
  17. package/dist/{issue-triage-J2MUXK6R.js → issue-triage-FVZOVIRX.js} +3 -2
  18. package/dist/{pr-reviewer-helpers-WYPUYQ2U.js → pr-reviewer-helpers-7D2W5HTO.js} +10 -3
  19. package/dist/{setup-command-Z7TRZUDI.js → setup-command-UN3XDJ2H.js} +3 -3
  20. package/package.json +1 -1
  21. package/dist/chunk-3RZWLQSC.js.map +0 -1
  22. package/dist/chunk-L3S7HOAS.js.map +0 -1
  23. package/dist/chunk-X2M7OF27.js.map +0 -1
  24. /package/dist/{chunk-IBRZK662.js.map → chunk-LOBVTRQQ.js.map} +0 -0
  25. /package/dist/{chunk-3NNVITJF.js.map → chunk-VW2LBC7B.js.map} +0 -0
  26. /package/dist/{issue-triage-J2MUXK6R.js.map → issue-triage-FVZOVIRX.js.map} +0 -0
  27. /package/dist/{pr-reviewer-helpers-WYPUYQ2U.js.map → pr-reviewer-helpers-7D2W5HTO.js.map} +0 -0
  28. /package/dist/{setup-command-Z7TRZUDI.js.map → setup-command-UN3XDJ2H.js.map} +0 -0
@@ -0,0 +1,547 @@
1
+ import {
2
+ CACHE_TIMEOUTS,
3
+ getTimeProvider
4
+ } from "./chunk-W5I6L4UT.js";
5
+
6
+ // src/security/trust-types.ts
7
+ import { z } from "zod";
8
+ var TrustTierSchema = z.enum(["1", "2", "3", "4"]);
9
+ var TRUST_TIER_NUMERIC = {
10
+ "1": 1,
11
+ "2": 2,
12
+ "3": 3,
13
+ "4": 4
14
+ };
15
+ var GitHubUserRoleSchema = z.enum([
16
+ "owner",
17
+ "maintainer",
18
+ "collaborator",
19
+ "contributor",
20
+ "member",
21
+ "unknown"
22
+ ]);
23
+ var ROLE_DEFAULT_TRUST = {
24
+ owner: "1",
25
+ maintainer: "1",
26
+ collaborator: "2",
27
+ contributor: "2",
28
+ member: "3",
29
+ unknown: "3"
30
+ };
31
+ var InjectionFlagSchema = z.enum([
32
+ "authority_claim",
33
+ "instruction_pattern",
34
+ "system_prompt_manipulation",
35
+ "hidden_content",
36
+ "urgency_manipulation",
37
+ "fake_conversation",
38
+ "base64_encoded",
39
+ "external_link_instruction"
40
+ ]);
41
+ var StrippedElementSchema = z.object({
42
+ /** Type of element stripped. */
43
+ tag: z.string().min(1),
44
+ /** Reason for stripping. */
45
+ reason: z.string().min(1),
46
+ /** Start index in original content. */
47
+ startIndex: z.number().int().nonnegative(),
48
+ /** Length of stripped content. */
49
+ length: z.number().int().positive()
50
+ });
51
+ var SanitizedInputSchema = z.object({
52
+ /** Sanitized content with dangerous elements removed. */
53
+ content: z.string(),
54
+ /** Original content before sanitization (for audit). */
55
+ originalLength: z.number().int().nonnegative(),
56
+ /** Assigned trust tier based on user role and content analysis. */
57
+ trustTier: TrustTierSchema,
58
+ /** GitHub user role of the input source. */
59
+ userRole: GitHubUserRoleSchema,
60
+ /** Injection patterns detected in content. */
61
+ injectionFlags: z.array(InjectionFlagSchema),
62
+ /** Elements stripped during sanitization (audit trail). */
63
+ strippedElements: z.array(StrippedElementSchema),
64
+ /** Whether any dangerous content was detected and stripped. */
65
+ wasModified: z.boolean(),
66
+ /** Timestamp of sanitization (ISO 8601). */
67
+ sanitizedAt: z.iso.datetime()
68
+ });
69
+ var SanitizerConfigSchema = z.object({
70
+ /** GitHub usernames that are always Tier 1 (allowlisted maintainers). */
71
+ allowlistedMaintainers: z.array(z.string().min(1)).default([]),
72
+ /** Whether to fail open (log only) or fail closed (block). Phase 1 = open. */
73
+ failOpen: z.boolean().default(true),
74
+ /** Maximum input length before truncation. */
75
+ maxInputLength: z.number().int().positive().default(5e4)
76
+ });
77
+
78
+ // src/security/input-sanitizer.ts
79
+ var DANGEROUS_HTML_PATTERN = /<(picture|source|img)\b[^>]*>[\s\S]*?<\/\1>|<(picture|source|img)\b[^>]*\/?>/gi;
80
+ var XML_INJECTION_PATTERN = /<\/?(system|human|assistant|instructions|user|prompt|context|tool_use|tool_result)\b[^>]*>/gi;
81
+ var HTML_COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
82
+ var INJECTION_PATTERNS = [
83
+ {
84
+ flag: "authority_claim",
85
+ pattern: /\b(as (?:a|the) (?:maintainer|admin|owner|security lead|repo owner|developer))\b/i
86
+ },
87
+ {
88
+ flag: "authority_claim",
89
+ pattern: /\b(i(?:'m| am) the (?:repo |project )?(?:owner|maintainer|admin))\b/i
90
+ },
91
+ {
92
+ flag: "instruction_pattern",
93
+ pattern: /\b(please (?:close|merge|label|mark|apply|delete|remove|approve|reject))\b/i
94
+ },
95
+ {
96
+ flag: "instruction_pattern",
97
+ pattern: /\b(you (?:should|must|need to) (?:close|merge|label|apply|delete))\b/i
98
+ },
99
+ {
100
+ flag: "system_prompt_manipulation",
101
+ pattern: /\b(ignore (?:all )?previous (?:instructions|rules|prompts))\b/i
102
+ },
103
+ {
104
+ flag: "system_prompt_manipulation",
105
+ pattern: /\b(forget (?:your |all )?(?:instructions|rules|safety))\b/i
106
+ },
107
+ {
108
+ flag: "system_prompt_manipulation",
109
+ pattern: /\b(new (?:instructions|rules|system prompt|directives))\b/i
110
+ },
111
+ {
112
+ flag: "urgency_manipulation",
113
+ pattern: /\b(critical|emergency|urgent|must act now|immediately|time[- ]?sensitive)\b/i
114
+ },
115
+ {
116
+ flag: "fake_conversation",
117
+ pattern: /<(?:assistant|human|user|system)>/i
118
+ },
119
+ // base64_encoded is detected separately by `looksLikeBase64Payload` below.
120
+ // The lookahead-based regex it replaced exhibited catastrophic backtracking
121
+ // on long hex-only inputs (#2191) — see `looksLikeBase64Payload` for the
122
+ // two-phase rewrite that preserves the #1811 SHA-hash false-positive guard.
123
+ {
124
+ flag: "external_link_instruction",
125
+ pattern: /(?:apply|run|execute|install)\s+(?:this\s+)?(?:from\s+)?https?:\/\//i
126
+ }
127
+ ];
128
+ var BASE64_RUN_GLOBAL = /[A-Za-z0-9+/]{40,}={0,2}/g;
129
+ var BASE64_DISCRIMINATOR = /[g-zG-Z+/=]/;
130
+ function looksLikeBase64Payload(content) {
131
+ for (const match of content.matchAll(BASE64_RUN_GLOBAL)) {
132
+ if (BASE64_DISCRIMINATOR.test(match[0])) return true;
133
+ }
134
+ return false;
135
+ }
136
+ var DANGEROUS_TAG_NAMES = "picture|source|img|system|human|assistant|instructions|user|prompt|context|tool_use|tool_result";
137
+ var ENCODED_DANGEROUS_TAG_PATTERN = new RegExp(
138
+ `&(?:lt|#0*60|#x0*3c);\\s*\\/?\\s*(?:${DANGEROUS_TAG_NAMES})\\b`,
139
+ "i"
140
+ );
141
+ function decodeEntities(content) {
142
+ return content.replace(/&#(\d+);/g, (_match, dec) => {
143
+ const code = Number.parseInt(dec, 10);
144
+ return Number.isFinite(code) ? String.fromCodePoint(code) : _match;
145
+ }).replace(/&#x([0-9a-f]+);/gi, (_match, hex) => {
146
+ const code = Number.parseInt(hex, 16);
147
+ return Number.isFinite(code) ? String.fromCodePoint(code) : _match;
148
+ }).replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&apos;/gi, "'").replace(/&amp;/gi, "&");
149
+ }
150
+ function applyEntityEvasionDefense(content) {
151
+ if (!ENCODED_DANGEROUS_TAG_PATTERN.test(content)) {
152
+ return { cleaned: content, stripped: [] };
153
+ }
154
+ const decoded = decodeEntities(content);
155
+ return {
156
+ cleaned: decoded,
157
+ stripped: [
158
+ {
159
+ tag: "&\u2026;",
160
+ reason: "HTML entity-encoded dangerous tag decoded for stripping (CWE-79)",
161
+ startIndex: 0,
162
+ length: content.length
163
+ }
164
+ ]
165
+ };
166
+ }
167
+ function stripDangerousHtml(content) {
168
+ const stripped = [];
169
+ let cleaned = content;
170
+ const MAX_PASSES = 5;
171
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
172
+ DANGEROUS_HTML_PATTERN.lastIndex = 0;
173
+ if (!DANGEROUS_HTML_PATTERN.test(cleaned)) break;
174
+ cleaned = cleaned.replace(DANGEROUS_HTML_PATTERN, (match, _g1, _g2, offset) => {
175
+ stripped.push({
176
+ tag: match.slice(0, 30) + (match.length > 30 ? "..." : ""),
177
+ reason: "Dangerous HTML tag (Trail of Bits injection vector)",
178
+ startIndex: offset,
179
+ length: match.length
180
+ });
181
+ return "";
182
+ });
183
+ }
184
+ return { cleaned, stripped };
185
+ }
186
+ function stripXmlTags(content) {
187
+ const stripped = [];
188
+ let cleaned = content;
189
+ const MAX_PASSES = 5;
190
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
191
+ XML_INJECTION_PATTERN.lastIndex = 0;
192
+ if (!XML_INJECTION_PATTERN.test(cleaned)) break;
193
+ cleaned = cleaned.replace(XML_INJECTION_PATTERN, (match, _g1, offset) => {
194
+ stripped.push({
195
+ tag: match,
196
+ reason: "XML-like conversation injection tag",
197
+ startIndex: offset,
198
+ length: match.length
199
+ });
200
+ return "";
201
+ });
202
+ }
203
+ return { cleaned, stripped };
204
+ }
205
+ function stripHtmlComments(content) {
206
+ const stripped = [];
207
+ let cleaned = content;
208
+ const MAX_PASSES = 5;
209
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
210
+ HTML_COMMENT_PATTERN.lastIndex = 0;
211
+ const prevLength = cleaned.length;
212
+ cleaned = cleaned.replace(HTML_COMMENT_PATTERN, (match, offset) => {
213
+ const hasInstruction = /\b(ignore|execute|close|merge|delete|apply)\b/i.test(match);
214
+ if (!hasInstruction) return match;
215
+ stripped.push({
216
+ tag: "<!-- ... -->",
217
+ reason: "HTML comment with instruction-like content",
218
+ startIndex: offset,
219
+ length: match.length
220
+ });
221
+ return "";
222
+ });
223
+ if (cleaned.length === prevLength) break;
224
+ }
225
+ let searchFrom = 0;
226
+ while (searchFrom < cleaned.length) {
227
+ const openIdx = cleaned.indexOf("<!--", searchFrom);
228
+ if (openIdx === -1) break;
229
+ const closeIdx = cleaned.indexOf("-->", openIdx + 4);
230
+ if (closeIdx === -1) {
231
+ stripped.push({
232
+ tag: "<!--",
233
+ reason: "Unclosed HTML comment (potential injection vector)",
234
+ startIndex: openIdx,
235
+ length: cleaned.length - openIdx
236
+ });
237
+ cleaned = cleaned.slice(0, openIdx);
238
+ break;
239
+ }
240
+ searchFrom = closeIdx + 3;
241
+ }
242
+ return { cleaned, stripped };
243
+ }
244
+ function detectInjectionPatterns(content) {
245
+ const flags = /* @__PURE__ */ new Set();
246
+ for (const { flag, pattern } of INJECTION_PATTERNS) {
247
+ pattern.lastIndex = 0;
248
+ if (pattern.test(content)) {
249
+ flags.add(flag);
250
+ }
251
+ }
252
+ if (looksLikeBase64Payload(content)) {
253
+ flags.add("base64_encoded");
254
+ }
255
+ return Array.from(flags);
256
+ }
257
+ function normalizeRole(userRole) {
258
+ const lower = userRole.toLowerCase();
259
+ if (lower in ROLE_DEFAULT_TRUST) return lower;
260
+ return "unknown";
261
+ }
262
+ function assignTrustTier(userRole, injectionFlags, allowlisted) {
263
+ if (allowlisted) return "1";
264
+ const normalizedRole = normalizeRole(userRole);
265
+ const baseTier = ROLE_DEFAULT_TRUST[normalizedRole];
266
+ const hostileFlags = ["system_prompt_manipulation", "fake_conversation"];
267
+ if (injectionFlags.some((f) => hostileFlags.includes(f))) return "4";
268
+ if (injectionFlags.includes("authority_claim") && normalizedRole !== "owner" && normalizedRole !== "maintainer") {
269
+ return "4";
270
+ }
271
+ return baseTier;
272
+ }
273
+ function sanitizeInput(content, userRole, username, config) {
274
+ const cfg = SanitizerConfigSchema.parse(config ?? {});
275
+ const truncated = content.slice(0, cfg.maxInputLength);
276
+ const allowlisted = cfg.allowlistedMaintainers.includes(username);
277
+ try {
278
+ const entityDecoded = applyEntityEvasionDefense(truncated);
279
+ const html = stripDangerousHtml(entityDecoded.cleaned);
280
+ const xml = stripXmlTags(html.cleaned);
281
+ const comments = stripHtmlComments(xml.cleaned);
282
+ const allStripped = [
283
+ ...entityDecoded.stripped,
284
+ ...html.stripped,
285
+ ...xml.stripped,
286
+ ...comments.stripped
287
+ ];
288
+ const injectionFlags = detectInjectionPatterns(truncated);
289
+ const trustTier = assignTrustTier(userRole, injectionFlags, allowlisted);
290
+ return {
291
+ content: comments.cleaned,
292
+ originalLength: content.length,
293
+ trustTier,
294
+ userRole,
295
+ injectionFlags,
296
+ strippedElements: allStripped,
297
+ wasModified: allStripped.length > 0,
298
+ sanitizedAt: (/* @__PURE__ */ new Date()).toISOString()
299
+ };
300
+ } catch (err) {
301
+ return buildFailClosedResult(err, content, truncated, userRole, allowlisted);
302
+ }
303
+ }
304
+ function buildFailClosedResult(err, originalContent, truncated, userRole, allowlisted) {
305
+ const message = err instanceof Error ? err.message : String(err);
306
+ return {
307
+ content: "",
308
+ originalLength: originalContent.length,
309
+ trustTier: allowlisted ? "1" : "4",
310
+ userRole,
311
+ injectionFlags: [],
312
+ strippedElements: [
313
+ {
314
+ tag: "(pipeline-failure)",
315
+ reason: `Sanitizer pipeline threw; input discarded as fail-closed: ${message}`,
316
+ startIndex: 0,
317
+ length: truncated.length
318
+ }
319
+ ],
320
+ wasModified: true,
321
+ sanitizedAt: (/* @__PURE__ */ new Date()).toISOString()
322
+ };
323
+ }
324
+
325
+ // src/security/reputation-model.ts
326
+ import { z as z2 } from "zod";
327
+ var SuspiciousSignalSchema = z2.enum([
328
+ "new_account",
329
+ "no_prior_contributions",
330
+ "injection_patterns_detected",
331
+ "rapid_comments",
332
+ "mismatched_authority_claim"
333
+ ]);
334
+ var DAYS_PER_YEAR_APPROX = 36.5;
335
+ var SUSPICIOUS_THRESHOLDS = {
336
+ /** Account younger than this (days) is flagged. */
337
+ newAccountDays: 30,
338
+ /** Fewer contributions than this is flagged. */
339
+ minContributions: 1,
340
+ /** More comments than this in the window triggers rapid-comment flag. */
341
+ rapidCommentThreshold: 5,
342
+ /** Time window (minutes) for rapid comment detection. */
343
+ rapidCommentWindowMinutes: 10
344
+ };
345
+ var DEFAULT_TTL_MS = CACHE_TIMEOUTS.reputationTtlMs;
346
+ var DEFAULT_MAX_SIZE = 1e3;
347
+ var ReputationCache = class {
348
+ cache = /* @__PURE__ */ new Map();
349
+ ttlMs;
350
+ maxSize;
351
+ constructor(ttlMs = DEFAULT_TTL_MS, maxSize = DEFAULT_MAX_SIZE) {
352
+ this.ttlMs = ttlMs;
353
+ this.maxSize = maxSize;
354
+ }
355
+ get(username) {
356
+ const entry = this.cache.get(username);
357
+ if (entry === void 0) return void 0;
358
+ if (getTimeProvider().now() > entry.expiresAt) {
359
+ this.cache.delete(username);
360
+ return void 0;
361
+ }
362
+ return entry.assessment;
363
+ }
364
+ set(username, assessment) {
365
+ if (this.cache.size >= this.maxSize && !this.cache.has(username)) {
366
+ this.evictOldest();
367
+ }
368
+ this.cache.set(username, {
369
+ assessment,
370
+ expiresAt: getTimeProvider().now() + this.ttlMs
371
+ });
372
+ }
373
+ /** Evict a batch of oldest entries (10% of maxSize, minimum 1). */
374
+ evictOldest() {
375
+ const batchSize = Math.max(1, Math.floor(this.maxSize * 0.1));
376
+ const keys = this.cache.keys();
377
+ for (let i = 0; i < batchSize; i++) {
378
+ const next = keys.next();
379
+ if (next.done === true) break;
380
+ this.cache.delete(next.value);
381
+ }
382
+ }
383
+ clear() {
384
+ this.cache.clear();
385
+ }
386
+ get size() {
387
+ return this.cache.size;
388
+ }
389
+ };
390
+ var HOSTILE_INJECTION_FLAGS = [
391
+ "system_prompt_manipulation",
392
+ "fake_conversation",
393
+ "authority_claim",
394
+ "hidden_content"
395
+ ];
396
+ function hasHostileInjection(flags) {
397
+ return flags.some((f) => HOSTILE_INJECTION_FLAGS.includes(f));
398
+ }
399
+ function isRapidCommenting(m) {
400
+ return m.recentCommentCount !== void 0 && m.recentCommentWindowMinutes !== void 0 && m.recentCommentCount > SUSPICIOUS_THRESHOLDS.rapidCommentThreshold && m.recentCommentWindowMinutes <= SUSPICIOUS_THRESHOLDS.rapidCommentWindowMinutes;
401
+ }
402
+ function isMismatchedAuthority(m) {
403
+ if (!m.injectionFlags.includes("authority_claim")) return false;
404
+ const association = m.authorAssociation.toUpperCase();
405
+ return association !== "OWNER" && association !== "MEMBER";
406
+ }
407
+ function detectSuspiciousSignals(metadata) {
408
+ const signals = [];
409
+ const { accountAgeDays, priorContributions } = metadata;
410
+ if (accountAgeDays !== void 0 && accountAgeDays < SUSPICIOUS_THRESHOLDS.newAccountDays) {
411
+ signals.push("new_account");
412
+ }
413
+ if (priorContributions !== void 0 && priorContributions < SUSPICIOUS_THRESHOLDS.minContributions) {
414
+ signals.push("no_prior_contributions");
415
+ }
416
+ if (hasHostileInjection(metadata.injectionFlags)) signals.push("injection_patterns_detected");
417
+ if (isRapidCommenting(metadata)) signals.push("rapid_comments");
418
+ if (isMismatchedAuthority(metadata)) signals.push("mismatched_authority_claim");
419
+ return signals;
420
+ }
421
+ function calculateReputationScore(metadata, signals, userRole) {
422
+ let score = 50;
423
+ const roleBonus = {
424
+ owner: 40,
425
+ maintainer: 35,
426
+ collaborator: 25,
427
+ contributor: 15,
428
+ member: 5,
429
+ unknown: 0
430
+ };
431
+ score += roleBonus[userRole];
432
+ if (metadata.accountAgeDays !== void 0) {
433
+ score += Math.min(metadata.accountAgeDays / DAYS_PER_YEAR_APPROX, 10);
434
+ }
435
+ if (metadata.priorContributions !== void 0) {
436
+ score += Math.min(metadata.priorContributions, 10);
437
+ }
438
+ const signalPenalty = {
439
+ new_account: -15,
440
+ no_prior_contributions: -10,
441
+ injection_patterns_detected: -25,
442
+ rapid_comments: -20,
443
+ mismatched_authority_claim: -30
444
+ };
445
+ for (const signal of signals) {
446
+ score += signalPenalty[signal];
447
+ }
448
+ return Math.max(0, Math.min(100, Math.round(score)));
449
+ }
450
+ function mapRole(association) {
451
+ switch (association.toUpperCase()) {
452
+ case "OWNER":
453
+ return "owner";
454
+ case "MEMBER":
455
+ return "member";
456
+ case "COLLABORATOR":
457
+ return "collaborator";
458
+ case "CONTRIBUTOR":
459
+ return "contributor";
460
+ default:
461
+ return "unknown";
462
+ }
463
+ }
464
+ function determineEffectiveTier(userRole, signals) {
465
+ const baseTier = ROLE_DEFAULT_TRUST[userRole];
466
+ const hostileSignals = [
467
+ "injection_patterns_detected",
468
+ "mismatched_authority_claim"
469
+ ];
470
+ if (signals.some((s) => hostileSignals.includes(s))) return "4";
471
+ if (signals.length >= 2) {
472
+ const baseNumeric = TRUST_TIER_NUMERIC[baseTier];
473
+ const downgraded = Math.min(baseNumeric + 1, 4);
474
+ return String(downgraded);
475
+ }
476
+ return baseTier;
477
+ }
478
+ function assessReputation(metadata, cache) {
479
+ const cached = cache?.get(metadata.username);
480
+ if (cached !== void 0) return cached;
481
+ const userRole = mapRole(metadata.authorAssociation);
482
+ const signals = detectSuspiciousSignals(metadata);
483
+ const score = calculateReputationScore(metadata, signals, userRole);
484
+ const effectiveTier = determineEffectiveTier(userRole, signals);
485
+ const assessment = {
486
+ username: metadata.username,
487
+ userRole,
488
+ suspiciousSignals: signals,
489
+ isSuspicious: signals.length > 0,
490
+ effectiveTrustTier: effectiveTier,
491
+ reputationScore: score,
492
+ reason: buildReason(userRole, signals, effectiveTier),
493
+ assessedAt: (/* @__PURE__ */ new Date()).toISOString()
494
+ };
495
+ cache?.set(metadata.username, assessment);
496
+ return assessment;
497
+ }
498
+ function reconcileTrustTier(classifierTier, reputation) {
499
+ if (classifierTier === "1") return "1";
500
+ const repTier = reputation?.effectiveTrustTier;
501
+ if (repTier === void 0) return classifierTier;
502
+ return TRUST_TIER_NUMERIC[repTier] > TRUST_TIER_NUMERIC[classifierTier] ? repTier : classifierTier;
503
+ }
504
+ var ReputationGatingModeSchema = z2.enum(["off", "audit", "enforce"]);
505
+ var DEFAULT_REPUTATION_GATING_MODE = "audit";
506
+ function resolveReputationGatingMode(env = process.env) {
507
+ const raw = env["NEXUS_REPUTATION_GATING"];
508
+ if (typeof raw !== "string" || raw.length === 0) return DEFAULT_REPUTATION_GATING_MODE;
509
+ const parsed = ReputationGatingModeSchema.safeParse(raw.toLowerCase());
510
+ return parsed.success ? parsed.data : DEFAULT_REPUTATION_GATING_MODE;
511
+ }
512
+ function gateWithReputation(classifierTier, reputation, mode) {
513
+ const reconciledTier = mode === "off" ? classifierTier : reconcileTrustTier(classifierTier, reputation);
514
+ const enforcedTier = mode === "enforce" ? reconciledTier : classifierTier;
515
+ return {
516
+ enforcedTier,
517
+ reconciledTier,
518
+ demotionSuppressed: mode !== "enforce" && reconciledTier !== classifierTier,
519
+ mode
520
+ };
521
+ }
522
+ function buildReason(role, signals, tier) {
523
+ if (signals.length === 0) {
524
+ return `Role ${role} \u2192 Tier ${tier} (no suspicious signals)`;
525
+ }
526
+ const signalList = signals.join(", ");
527
+ return `Role ${role} \u2192 Tier ${tier} (signals: ${signalList})`;
528
+ }
529
+
530
+ export {
531
+ TrustTierSchema,
532
+ TRUST_TIER_NUMERIC,
533
+ GitHubUserRoleSchema,
534
+ ROLE_DEFAULT_TRUST,
535
+ InjectionFlagSchema,
536
+ StrippedElementSchema,
537
+ SanitizedInputSchema,
538
+ SanitizerConfigSchema,
539
+ sanitizeInput,
540
+ SuspiciousSignalSchema,
541
+ ReputationCache,
542
+ assessReputation,
543
+ reconcileTrustTier,
544
+ resolveReputationGatingMode,
545
+ gateWithReputation
546
+ };
547
+ //# sourceMappingURL=chunk-NR4NSTJH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/trust-types.ts","../src/security/input-sanitizer.ts","../src/security/reputation-model.ts"],"sourcesContent":["/**\n * nexus-agents/security - Trust Types\n *\n * Zod schemas and TypeScript types for the untrusted input hardening\n * framework. Defines trust tiers, sanitized input, user roles, and\n * injection detection flags.\n *\n * @module security/trust-types\n * (Source: Issue #818, #819 — Phase 1: Input Sanitization)\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Trust Tiers\n// ============================================================================\n\n/**\n * Trust tier classification for input sources.\n * Lower number = higher trust.\n *\n * 1 = Authoritative (repo files, CI, CLAUDE.md, allowlisted maintainers)\n * 2 = Semi-trusted (collaborator issue body, contributor PR metadata)\n * 3 = Untrusted (unknown user comments, non-collaborator issue body)\n * 4 = Hostile (injection patterns, hidden HTML, instruction-like content)\n */\nexport const TrustTierSchema = z.enum(['1', '2', '3', '4']);\nexport type TrustTier = z.infer<typeof TrustTierSchema>;\n\n/** Numeric trust tier for comparisons. Higher number = lower trust. */\nexport const TRUST_TIER_NUMERIC: Record<TrustTier, number> = {\n '1': 1,\n '2': 2,\n '3': 3,\n '4': 4,\n};\n\n// ============================================================================\n// GitHub User Roles\n// ============================================================================\n\n/**\n * GitHub user relationship to the repository.\n */\nexport const GitHubUserRoleSchema = z.enum([\n 'owner',\n 'maintainer',\n 'collaborator',\n 'contributor',\n 'member',\n 'unknown',\n]);\nexport type GitHubUserRole = z.infer<typeof GitHubUserRoleSchema>;\n\n/**\n * Default trust tier mapping for each GitHub role.\n * Can be overridden by injection pattern detection (downgrade only).\n */\nexport const ROLE_DEFAULT_TRUST: Record<GitHubUserRole, TrustTier> = {\n owner: '1',\n maintainer: '1',\n collaborator: '2',\n contributor: '2',\n member: '3',\n unknown: '3',\n};\n\n// ============================================================================\n// Injection Detection\n// ============================================================================\n\n/**\n * Categories of injection patterns detected in content.\n */\nexport const InjectionFlagSchema = z.enum([\n 'authority_claim',\n 'instruction_pattern',\n 'system_prompt_manipulation',\n 'hidden_content',\n 'urgency_manipulation',\n 'fake_conversation',\n 'base64_encoded',\n 'external_link_instruction',\n]);\nexport type InjectionFlag = z.infer<typeof InjectionFlagSchema>;\n\n/**\n * An element stripped during sanitization, preserved for audit trail.\n */\nexport const StrippedElementSchema = z.object({\n /** Type of element stripped. */\n tag: z.string().min(1),\n /** Reason for stripping. */\n reason: z.string().min(1),\n /** Start index in original content. */\n startIndex: z.number().int().nonnegative(),\n /** Length of stripped content. */\n length: z.number().int().positive(),\n});\nexport type StrippedElement = z.infer<typeof StrippedElementSchema>;\n\n// ============================================================================\n// Sanitized Input\n// ============================================================================\n\n/**\n * The result of sanitizing untrusted input.\n * Contains cleaned content, trust classification, and audit data.\n */\nexport const SanitizedInputSchema = z.object({\n /** Sanitized content with dangerous elements removed. */\n content: z.string(),\n /** Original content before sanitization (for audit). */\n originalLength: z.number().int().nonnegative(),\n /** Assigned trust tier based on user role and content analysis. */\n trustTier: TrustTierSchema,\n /** GitHub user role of the input source. */\n userRole: GitHubUserRoleSchema,\n /** Injection patterns detected in content. */\n injectionFlags: z.array(InjectionFlagSchema),\n /** Elements stripped during sanitization (audit trail). */\n strippedElements: z.array(StrippedElementSchema),\n /** Whether any dangerous content was detected and stripped. */\n wasModified: z.boolean(),\n /** Timestamp of sanitization (ISO 8601). */\n sanitizedAt: z.iso.datetime(),\n});\nexport type SanitizedInput = z.infer<typeof SanitizedInputSchema>;\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for the input sanitizer.\n */\nexport const SanitizerConfigSchema = z.object({\n /** GitHub usernames that are always Tier 1 (allowlisted maintainers). */\n allowlistedMaintainers: z.array(z.string().min(1)).default([]),\n /** Whether to fail open (log only) or fail closed (block). Phase 1 = open. */\n failOpen: z.boolean().default(true),\n /** Maximum input length before truncation. */\n maxInputLength: z.number().int().positive().default(50_000),\n});\nexport type SanitizerConfig = z.infer<typeof SanitizerConfigSchema>;\n","/**\n * nexus-agents/security - Input Sanitizer\n *\n * Sanitizes untrusted GitHub input by stripping dangerous HTML/XML tags,\n * detecting injection patterns, and producing a SanitizedInput result\n * with full audit trail.\n *\n * Defense layer 1 of the three-layer hardening architecture.\n * See: docs/architecture/UNTRUSTED_INPUT_HARDENING.md\n *\n * @module security/input-sanitizer\n * (Source: Issue #818, #819 — Phase 1: Input Sanitization)\n */\n\nimport type {\n InjectionFlag,\n SanitizedInput,\n SanitizerConfig,\n StrippedElement,\n TrustTier,\n GitHubUserRole,\n} from './trust-types.js';\nimport { ROLE_DEFAULT_TRUST, SanitizerConfigSchema } from './trust-types.js';\n\n// ============================================================================\n// Dangerous HTML Patterns (Trail of Bits / GitHub Copilot vectors)\n// ============================================================================\n\n/**\n * HTML tags to strip. These are known injection vectors:\n * - `<picture>` / `<source>`: Trail of Bits GitHub Copilot injection\n * - `<img>`: Can carry injection via alt text or onerror\n */\nconst DANGEROUS_HTML_PATTERN =\n /<(picture|source|img)\\b[^>]*>[\\s\\S]*?<\\/\\1>|<(picture|source|img)\\b[^>]*\\/?>/gi;\n\n// ============================================================================\n// XML-like Tags (Conversation History Injection)\n// ============================================================================\n\n/**\n * XML-like tags that mimic conversation structure or system prompts.\n */\nconst XML_INJECTION_PATTERN =\n /<\\/?(system|human|assistant|instructions|user|prompt|context|tool_use|tool_result)\\b[^>]*>/gi;\n\n// ============================================================================\n// HTML Comments with Instructions\n// ============================================================================\n\nconst HTML_COMMENT_PATTERN = /<!--[\\s\\S]*?-->/g;\n\n// ============================================================================\n// Injection Pattern Detectors\n// ============================================================================\n\ninterface PatternMatch {\n flag: InjectionFlag;\n pattern: RegExp;\n}\n\nconst INJECTION_PATTERNS: readonly PatternMatch[] = [\n {\n flag: 'authority_claim',\n pattern: /\\b(as (?:a|the) (?:maintainer|admin|owner|security lead|repo owner|developer))\\b/i,\n },\n {\n flag: 'authority_claim',\n pattern: /\\b(i(?:'m| am) the (?:repo |project )?(?:owner|maintainer|admin))\\b/i,\n },\n {\n flag: 'instruction_pattern',\n pattern: /\\b(please (?:close|merge|label|mark|apply|delete|remove|approve|reject))\\b/i,\n },\n {\n flag: 'instruction_pattern',\n pattern: /\\b(you (?:should|must|need to) (?:close|merge|label|apply|delete))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(ignore (?:all )?previous (?:instructions|rules|prompts))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(forget (?:your |all )?(?:instructions|rules|safety))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(new (?:instructions|rules|system prompt|directives))\\b/i,\n },\n {\n flag: 'urgency_manipulation',\n pattern: /\\b(critical|emergency|urgent|must act now|immediately|time[- ]?sensitive)\\b/i,\n },\n {\n flag: 'fake_conversation',\n pattern: /<(?:assistant|human|user|system)>/i,\n },\n // base64_encoded is detected separately by `looksLikeBase64Payload` below.\n // The lookahead-based regex it replaced exhibited catastrophic backtracking\n // on long hex-only inputs (#2191) — see `looksLikeBase64Payload` for the\n // two-phase rewrite that preserves the #1811 SHA-hash false-positive guard.\n {\n flag: 'external_link_instruction',\n pattern: /(?:apply|run|execute|install)\\s+(?:this\\s+)?(?:from\\s+)?https?:\\/\\//i,\n },\n];\n\n/**\n * Two-phase base64-payload detection (#2191).\n *\n * The original `(?=[A-Za-z0-9+/]*[g-zG-Z+/=])[A-Za-z0-9+/]{40,}={0,2}` regex\n * was vulnerable to catastrophic backtracking — V8 took ~1.8s on a 50K\n * hex-only adversarial input. Splitting the check into two non-overlapping\n * phases removes the lookahead and makes the worst case linear.\n *\n * Phase 1: find a 40+ run of base64-alphabet chars (no lookahead).\n * Phase 2: confirm the matched substring contains a base64-discriminating\n * char (g-z, G-Z, +, /, =) so SHA-1 / SHA-256 hex hashes don't\n * false-positive (preserves #1811 behavior).\n *\n * Same detection coverage as the original; same false-positive resistance.\n */\nconst BASE64_RUN_GLOBAL = /[A-Za-z0-9+/]{40,}={0,2}/g;\nconst BASE64_DISCRIMINATOR = /[g-zG-Z+/=]/;\n\nfunction looksLikeBase64Payload(content: string): boolean {\n // Iterate every 40+ base64-alphabet run rather than just the first one,\n // so a long hex-only prefix doesn't mask a real base64 payload that\n // appears later in the content.\n for (const match of content.matchAll(BASE64_RUN_GLOBAL)) {\n if (BASE64_DISCRIMINATOR.test(match[0])) return true;\n }\n return false;\n}\n\n// ============================================================================\n// HTML Entity Decoding (evasion defense)\n// ============================================================================\n\n/**\n * Dangerous-tag names we will still match after entity decoding.\n * Kept in sync with DANGEROUS_HTML_PATTERN and XML_INJECTION_PATTERN above.\n */\nconst DANGEROUS_TAG_NAMES =\n 'picture|source|img|system|human|assistant|instructions|user|prompt|context|tool_use|tool_result';\n\n/**\n * Detects whether the input contains entity-encoded forms of any dangerous\n * tag (&lt;picture, &#60;system, &#x3c;img …). Used as a cheap pre-check so\n * that benign content with legitimate entities (e.g. \"AT&amp;T\") is passed\n * through untouched and wasModified stays false.\n */\nconst ENCODED_DANGEROUS_TAG_PATTERN = new RegExp(\n `&(?:lt|#0*60|#x0*3c);\\\\s*\\\\/?\\\\s*(?:${DANGEROUS_TAG_NAMES})\\\\b`,\n 'i'\n);\n\n/** Decodes the subset of HTML entities that can reconstruct tag syntax. */\nfunction decodeEntities(content: string): string {\n return (\n content\n // Numeric (decimal) references\n .replace(/&#(\\d+);/g, (_match, dec: string) => {\n const code = Number.parseInt(dec, 10);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _match;\n })\n // Numeric (hex) references\n .replace(/&#x([0-9a-f]+);/gi, (_match, hex: string) => {\n const code = Number.parseInt(hex, 16);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _match;\n })\n // Named entities most relevant to tag reconstruction\n .replace(/&lt;/gi, '<')\n .replace(/&gt;/gi, '>')\n .replace(/&quot;/gi, '\"')\n .replace(/&apos;/gi, \"'\")\n // &amp; must be decoded last so that &amp;lt; does not resurface as <\n .replace(/&amp;/gi, '&')\n );\n}\n\n/**\n * Runs decodeEntities only if the input contains an entity-encoded dangerous\n * tag. This keeps benign content with legitimate entities untouched.\n */\nfunction applyEntityEvasionDefense(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n if (!ENCODED_DANGEROUS_TAG_PATTERN.test(content)) {\n return { cleaned: content, stripped: [] };\n }\n const decoded = decodeEntities(content);\n return {\n cleaned: decoded,\n stripped: [\n {\n tag: '&…;',\n reason: 'HTML entity-encoded dangerous tag decoded for stripping (CWE-79)',\n startIndex: 0,\n length: content.length,\n },\n ],\n };\n}\n\n// ============================================================================\n// Core Sanitization Functions\n// ============================================================================\n\n/** Strips dangerous HTML tags and records what was removed.\n * Loops until stable to prevent reconstructed patterns after removal (#1496). */\nfunction stripDangerousHtml(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n DANGEROUS_HTML_PATTERN.lastIndex = 0;\n if (!DANGEROUS_HTML_PATTERN.test(cleaned)) break;\n cleaned = cleaned.replace(DANGEROUS_HTML_PATTERN, (match, _g1, _g2, offset: number) => {\n stripped.push({\n tag: match.slice(0, 30) + (match.length > 30 ? '...' : ''),\n reason: 'Dangerous HTML tag (Trail of Bits injection vector)',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n }\n return { cleaned, stripped };\n}\n\n/** Strips XML-like tags that mimic conversation structure.\n * Loops until stable to prevent reconstructed patterns after removal (#1496). */\nfunction stripXmlTags(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n XML_INJECTION_PATTERN.lastIndex = 0;\n if (!XML_INJECTION_PATTERN.test(cleaned)) break;\n cleaned = cleaned.replace(XML_INJECTION_PATTERN, (match, _g1, offset: number) => {\n stripped.push({\n tag: match,\n reason: 'XML-like conversation injection tag',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n }\n return { cleaned, stripped };\n}\n\n/** Strips HTML comments that may contain hidden instructions.\n * Loops until stable to prevent reconstructed comment patterns (#1496). */\nfunction stripHtmlComments(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n // Loop until stable: stripping may reveal new instruction-bearing comments\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n HTML_COMMENT_PATTERN.lastIndex = 0;\n const prevLength = cleaned.length;\n cleaned = cleaned.replace(HTML_COMMENT_PATTERN, (match, offset: number) => {\n const hasInstruction = /\\b(ignore|execute|close|merge|delete|apply)\\b/i.test(match);\n if (!hasInstruction) return match;\n\n stripped.push({\n tag: '<!-- ... -->',\n reason: 'HTML comment with instruction-like content',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n if (cleaned.length === prevLength) break;\n }\n // Second pass: strip unclosed <!-- tags (incomplete comment injection)\n let searchFrom = 0;\n while (searchFrom < cleaned.length) {\n const openIdx = cleaned.indexOf('<!--', searchFrom);\n if (openIdx === -1) break;\n const closeIdx = cleaned.indexOf('-->', openIdx + 4);\n if (closeIdx === -1) {\n stripped.push({\n tag: '<!--',\n reason: 'Unclosed HTML comment (potential injection vector)',\n startIndex: openIdx,\n length: cleaned.length - openIdx,\n });\n cleaned = cleaned.slice(0, openIdx);\n break;\n }\n searchFrom = closeIdx + 3;\n }\n return { cleaned, stripped };\n}\n\n/** Detects injection patterns in content without modifying it. */\nfunction detectInjectionPatterns(content: string): InjectionFlag[] {\n const flags = new Set<InjectionFlag>();\n for (const { flag, pattern } of INJECTION_PATTERNS) {\n // Reset lastIndex for global patterns\n pattern.lastIndex = 0;\n if (pattern.test(content)) {\n flags.add(flag);\n }\n }\n if (looksLikeBase64Payload(content)) {\n flags.add('base64_encoded');\n }\n return Array.from(flags);\n}\n\n/** Lower-cases an arbitrary role literal and maps it to a known role. */\nfunction normalizeRole(userRole: string): GitHubUserRole {\n const lower = userRole.toLowerCase();\n if (lower in ROLE_DEFAULT_TRUST) return lower as GitHubUserRole;\n return 'unknown';\n}\n\n/**\n * Assigns trust tier based on user role and injection analysis.\n * Injection patterns can only DOWNGRADE trust, never upgrade.\n */\nfunction assignTrustTier(\n userRole: GitHubUserRole,\n injectionFlags: readonly InjectionFlag[],\n allowlisted: boolean\n): TrustTier {\n if (allowlisted) return '1';\n\n // Defensive lowercase — the type says GitHubUserRole, but callers\n // sometimes cast an unnormalized GitHub author_association literal\n // (e.g. 'OWNER', 'MEMBER') directly. Normalize here so the maintainer\n // exemption below matches regardless of case (CWE-178).\n const normalizedRole = normalizeRole(userRole);\n const baseTier = ROLE_DEFAULT_TRUST[normalizedRole];\n\n // Content with injection patterns is downgraded to Tier 4 (hostile)\n const hostileFlags: InjectionFlag[] = ['system_prompt_manipulation', 'fake_conversation'];\n if (injectionFlags.some((f) => hostileFlags.includes(f))) return '4';\n\n // Content with authority claims from non-maintainers is suspicious\n if (\n injectionFlags.includes('authority_claim') &&\n normalizedRole !== 'owner' &&\n normalizedRole !== 'maintainer'\n ) {\n return '4';\n }\n\n return baseTier;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Sanitizes untrusted GitHub input through the full Layer 1 pipeline:\n * 1. HTML stripping (picture/source/img tags)\n * 2. XML tag stripping (system/human/assistant)\n * 3. HTML comment stripping (instruction-bearing comments only)\n * 4. Injection pattern detection\n * 5. Trust tier assignment\n *\n * ⚠ **Use HostileInputFirewall.process() in agent code paths.** Calling\n * sanitizeInput() directly only runs Layer 1 — it does not evaluate the\n * Rule of Two (enforced in policy-gate.ts via evaluatePolicy) and does\n * not emit audit-trail events. An agent that processes untrusted input\n * while holding both write access and secrets violates the Rule of Two;\n * the policy gate is what catches this, and it only runs inside the\n * firewall pipeline. Direct use of this function is appropriate for\n * unit tests and pure content analysis, not for agent decision paths.\n *\n * @see packages/nexus-agents/src/security/firewall/firewall-pipeline.ts\n * @see packages/nexus-agents/src/security/policy-gate.ts\n * @param content - Raw untrusted content from GitHub\n * @param userRole - GitHub user's relationship to the repository\n * @param username - GitHub username (for allowlist check)\n * @param config - Optional sanitizer configuration\n * @returns SanitizedInput with cleaned content and audit data\n */\nexport function sanitizeInput(\n content: string,\n userRole: GitHubUserRole,\n username: string,\n config?: Partial<SanitizerConfig>\n): SanitizedInput {\n const cfg = SanitizerConfigSchema.parse(config ?? {});\n const truncated = content.slice(0, cfg.maxInputLength);\n const allowlisted = cfg.allowlistedMaintainers.includes(username);\n\n try {\n // Pipeline: decode entity-encoded dangerous tags, then strip dangerous content\n const entityDecoded = applyEntityEvasionDefense(truncated);\n const html = stripDangerousHtml(entityDecoded.cleaned);\n const xml = stripXmlTags(html.cleaned);\n const comments = stripHtmlComments(xml.cleaned);\n const allStripped = [\n ...entityDecoded.stripped,\n ...html.stripped,\n ...xml.stripped,\n ...comments.stripped,\n ];\n\n // Detect injection patterns on ORIGINAL content (before stripping)\n const injectionFlags = detectInjectionPatterns(truncated);\n\n // Assign trust tier\n const trustTier = assignTrustTier(userRole, injectionFlags, allowlisted);\n\n return {\n content: comments.cleaned,\n originalLength: content.length,\n trustTier,\n userRole,\n injectionFlags,\n strippedElements: allStripped,\n wasModified: allStripped.length > 0,\n sanitizedAt: new Date().toISOString(),\n };\n } catch (err: unknown) {\n return buildFailClosedResult(err, content, truncated, userRole, allowlisted);\n }\n}\n\n/**\n * Fail-closed result returned when the sanitizer pipeline throws.\n * Returns empty content at Tier-4 (or Tier-1 for allowlisted maintainers,\n * since their bypass is not regex-dependent) so downstream consumers\n * cannot act on untrusted content we could not validate.\n * CLAUDE.md: \"Fail closed on ambiguity.\"\n */\nfunction buildFailClosedResult(\n err: unknown,\n originalContent: string,\n truncated: string,\n userRole: GitHubUserRole,\n allowlisted: boolean\n): SanitizedInput {\n const message = err instanceof Error ? err.message : String(err);\n return {\n content: '',\n originalLength: originalContent.length,\n trustTier: allowlisted ? '1' : '4',\n userRole,\n injectionFlags: [],\n strippedElements: [\n {\n tag: '(pipeline-failure)',\n reason: `Sanitizer pipeline threw; input discarded as fail-closed: ${message}`,\n startIndex: 0,\n length: truncated.length,\n },\n ],\n wasModified: true,\n sanitizedAt: new Date().toISOString(),\n };\n}\n","/**\n * nexus-agents/security - Reputation Model\n *\n * Lightweight trust model for GitHub users that assesses reputation\n * based on account age, contribution history, and behavioral signals.\n * Integrates with the trust classifier for comprehensive trust assessment.\n *\n * @module security/reputation-model\n * (Source: Issue #818, #824 — Phase 3: Reputation Model)\n */\n\nimport { z } from 'zod';\n\nimport { getTimeProvider } from '../core/index.js';\nimport type { TrustTier, GitHubUserRole, InjectionFlag } from './trust-types.js';\nimport { TRUST_TIER_NUMERIC, ROLE_DEFAULT_TRUST } from './trust-types.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Signals that indicate a suspicious actor.\n */\nexport const SuspiciousSignalSchema = z.enum([\n 'new_account',\n 'no_prior_contributions',\n 'injection_patterns_detected',\n 'rapid_comments',\n 'mismatched_authority_claim',\n]);\nexport type SuspiciousSignal = z.infer<typeof SuspiciousSignalSchema>;\n\n/**\n * GitHub user metadata for reputation assessment.\n */\nexport interface GitHubUserMetadata {\n readonly username: string;\n /**\n * Account/activity fields are OPTIONAL (#3106). When a field is absent (the\n * caller couldn't fetch it — e.g. the firewall before Phase 3 wiring), its\n * signal is SKIPPED rather than fabricated: an unknown value must never be\n * treated as benign (the old hardcoded `365`/`0`) nor as hostile. Only the\n * `authorAssociation` + `injectionFlags` signals fire on absent activity data.\n */\n readonly accountAgeDays?: number;\n readonly priorContributions?: number;\n readonly recentCommentCount?: number;\n readonly recentCommentWindowMinutes?: number;\n readonly authorAssociation: string;\n readonly injectionFlags: readonly InjectionFlag[];\n}\n\n/**\n * Result of a reputation assessment.\n */\nexport interface ReputationAssessment {\n readonly username: string;\n readonly userRole: GitHubUserRole;\n readonly suspiciousSignals: readonly SuspiciousSignal[];\n readonly isSuspicious: boolean;\n readonly effectiveTrustTier: TrustTier;\n readonly reputationScore: number;\n readonly reason: string;\n readonly assessedAt: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Thresholds for suspicious behavior detection. */\n/** Approximate days per year, used to normalize account age to a 0–10 scale. */\nconst DAYS_PER_YEAR_APPROX = 36.5;\n\nconst SUSPICIOUS_THRESHOLDS = {\n /** Account younger than this (days) is flagged. */\n newAccountDays: 30,\n /** Fewer contributions than this is flagged. */\n minContributions: 1,\n /** More comments than this in the window triggers rapid-comment flag. */\n rapidCommentThreshold: 5,\n /** Time window (minutes) for rapid comment detection. */\n rapidCommentWindowMinutes: 10,\n} as const;\n\n// ============================================================================\n// Reputation Cache\n// ============================================================================\n\ninterface CacheEntry {\n assessment: ReputationAssessment;\n expiresAt: number;\n}\n\n// Canonical source: config/timeouts.ts (Issue #1046)\nimport { CACHE_TIMEOUTS } from '../config/timeouts.js';\n\nconst DEFAULT_TTL_MS: number = CACHE_TIMEOUTS.reputationTtlMs;\nconst DEFAULT_MAX_SIZE = 1000;\n\n/**\n * In-memory reputation cache with TTL and max size.\n * Reduces redundant assessments for the same user within a short window.\n * Evicts oldest entries when max size is exceeded.\n */\nexport class ReputationCache {\n private readonly cache = new Map<string, CacheEntry>();\n private readonly ttlMs: number;\n private readonly maxSize: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS, maxSize = DEFAULT_MAX_SIZE) {\n this.ttlMs = ttlMs;\n this.maxSize = maxSize;\n }\n\n get(username: string): ReputationAssessment | undefined {\n const entry = this.cache.get(username);\n if (entry === undefined) return undefined;\n if (getTimeProvider().now() > entry.expiresAt) {\n this.cache.delete(username);\n return undefined;\n }\n return entry.assessment;\n }\n\n set(username: string, assessment: ReputationAssessment): void {\n if (this.cache.size >= this.maxSize && !this.cache.has(username)) {\n this.evictOldest();\n }\n this.cache.set(username, {\n assessment,\n expiresAt: getTimeProvider().now() + this.ttlMs,\n });\n }\n\n /** Evict a batch of oldest entries (10% of maxSize, minimum 1). */\n private evictOldest(): void {\n const batchSize = Math.max(1, Math.floor(this.maxSize * 0.1));\n const keys = this.cache.keys();\n for (let i = 0; i < batchSize; i++) {\n const next = keys.next();\n if (next.done === true) break;\n this.cache.delete(next.value);\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n// ============================================================================\n// Suspicious Signal Detection\n// ============================================================================\n\n/** Only hostile-tier injection flags count — benign flags like\n * instruction_pattern (\"please remove\") must not trip the injection signal. */\nconst HOSTILE_INJECTION_FLAGS: readonly InjectionFlag[] = [\n 'system_prompt_manipulation',\n 'fake_conversation',\n 'authority_claim',\n 'hidden_content',\n];\n\nfunction hasHostileInjection(flags: readonly InjectionFlag[]): boolean {\n return flags.some((f) => HOSTILE_INJECTION_FLAGS.includes(f));\n}\n\n/** Rapid-comment burst — only when both count and window are known (#3106). */\nfunction isRapidCommenting(m: GitHubUserMetadata): boolean {\n return (\n m.recentCommentCount !== undefined &&\n m.recentCommentWindowMinutes !== undefined &&\n m.recentCommentCount > SUSPICIOUS_THRESHOLDS.rapidCommentThreshold &&\n m.recentCommentWindowMinutes <= SUSPICIOUS_THRESHOLDS.rapidCommentWindowMinutes\n );\n}\n\n/** Authority claim from a non-maintainer role. */\nfunction isMismatchedAuthority(m: GitHubUserMetadata): boolean {\n if (!m.injectionFlags.includes('authority_claim')) return false;\n const association = m.authorAssociation.toUpperCase();\n return association !== 'OWNER' && association !== 'MEMBER';\n}\n\n/** Detect all suspicious signals from user metadata. #3106: account/activity\n * signals are skipped when their data is absent — never fabricated. */\nfunction detectSuspiciousSignals(metadata: GitHubUserMetadata): SuspiciousSignal[] {\n const signals: SuspiciousSignal[] = [];\n const { accountAgeDays, priorContributions } = metadata;\n\n if (accountAgeDays !== undefined && accountAgeDays < SUSPICIOUS_THRESHOLDS.newAccountDays) {\n signals.push('new_account');\n }\n if (\n priorContributions !== undefined &&\n priorContributions < SUSPICIOUS_THRESHOLDS.minContributions\n ) {\n signals.push('no_prior_contributions');\n }\n if (hasHostileInjection(metadata.injectionFlags)) signals.push('injection_patterns_detected');\n if (isRapidCommenting(metadata)) signals.push('rapid_comments');\n if (isMismatchedAuthority(metadata)) signals.push('mismatched_authority_claim');\n\n return signals;\n}\n\n/** Calculate a 0-100 reputation score. */\nfunction calculateReputationScore(\n metadata: GitHubUserMetadata,\n signals: readonly SuspiciousSignal[],\n userRole: GitHubUserRole\n): number {\n let score = 50; // baseline\n\n // Role bonus\n const roleBonus: Record<GitHubUserRole, number> = {\n owner: 40,\n maintainer: 35,\n collaborator: 25,\n contributor: 15,\n member: 5,\n unknown: 0,\n };\n score += roleBonus[userRole];\n\n // Account age bonus (max +10). #3106: absent → no bonus (avoid NaN; an\n // unknown account neither earns nor loses the age bonus).\n if (metadata.accountAgeDays !== undefined) {\n score += Math.min(metadata.accountAgeDays / DAYS_PER_YEAR_APPROX, 10);\n }\n\n // Contribution bonus (max +10). #3106: absent → no bonus.\n if (metadata.priorContributions !== undefined) {\n score += Math.min(metadata.priorContributions, 10);\n }\n\n // Suspicious signal penalties\n const signalPenalty: Record<SuspiciousSignal, number> = {\n new_account: -15,\n no_prior_contributions: -10,\n injection_patterns_detected: -25,\n rapid_comments: -20,\n mismatched_authority_claim: -30,\n };\n for (const signal of signals) {\n score += signalPenalty[signal];\n }\n\n return Math.max(0, Math.min(100, Math.round(score)));\n}\n\n/** Map role string to GitHubUserRole. */\nfunction mapRole(association: string): GitHubUserRole {\n switch (association.toUpperCase()) {\n case 'OWNER':\n return 'owner';\n case 'MEMBER':\n return 'member';\n case 'COLLABORATOR':\n return 'collaborator';\n case 'CONTRIBUTOR':\n return 'contributor';\n default:\n return 'unknown';\n }\n}\n\n/** Determine effective trust tier from signals and role. */\nfunction determineEffectiveTier(\n userRole: GitHubUserRole,\n signals: readonly SuspiciousSignal[]\n): TrustTier {\n const baseTier = ROLE_DEFAULT_TRUST[userRole];\n\n // Hostile signals → Tier 4\n const hostileSignals: SuspiciousSignal[] = [\n 'injection_patterns_detected',\n 'mismatched_authority_claim',\n ];\n if (signals.some((s) => hostileSignals.includes(s))) return '4';\n\n // Multiple suspicious signals → downgrade by 1\n if (signals.length >= 2) {\n const baseNumeric = TRUST_TIER_NUMERIC[baseTier];\n const downgraded = Math.min(baseNumeric + 1, 4);\n return String(downgraded) as TrustTier;\n }\n\n return baseTier;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Assess a GitHub user's reputation for trust classification.\n *\n * @param metadata - User metadata from GitHub API or local context.\n * @param cache - Optional cache instance for TTL-based deduplication.\n * @returns ReputationAssessment with trust tier and suspicious signals.\n */\nexport function assessReputation(\n metadata: GitHubUserMetadata,\n cache?: ReputationCache\n): ReputationAssessment {\n // Check cache first\n const cached = cache?.get(metadata.username);\n if (cached !== undefined) return cached;\n\n const userRole = mapRole(metadata.authorAssociation);\n const signals = detectSuspiciousSignals(metadata);\n const score = calculateReputationScore(metadata, signals, userRole);\n const effectiveTier = determineEffectiveTier(userRole, signals);\n\n const assessment: ReputationAssessment = {\n username: metadata.username,\n userRole,\n suspiciousSignals: signals,\n isSuspicious: signals.length > 0,\n effectiveTrustTier: effectiveTier,\n reputationScore: score,\n reason: buildReason(userRole, signals, effectiveTier),\n assessedAt: new Date().toISOString(),\n };\n\n cache?.set(metadata.username, assessment);\n return assessment;\n}\n\n/**\n * Reconcile a trust-classifier tier with a reputation assessment into the\n * effective tier to enforce (#3119 / epic #3118). Demotion-only — reputation\n * can only RAISE the tier number (more restrictive), never lower it.\n *\n * Invariants:\n * - **Allowlist/Tier-1 wins**: a classifier Tier 1 (owner/allowlisted maintainer)\n * is authoritative — reputation never demotes it.\n * - **Absent reputation → classifier tier**: no assessment (stage off / not\n * fetched) keeps the classifier/role-default tier — never fabricate a benign\n * tier, never escalate on mere absence (fetch-failure ≠ hostile signal).\n * - **Score is advisory**: only `effectiveTrustTier` participates; the 0–100\n * `reputationScore` never moves the gate.\n */\nexport function reconcileTrustTier(\n classifierTier: TrustTier,\n reputation: ReputationAssessment | undefined\n): TrustTier {\n if (classifierTier === '1') return '1';\n const repTier = reputation?.effectiveTrustTier;\n if (repTier === undefined) return classifierTier;\n return TRUST_TIER_NUMERIC[repTier] > TRUST_TIER_NUMERIC[classifierTier]\n ? repTier\n : classifierTier;\n}\n\n// ============================================================================\n// Reputation gating rollout (#3122 / epic #3118 Phase 4)\n// ============================================================================\n\n/**\n * Rollout mode for reputation-based tier gating, mirroring\n * `NEXUS_ACCESS_POLICY_MODE` (#1977): `off` (no reputation effect), `audit`\n * (compute + report the would-be demotion but enforce the classifier tier), or\n * `enforce` (apply the demotion). Default `audit` — surface telemetry without\n * blocking until the false-positive rate is known, then flip to `enforce`.\n */\nexport const ReputationGatingModeSchema = z.enum(['off', 'audit', 'enforce']);\nexport type ReputationGatingMode = z.infer<typeof ReputationGatingModeSchema>;\n\n/** Default when `NEXUS_REPUTATION_GATING` is unset/invalid — audit (telemetry, no block). */\nexport const DEFAULT_REPUTATION_GATING_MODE: ReputationGatingMode = 'audit';\n\n/** Resolve the gating mode from the environment (invalid → default, never throws). */\nexport function resolveReputationGatingMode(\n env: NodeJS.ProcessEnv = process.env\n): ReputationGatingMode {\n const raw = env['NEXUS_REPUTATION_GATING'];\n if (typeof raw !== 'string' || raw.length === 0) return DEFAULT_REPUTATION_GATING_MODE;\n const parsed = ReputationGatingModeSchema.safeParse(raw.toLowerCase());\n return parsed.success ? parsed.data : DEFAULT_REPUTATION_GATING_MODE;\n}\n\n/** Outcome of applying the gating mode to a reputation assessment. */\nexport interface ReputationGateDecision {\n /** Tier to actually enforce at the policy gate. */\n readonly enforcedTier: TrustTier;\n /** Tier reputation reconciliation computed (what `enforce` mode WOULD use). */\n readonly reconciledTier: TrustTier;\n /** True when reputation would demote but the mode (off/audit) did not enforce it. */\n readonly demotionSuppressed: boolean;\n readonly mode: ReputationGatingMode;\n}\n\n/**\n * Apply the rollout mode to a reputation assessment (#3122). `enforce` gates on\n * the reconciled (possibly demoted) tier; `audit`/`off` gate on the classifier\n * tier but report whether a demotion was suppressed (for telemetry). The\n * Tier-1/allowlist-wins and demotion-only invariants live in `reconcileTrustTier`,\n * so the allowlist remains the escape hatch in every mode.\n */\nexport function gateWithReputation(\n classifierTier: TrustTier,\n reputation: ReputationAssessment | undefined,\n mode: ReputationGatingMode\n): ReputationGateDecision {\n const reconciledTier =\n mode === 'off' ? classifierTier : reconcileTrustTier(classifierTier, reputation);\n const enforcedTier = mode === 'enforce' ? reconciledTier : classifierTier;\n return {\n enforcedTier,\n reconciledTier,\n demotionSuppressed: mode !== 'enforce' && reconciledTier !== classifierTier,\n mode,\n };\n}\n\n/** Build a human-readable reason string. */\nfunction buildReason(\n role: GitHubUserRole,\n signals: readonly SuspiciousSignal[],\n tier: TrustTier\n): string {\n if (signals.length === 0) {\n return `Role ${role} → Tier ${tier} (no suspicious signals)`;\n }\n const signalList = signals.join(', ');\n return `Role ${role} → Tier ${tier} (signals: ${signalList})`;\n}\n"],"mappings":";;;;;;AAWA,SAAS,SAAS;AAeX,IAAM,kBAAkB,EAAE,KAAK,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAInD,IAAM,qBAAgD;AAAA,EAC3D,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AASO,IAAM,uBAAuB,EAAE,KAAK;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOM,IAAM,qBAAwD;AAAA,EACnE,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;AASO,IAAM,sBAAsB,EAAE,KAAK;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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