@claude-flow/security 3.0.0-alpha.1 → 3.0.0-alpha.10

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 (115) hide show
  1. package/README.md +292 -234
  2. package/__tests__/acceptance/security-compliance.test.ts +674 -674
  3. package/__tests__/authorization-propagator.test.ts +155 -0
  4. package/__tests__/credential-generator.test.ts +310 -310
  5. package/__tests__/fixtures/configurations.ts +425 -419
  6. package/__tests__/fixtures/index.ts +21 -21
  7. package/__tests__/helpers/create-mock.ts +469 -469
  8. package/__tests__/helpers/index.ts +32 -32
  9. package/__tests__/input-validator.test.ts +382 -381
  10. package/__tests__/integration/security-flow.test.ts +606 -606
  11. package/__tests__/password-hasher.test.ts +239 -239
  12. package/__tests__/path-validator.test.ts +302 -302
  13. package/__tests__/plugin-integrity-verifier.test.ts +199 -0
  14. package/__tests__/safe-executor.test.ts +292 -292
  15. package/__tests__/token-generator.test.ts +371 -371
  16. package/__tests__/tool-output-guardrail.test.ts +256 -0
  17. package/__tests__/unit/credential-generator.test.ts +182 -182
  18. package/__tests__/unit/password-hasher.test.ts +359 -359
  19. package/__tests__/unit/path-validator.test.ts +509 -509
  20. package/__tests__/unit/safe-executor.test.ts +667 -667
  21. package/__tests__/unit/token-generator.test.ts +310 -310
  22. package/dist/authorization/propagator.d.ts +148 -0
  23. package/dist/authorization/propagator.d.ts.map +1 -0
  24. package/dist/authorization/propagator.js +182 -0
  25. package/dist/authorization/propagator.js.map +1 -0
  26. package/dist/credential-generator.js +9 -9
  27. package/dist/domain/services/security-domain-service.js +1 -1
  28. package/dist/domain/services/security-domain-service.js.map +1 -1
  29. package/dist/index.d.ts +4 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +11 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/password-hasher.d.ts.map +1 -1
  34. package/dist/password-hasher.js +8 -1
  35. package/dist/password-hasher.js.map +1 -1
  36. package/dist/plugins/integrity-verifier.d.ts +125 -0
  37. package/dist/plugins/integrity-verifier.d.ts.map +1 -0
  38. package/dist/plugins/integrity-verifier.js +186 -0
  39. package/dist/plugins/integrity-verifier.js.map +1 -0
  40. package/dist/safe-executor.d.ts +7 -0
  41. package/dist/safe-executor.d.ts.map +1 -1
  42. package/dist/safe-executor.js +21 -1
  43. package/dist/safe-executor.js.map +1 -1
  44. package/dist/tool-output-guardrail.d.ts +126 -0
  45. package/dist/tool-output-guardrail.d.ts.map +1 -0
  46. package/dist/tool-output-guardrail.js +257 -0
  47. package/dist/tool-output-guardrail.js.map +1 -0
  48. package/package.json +28 -28
  49. package/src/CVE-REMEDIATION.ts +251 -251
  50. package/src/application/index.ts +10 -10
  51. package/src/application/services/security-application-service.ts +193 -193
  52. package/src/authorization/propagator.ts +279 -0
  53. package/src/credential-generator.ts +368 -368
  54. package/src/domain/entities/security-context.ts +173 -173
  55. package/src/domain/index.ts +17 -17
  56. package/src/domain/services/security-domain-service.ts +296 -296
  57. package/src/index.ts +314 -271
  58. package/src/input-validator.ts +466 -466
  59. package/src/password-hasher.ts +277 -270
  60. package/src/path-validator.ts +525 -525
  61. package/src/plugins/integrity-verifier.ts +265 -0
  62. package/src/safe-executor.ts +546 -525
  63. package/src/token-generator.ts +463 -463
  64. package/src/tool-output-guardrail.ts +360 -0
  65. package/tmp.json +0 -0
  66. package/tsconfig.json +9 -9
  67. package/tsconfig.tsbuildinfo +1 -1
  68. package/vitest.config.ts +20 -0
  69. package/.agentic-flow/intelligence.json +0 -16
  70. package/__tests__/coverage/base.css +0 -224
  71. package/__tests__/coverage/block-navigation.js +0 -87
  72. package/__tests__/coverage/coverage-final.json +0 -11
  73. package/__tests__/coverage/favicon.png +0 -0
  74. package/__tests__/coverage/index.html +0 -161
  75. package/__tests__/coverage/lcov-report/base.css +0 -224
  76. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  77. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  78. package/__tests__/coverage/lcov-report/index.html +0 -161
  79. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  80. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  81. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  82. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  83. package/__tests__/coverage/lcov-report/src/CVE-REMEDIATION.ts.html +0 -838
  84. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  85. package/__tests__/coverage/lcov-report/src/application/services/security-application-service.ts.html +0 -664
  86. package/__tests__/coverage/lcov-report/src/credential-generator.ts.html +0 -1189
  87. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  88. package/__tests__/coverage/lcov-report/src/domain/entities/security-context.ts.html +0 -604
  89. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  90. package/__tests__/coverage/lcov-report/src/domain/services/security-domain-service.ts.html +0 -973
  91. package/__tests__/coverage/lcov-report/src/index.html +0 -206
  92. package/__tests__/coverage/lcov-report/src/input-validator.ts.html +0 -1483
  93. package/__tests__/coverage/lcov-report/src/password-hasher.ts.html +0 -895
  94. package/__tests__/coverage/lcov-report/src/path-validator.ts.html +0 -1660
  95. package/__tests__/coverage/lcov-report/src/safe-executor.ts.html +0 -1660
  96. package/__tests__/coverage/lcov-report/src/token-generator.ts.html +0 -1474
  97. package/__tests__/coverage/lcov.info +0 -3650
  98. package/__tests__/coverage/prettify.css +0 -1
  99. package/__tests__/coverage/prettify.js +0 -2
  100. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  101. package/__tests__/coverage/sorter.js +0 -210
  102. package/__tests__/coverage/src/CVE-REMEDIATION.ts.html +0 -838
  103. package/__tests__/coverage/src/application/services/index.html +0 -116
  104. package/__tests__/coverage/src/application/services/security-application-service.ts.html +0 -664
  105. package/__tests__/coverage/src/credential-generator.ts.html +0 -1189
  106. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  107. package/__tests__/coverage/src/domain/entities/security-context.ts.html +0 -604
  108. package/__tests__/coverage/src/domain/services/index.html +0 -116
  109. package/__tests__/coverage/src/domain/services/security-domain-service.ts.html +0 -973
  110. package/__tests__/coverage/src/index.html +0 -206
  111. package/__tests__/coverage/src/input-validator.ts.html +0 -1483
  112. package/__tests__/coverage/src/password-hasher.ts.html +0 -895
  113. package/__tests__/coverage/src/path-validator.ts.html +0 -1660
  114. package/__tests__/coverage/src/safe-executor.ts.html +0 -1660
  115. package/__tests__/coverage/src/token-generator.ts.html +0 -1474
@@ -1,193 +1,193 @@
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
+ /**
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
+ }
@@ -0,0 +1,279 @@
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
+ }