@claude-flow/security 3.0.0-alpha.9 → 3.0.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 (116) hide show
  1. package/dist/CVE-REMEDIATION.d.ts +17 -6
  2. package/dist/CVE-REMEDIATION.d.ts.map +1 -1
  3. package/dist/CVE-REMEDIATION.js +328 -12
  4. package/dist/CVE-REMEDIATION.js.map +1 -1
  5. package/dist/index.d.ts +8 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +26 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/keychain-adapter.d.ts +48 -0
  10. package/dist/keychain-adapter.d.ts.map +1 -0
  11. package/dist/keychain-adapter.js +0 -0
  12. package/dist/keychain-adapter.js.map +1 -0
  13. package/dist/mcp-caller-identity.d.ts +101 -0
  14. package/dist/mcp-caller-identity.d.ts.map +1 -0
  15. package/dist/mcp-caller-identity.js +0 -0
  16. package/dist/mcp-caller-identity.js.map +1 -0
  17. package/dist/mcp-composition-inspector.d.ts +133 -0
  18. package/dist/mcp-composition-inspector.d.ts.map +1 -0
  19. package/dist/mcp-composition-inspector.js +254 -0
  20. package/dist/mcp-composition-inspector.js.map +1 -0
  21. package/dist/oauth/browser.d.ts +31 -0
  22. package/dist/oauth/browser.d.ts.map +1 -0
  23. package/dist/oauth/browser.js +55 -0
  24. package/dist/oauth/browser.js.map +1 -0
  25. package/dist/oauth/callback-server.d.ts +37 -0
  26. package/dist/oauth/callback-server.d.ts.map +1 -0
  27. package/dist/oauth/callback-server.js +86 -0
  28. package/dist/oauth/callback-server.js.map +1 -0
  29. package/dist/oauth/client.d.ts +57 -0
  30. package/dist/oauth/client.d.ts.map +1 -0
  31. package/dist/oauth/client.js +120 -0
  32. package/dist/oauth/client.js.map +1 -0
  33. package/dist/oauth/pkce.d.ts +25 -0
  34. package/dist/oauth/pkce.d.ts.map +1 -0
  35. package/dist/oauth/pkce.js +36 -0
  36. package/dist/oauth/pkce.js.map +1 -0
  37. package/dist/path-validator.d.ts +23 -0
  38. package/dist/path-validator.d.ts.map +1 -1
  39. package/dist/path-validator.js +128 -5
  40. package/dist/path-validator.js.map +1 -1
  41. package/dist/policy/canonical.d.ts +5 -0
  42. package/dist/policy/canonical.d.ts.map +1 -0
  43. package/dist/policy/canonical.js +30 -0
  44. package/dist/policy/canonical.js.map +1 -0
  45. package/dist/policy/engine.d.ts +34 -0
  46. package/dist/policy/engine.d.ts.map +1 -0
  47. package/dist/policy/engine.js +285 -0
  48. package/dist/policy/engine.js.map +1 -0
  49. package/dist/policy/envelope.d.ts +9 -0
  50. package/dist/policy/envelope.d.ts.map +1 -0
  51. package/dist/policy/envelope.js +90 -0
  52. package/dist/policy/envelope.js.map +1 -0
  53. package/dist/policy/evaluator.d.ts +4 -0
  54. package/dist/policy/evaluator.d.ts.map +1 -0
  55. package/dist/policy/evaluator.js +119 -0
  56. package/dist/policy/evaluator.js.map +1 -0
  57. package/dist/policy/index.d.ts +7 -0
  58. package/dist/policy/index.d.ts.map +1 -0
  59. package/dist/policy/index.js +7 -0
  60. package/dist/policy/index.js.map +1 -0
  61. package/dist/policy/product-plane.d.ts +238 -0
  62. package/dist/policy/product-plane.d.ts.map +1 -0
  63. package/dist/policy/product-plane.js +1022 -0
  64. package/dist/policy/product-plane.js.map +1 -0
  65. package/dist/policy/types.d.ts +169 -0
  66. package/dist/policy/types.d.ts.map +1 -0
  67. package/dist/policy/types.js +2 -0
  68. package/dist/policy/types.js.map +1 -0
  69. package/dist/safe-git.d.ts +22 -0
  70. package/dist/safe-git.d.ts.map +1 -0
  71. package/dist/safe-git.js +63 -0
  72. package/dist/safe-git.js.map +1 -0
  73. package/package.json +17 -5
  74. package/.claude-flow/data/pending-insights.jsonl +0 -6
  75. package/.claude-flow/neural/stats.json +0 -6
  76. package/__tests__/acceptance/security-compliance.test.ts +0 -674
  77. package/__tests__/authorization-propagator.test.ts +0 -155
  78. package/__tests__/credential-generator.test.ts +0 -310
  79. package/__tests__/fixtures/configurations.ts +0 -425
  80. package/__tests__/fixtures/index.ts +0 -21
  81. package/__tests__/helpers/create-mock.ts +0 -469
  82. package/__tests__/helpers/index.ts +0 -32
  83. package/__tests__/input-validator.test.ts +0 -382
  84. package/__tests__/integration/security-flow.test.ts +0 -606
  85. package/__tests__/password-hasher.test.ts +0 -239
  86. package/__tests__/path-validator.test.ts +0 -302
  87. package/__tests__/plugin-integrity-verifier.test.ts +0 -199
  88. package/__tests__/safe-executor.test.ts +0 -292
  89. package/__tests__/token-generator.test.ts +0 -371
  90. package/__tests__/tool-output-guardrail.test.ts +0 -256
  91. package/__tests__/unit/credential-generator.test.ts +0 -182
  92. package/__tests__/unit/password-hasher.test.ts +0 -359
  93. package/__tests__/unit/path-validator.test.ts +0 -509
  94. package/__tests__/unit/safe-executor.test.ts +0 -667
  95. package/__tests__/unit/token-generator.test.ts +0 -310
  96. package/ruvector.db +0 -0
  97. package/src/CVE-REMEDIATION.ts +0 -251
  98. package/src/application/index.ts +0 -10
  99. package/src/application/services/security-application-service.ts +0 -193
  100. package/src/authorization/propagator.ts +0 -279
  101. package/src/credential-generator.ts +0 -368
  102. package/src/domain/entities/security-context.ts +0 -173
  103. package/src/domain/index.ts +0 -17
  104. package/src/domain/services/security-domain-service.ts +0 -296
  105. package/src/index.ts +0 -314
  106. package/src/input-validator.ts +0 -466
  107. package/src/password-hasher.ts +0 -277
  108. package/src/path-validator.ts +0 -525
  109. package/src/plugins/integrity-verifier.ts +0 -265
  110. package/src/safe-executor.ts +0 -546
  111. package/src/token-generator.ts +0 -463
  112. package/src/tool-output-guardrail.ts +0 -360
  113. package/tmp.json +0 -0
  114. package/tsconfig.json +0 -9
  115. package/tsconfig.tsbuildinfo +0 -1
  116. package/vitest.config.ts +0 -20
@@ -1,193 +0,0 @@
1
- /**
2
- * Security Application Service - Application Layer
3
- *
4
- * Orchestrates security operations and provides simplified interface.
5
- *
6
- * @module v3/security/application/services
7
- */
8
-
9
- import { SecurityContext, PermissionLevel } from '../../domain/entities/security-context.js';
10
- import { SecurityDomainService, ValidationResult, ThreatDetectionResult } from '../../domain/services/security-domain-service.js';
11
-
12
- /**
13
- * Security audit result
14
- */
15
- export interface SecurityAuditResult {
16
- passed: boolean;
17
- score: number;
18
- checks: Array<{
19
- name: string;
20
- passed: boolean;
21
- severity: 'low' | 'medium' | 'high' | 'critical';
22
- message: string;
23
- }>;
24
- recommendations: string[];
25
- }
26
-
27
- /**
28
- * Security Application Service
29
- */
30
- export class SecurityApplicationService {
31
- private readonly domainService: SecurityDomainService;
32
- private readonly contexts: Map<string, SecurityContext> = new Map();
33
-
34
- constructor() {
35
- this.domainService = new SecurityDomainService();
36
- }
37
-
38
- // ============================================================================
39
- // Context Management
40
- // ============================================================================
41
-
42
- /**
43
- * Create and register security context for agent
44
- */
45
- createAgentContext(agentId: string, role: string): SecurityContext {
46
- const context = this.domainService.createAgentContext(agentId, role);
47
- this.contexts.set(agentId, context);
48
- return context;
49
- }
50
-
51
- /**
52
- * Get security context
53
- */
54
- getContext(principalId: string): SecurityContext | undefined {
55
- return this.contexts.get(principalId);
56
- }
57
-
58
- /**
59
- * Remove security context
60
- */
61
- removeContext(principalId: string): boolean {
62
- return this.contexts.delete(principalId);
63
- }
64
-
65
- // ============================================================================
66
- // Validation
67
- // ============================================================================
68
-
69
- /**
70
- * Validate path access
71
- */
72
- validatePath(path: string, principalId: string): ValidationResult {
73
- const context = this.contexts.get(principalId);
74
- if (!context) {
75
- return {
76
- valid: false,
77
- errors: ['Security context not found'],
78
- warnings: [],
79
- };
80
- }
81
-
82
- return this.domainService.validatePath(path, context);
83
- }
84
-
85
- /**
86
- * Validate command execution
87
- */
88
- validateCommand(command: string, principalId: string): ValidationResult {
89
- const context = this.contexts.get(principalId);
90
- if (!context) {
91
- return {
92
- valid: false,
93
- errors: ['Security context not found'],
94
- warnings: [],
95
- };
96
- }
97
-
98
- return this.domainService.validateCommand(command, context);
99
- }
100
-
101
- /**
102
- * Validate user input
103
- */
104
- validateInput(input: string): ValidationResult {
105
- return this.domainService.validateInput(input);
106
- }
107
-
108
- /**
109
- * Detect threats in content
110
- */
111
- detectThreats(content: string): ThreatDetectionResult {
112
- return this.domainService.detectThreats(content);
113
- }
114
-
115
- // ============================================================================
116
- // Audit
117
- // ============================================================================
118
-
119
- /**
120
- * Run security audit on codebase
121
- */
122
- async auditCodebase(files: Array<{ path: string; content: string }>): Promise<SecurityAuditResult> {
123
- const checks: SecurityAuditResult['checks'] = [];
124
- const recommendations: string[] = [];
125
- let criticalCount = 0;
126
- let highCount = 0;
127
-
128
- for (const file of files) {
129
- const threats = this.domainService.detectThreats(file.content);
130
-
131
- for (const threat of threats.threats) {
132
- checks.push({
133
- name: `${threat.type} in ${file.path}`,
134
- passed: false,
135
- severity: threat.severity,
136
- message: threat.description,
137
- });
138
-
139
- if (threat.severity === 'critical') criticalCount++;
140
- if (threat.severity === 'high') highCount++;
141
- }
142
-
143
- if (threats.safe) {
144
- checks.push({
145
- name: `Security check: ${file.path}`,
146
- passed: true,
147
- severity: 'low',
148
- message: 'No threats detected',
149
- });
150
- }
151
- }
152
-
153
- // Generate recommendations
154
- if (criticalCount > 0) {
155
- recommendations.push('Address critical security issues immediately');
156
- }
157
- if (highCount > 0) {
158
- recommendations.push('Review and fix high-severity findings');
159
- }
160
- recommendations.push('Run regular security scans');
161
- recommendations.push('Keep dependencies updated');
162
-
163
- // Calculate score
164
- const totalChecks = checks.length;
165
- const passedChecks = checks.filter((c) => c.passed).length;
166
- const score = totalChecks > 0 ? Math.round((passedChecks / totalChecks) * 100) : 100;
167
-
168
- return {
169
- passed: criticalCount === 0 && highCount === 0,
170
- score,
171
- checks,
172
- recommendations,
173
- };
174
- }
175
-
176
- /**
177
- * Check if operation is allowed
178
- */
179
- isOperationAllowed(
180
- principalId: string,
181
- operation: 'path' | 'command',
182
- target: string
183
- ): boolean {
184
- const context = this.contexts.get(principalId);
185
- if (!context || context.isExpired()) return false;
186
-
187
- if (operation === 'path') {
188
- return context.canAccessPath(target);
189
- } else {
190
- return context.canExecuteCommand(target);
191
- }
192
- }
193
- }
@@ -1,279 +0,0 @@
1
- /**
2
- * AgentAuthorizationPropagator — action-layer security for agent delegation.
3
- *
4
- * Implements P1 of ADR-144 (ruvnet/ruflo#2248): scope-envelope on SendMessage
5
- * + per-action authorization checks. P2-P5 wire this into the comms layer,
6
- * MCP dispatcher, MCP auth validator, and provenance log respectively.
7
- *
8
- * Threat model
9
- * ------------
10
- * When agent A delegates a task to agent B via SendMessage, B can today
11
- * escalate the granted scope by calling tools A was never authorized to
12
- * invoke. RBAC/ABAC on agent roles do not solve this — roles don't compose
13
- * under dynamic LLM delegation (arXiv:2605.05440, Grade A formal analysis).
14
- *
15
- * The fix is scope-based propagation: every SendMessage carries an
16
- * `AuthScope` that is *monotonically reducing* — each hop can drop tools or
17
- * servers from the granted set but never add them. This is the same shape
18
- * as OAuth scope reduction; adding back a tool requires talking to the
19
- * original principal out-of-band.
20
- *
21
- * Scope
22
- * -----
23
- * - P1 (this file): the component, the envelope, the type-level invariants.
24
- * No call sites yet — adding the wrapping/enforcement in P2-P4.
25
- * - All operations synchronous, pure, allocation-light. Targets < 1 ms p99
26
- * for `wrapOutbound` + `checkToolCall` so it can sit on every SendMessage.
27
- *
28
- * Backwards compatibility
29
- * -----------------------
30
- * `scope` on the envelope is optional in v1. Agents without scope set
31
- * operate in legacy permissive mode (all tools allowed, depth unlimited,
32
- * server auth unchecked). `CLAUDE_FLOW_STRICT_AUTH=true` enables enforcement.
33
- *
34
- * Reference: ADR-144, arXiv:2605.05440 (Authorization Propagation),
35
- * arXiv:2605.28914 (AIRGuard), arXiv:2605.22333 (MCP auth survey).
36
- */
37
-
38
- /** Scope granted to an agent at a delegation hop. Monotonically reducing. */
39
- export interface AuthScope {
40
- /** Stable identifier of the originating principal (agent or user). */
41
- readonly principalId: string;
42
- /** MCP tool IDs this scope is allowed to call. */
43
- readonly grantedTools: ReadonlyArray<string>;
44
- /** MCP server IDs whose tool responses this scope will accept. */
45
- readonly grantedServers: ReadonlyArray<string>;
46
- /** Max remaining delegation hops. Decrements on every `wrapOutbound`. */
47
- readonly delegationDepth: number;
48
- /** Unix ms after which this scope is no longer valid. */
49
- readonly expiresAt: number;
50
- /**
51
- * Optional opaque ID for cross-referencing with ADR-144 P5 provenance log
52
- * and ADR-146 telemetry events. Callers should treat as a correlation
53
- * handle, not a security claim.
54
- */
55
- readonly scopeId?: string;
56
- }
57
-
58
- /** Envelope shape attached to every SendMessage when strict-auth is on. */
59
- export interface SendMessageEnvelope<T = unknown> {
60
- /** Authorization scope governing what the receiver may do. */
61
- readonly scope: AuthScope;
62
- /** The original SendMessage payload, untouched. */
63
- readonly payload: T;
64
- }
65
-
66
- /** Decision returned by `checkToolCall`. Never throws. */
67
- export interface ToolCallDecision {
68
- readonly allowed: boolean;
69
- /** Human-readable reason; stable enough to match in tests/telemetry. */
70
- readonly reason?:
71
- | 'tool-not-in-scope'
72
- | 'server-not-in-scope'
73
- | 'scope-expired'
74
- | 'delegation-depth-exhausted'
75
- | 'principal-mismatch';
76
- }
77
-
78
- /**
79
- * Wrap-failure reasons surfaced to callers as a typed error. We use a
80
- * discriminated union rather than throwing so the comms layer (P2) can
81
- * decide whether to drop the SendMessage or surface to the user.
82
- */
83
- export class AuthorizationPropagationError extends Error {
84
- constructor(
85
- public readonly code:
86
- | 'scope-cannot-grow'
87
- | 'depth-underflow'
88
- | 'scope-expired'
89
- | 'principal-mismatch',
90
- message: string,
91
- ) {
92
- super(message);
93
- this.name = 'AuthorizationPropagationError';
94
- }
95
- }
96
-
97
- /**
98
- * Construct a default permissive scope. Used in legacy mode when no scope
99
- * was attached upstream. Callers SHOULD migrate to explicit scopes; this is
100
- * here so the propagator never has to special-case "no scope".
101
- */
102
- export function makeLegacyPermissiveScope(principalId = 'legacy'): AuthScope {
103
- return {
104
- principalId,
105
- grantedTools: ['*'], // sentinel — see `checkToolCall`
106
- grantedServers: ['*'],
107
- delegationDepth: Number.MAX_SAFE_INTEGER,
108
- expiresAt: Number.MAX_SAFE_INTEGER,
109
- };
110
- }
111
-
112
- /**
113
- * `AgentAuthorizationPropagator` — the load-bearing component for ADR-144.
114
- *
115
- * Construction is intentionally cheap (no I/O, no async). Callers can build
116
- * a fresh instance per task without overhead, or share one — it holds no
117
- * mutable state beyond the optional provenance buffer.
118
- */
119
- export class AgentAuthorizationPropagator {
120
- /**
121
- * In-memory provenance buffer. P5 will flush this to the structured
122
- * telemetry sink (ADR-146 GuardrailEvent shape). For P1 we just retain
123
- * the last N events for inspection/tests.
124
- */
125
- private readonly provenance: Array<{
126
- agentId: string;
127
- toolId: string;
128
- scope: AuthScope;
129
- outcome: 'allowed' | 'denied';
130
- reason?: string;
131
- ts: number;
132
- }> = [];
133
-
134
- constructor(private readonly opts: { provenanceBufferMax?: number } = {}) {}
135
-
136
- /**
137
- * Attach a reduced scope to an outbound SendMessage.
138
- *
139
- * Invariants enforced (throws `AuthorizationPropagationError` on violation):
140
- * - newly granted tools MUST be a subset of `currentScope.grantedTools`
141
- * - newly granted servers MUST be a subset of `currentScope.grantedServers`
142
- * - delegationDepth MUST decrement by ≥ 1 (must remain ≥ 0)
143
- * - principalId is propagated unchanged
144
- * - expiresAt cannot be extended; copied from the holder
145
- */
146
- wrapOutbound<T>(
147
- payload: T,
148
- currentScope: AuthScope,
149
- requested: { tools?: ReadonlyArray<string>; servers?: ReadonlyArray<string> } = {},
150
- ): SendMessageEnvelope<T> {
151
- if (currentScope.delegationDepth <= 0) {
152
- throw new AuthorizationPropagationError(
153
- 'depth-underflow',
154
- `cannot delegate further — delegationDepth=${currentScope.delegationDepth}`,
155
- );
156
- }
157
- const now = Date.now();
158
- if (currentScope.expiresAt <= now) {
159
- throw new AuthorizationPropagationError(
160
- 'scope-expired',
161
- `scope expired at ${new Date(currentScope.expiresAt).toISOString()}`,
162
- );
163
- }
164
-
165
- const reducedTools = subsetOrThrow(
166
- currentScope.grantedTools,
167
- requested.tools ?? currentScope.grantedTools,
168
- 'tools',
169
- );
170
- const reducedServers = subsetOrThrow(
171
- currentScope.grantedServers,
172
- requested.servers ?? currentScope.grantedServers,
173
- 'servers',
174
- );
175
-
176
- const reducedScope: AuthScope = {
177
- principalId: currentScope.principalId,
178
- grantedTools: reducedTools,
179
- grantedServers: reducedServers,
180
- delegationDepth: currentScope.delegationDepth - 1,
181
- expiresAt: currentScope.expiresAt,
182
- scopeId: currentScope.scopeId,
183
- };
184
-
185
- return { scope: reducedScope, payload };
186
- }
187
-
188
- /**
189
- * Validate a single tool call against a scope. Pure; never throws. Use the
190
- * result's `allowed` to make the dispatch decision.
191
- */
192
- checkToolCall(
193
- toolId: string,
194
- scope: AuthScope,
195
- opts: { serverId?: string; now?: number } = {},
196
- ): ToolCallDecision {
197
- const now = opts.now ?? Date.now();
198
- if (scope.expiresAt <= now) return { allowed: false, reason: 'scope-expired' };
199
-
200
- if (!matchesScopeList(scope.grantedTools, toolId)) {
201
- return { allowed: false, reason: 'tool-not-in-scope' };
202
- }
203
- if (opts.serverId && !matchesScopeList(scope.grantedServers, opts.serverId)) {
204
- return { allowed: false, reason: 'server-not-in-scope' };
205
- }
206
- return { allowed: true };
207
- }
208
-
209
- /**
210
- * Verify an MCP server presented a valid credential before its response is
211
- * consumed. P1 ships a permissive default (any non-empty credential is
212
- * accepted) so the API is stable; P4 wires this to a real validator.
213
- *
214
- * Returns `false` on missing/empty credential; callers MUST treat `false`
215
- * as a hard reject (same rule as ADR-131 reject findings).
216
- */
217
- verifyServerAuth(serverId: string, credential: unknown): boolean {
218
- if (!serverId || typeof serverId !== 'string') return false;
219
- if (credential == null) return false;
220
- if (typeof credential === 'string' && credential.trim().length === 0) return false;
221
- return true;
222
- }
223
-
224
- /**
225
- * Record an action in the provenance buffer. P5 will route to telemetry;
226
- * P1 keeps the last N events for test inspection and post-incident audit.
227
- */
228
- recordAction(
229
- agentId: string,
230
- toolId: string,
231
- scope: AuthScope,
232
- outcome: 'allowed' | 'denied',
233
- reason?: string,
234
- ): void {
235
- const max = this.opts.provenanceBufferMax ?? 1024;
236
- this.provenance.push({ agentId, toolId, scope, outcome, reason, ts: Date.now() });
237
- if (this.provenance.length > max) this.provenance.splice(0, this.provenance.length - max);
238
- }
239
-
240
- /** Read-only view of recorded provenance for tests + audit CLI (P5). */
241
- getProvenance(): ReadonlyArray<{
242
- agentId: string;
243
- toolId: string;
244
- scope: AuthScope;
245
- outcome: 'allowed' | 'denied';
246
- reason?: string;
247
- ts: number;
248
- }> {
249
- return this.provenance.slice();
250
- }
251
- }
252
-
253
- // ─── helpers ────────────────────────────────────────────────────────────
254
-
255
- function subsetOrThrow(
256
- parent: ReadonlyArray<string>,
257
- requested: ReadonlyArray<string>,
258
- kind: 'tools' | 'servers',
259
- ): ReadonlyArray<string> {
260
- if (parent.includes('*')) return Array.from(new Set(requested));
261
- for (const item of requested) {
262
- if (!parent.includes(item) && item !== '*') {
263
- throw new AuthorizationPropagationError(
264
- 'scope-cannot-grow',
265
- `cannot grant ${kind} '${item}' — not in parent scope`,
266
- );
267
- }
268
- }
269
- // De-duplicate; preserve requested order
270
- const seen = new Set<string>();
271
- const out: string[] = [];
272
- for (const r of requested) if (!seen.has(r)) (seen.add(r), out.push(r));
273
- return out;
274
- }
275
-
276
- function matchesScopeList(list: ReadonlyArray<string>, item: string): boolean {
277
- if (list.includes('*')) return true;
278
- return list.includes(item);
279
- }