@claude-flow/security 3.0.0-alpha.8 → 3.0.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-flow/data/pending-insights.jsonl +6 -0
- package/.claude-flow/neural/stats.json +6 -0
- package/__tests__/authorization-propagator.test.ts +155 -0
- package/__tests__/plugin-integrity-verifier.test.ts +199 -0
- package/__tests__/tool-output-guardrail.test.ts +256 -0
- package/dist/authorization/propagator.d.ts +148 -0
- package/dist/authorization/propagator.d.ts.map +1 -0
- package/dist/authorization/propagator.js +182 -0
- package/dist/authorization/propagator.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/plugins/integrity-verifier.d.ts +125 -0
- package/dist/plugins/integrity-verifier.d.ts.map +1 -0
- package/dist/plugins/integrity-verifier.js +186 -0
- package/dist/plugins/integrity-verifier.js.map +1 -0
- package/dist/tool-output-guardrail.d.ts +126 -0
- package/dist/tool-output-guardrail.d.ts.map +1 -0
- package/dist/tool-output-guardrail.js +257 -0
- package/dist/tool-output-guardrail.js.map +1 -0
- package/package.json +1 -1
- package/ruvector.db +0 -0
- package/src/authorization/propagator.ts +279 -0
- package/src/index.ts +43 -0
- package/src/plugins/integrity-verifier.ts +265 -0
- package/src/tool-output-guardrail.ts +360 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -109,6 +109,49 @@ export {
|
|
|
109
109
|
type VerificationCode,
|
|
110
110
|
} from './token-generator.js';
|
|
111
111
|
|
|
112
|
+
// Tool-Output Guardrail (ADR-131 — closes OWASP ASI01 gap; ruvnet/ruflo#2149)
|
|
113
|
+
export {
|
|
114
|
+
ToolOutputGuardrail,
|
|
115
|
+
createToolOutputGuardrail,
|
|
116
|
+
isToolOutputSafe,
|
|
117
|
+
type GuardrailConfig,
|
|
118
|
+
type GuardrailResult,
|
|
119
|
+
type GuardrailAction,
|
|
120
|
+
type InjectionFinding,
|
|
121
|
+
type InjectionSeverity,
|
|
122
|
+
type InjectionCategory,
|
|
123
|
+
} from './tool-output-guardrail.js';
|
|
124
|
+
|
|
125
|
+
// Agent Authorization Propagation (ADR-144 P1 — ruvnet/ruflo#2248)
|
|
126
|
+
// Action-layer: SendMessage envelope + per-action scope check + MCP server
|
|
127
|
+
// identity probe. Wraps the comms layer in P2; wraps the dispatcher in P3.
|
|
128
|
+
export {
|
|
129
|
+
AgentAuthorizationPropagator,
|
|
130
|
+
AuthorizationPropagationError,
|
|
131
|
+
makeLegacyPermissiveScope,
|
|
132
|
+
type AuthScope,
|
|
133
|
+
type SendMessageEnvelope,
|
|
134
|
+
type ToolCallDecision,
|
|
135
|
+
} from './authorization/propagator.js';
|
|
136
|
+
|
|
137
|
+
// Plugin Integrity Verifier (ADR-145 P1 — ruvnet/ruflo#2254)
|
|
138
|
+
// Install-layer: Ed25519 signature verification + trust-anchor allowlist.
|
|
139
|
+
// Stage-2 semantic-intent scan (SCH defence) lands in P2.
|
|
140
|
+
export {
|
|
141
|
+
PluginIntegrityVerifier,
|
|
142
|
+
canonicalize,
|
|
143
|
+
hashManifest,
|
|
144
|
+
fingerprint,
|
|
145
|
+
findAnchor,
|
|
146
|
+
type PluginManifest,
|
|
147
|
+
type SignedPluginManifest,
|
|
148
|
+
type TrustAnchor,
|
|
149
|
+
type TrustAnchors,
|
|
150
|
+
type VerificationStatus,
|
|
151
|
+
type VerificationResult,
|
|
152
|
+
type VerifierConfig,
|
|
153
|
+
} from './plugins/integrity-verifier.js';
|
|
154
|
+
|
|
112
155
|
// ============================================================================
|
|
113
156
|
// Convenience Factory Functions
|
|
114
157
|
// ============================================================================
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PluginIntegrityVerifier — install-layer security for plugin supply chain.
|
|
3
|
+
*
|
|
4
|
+
* Implements P1 of ADR-145 (ruvnet/ruflo#2254): Stage-1 Ed25519 signature
|
|
5
|
+
* verification at `plugins install`. Stage-2 (semantic-intent scan against
|
|
6
|
+
* SCH attacks) lands in P2; per-namespace write ACLs land in P3-P4.
|
|
7
|
+
*
|
|
8
|
+
* Threat model
|
|
9
|
+
* ------------
|
|
10
|
+
* Ruflo's plugin install path fetches manifests from IPFS via Pinata with
|
|
11
|
+
* NO signature verification and NO intent analysis. Two attacks land today:
|
|
12
|
+
*
|
|
13
|
+
* - DDIPE (arXiv:2604.03081): malicious logic embedded in plugin docs and
|
|
14
|
+
* config templates. 11.6-33.5% bypass rate across 4 frameworks/5 models;
|
|
15
|
+
* 2.5% evade both detection and alignment. Stage-1 signing blocks the
|
|
16
|
+
* static-payload variants.
|
|
17
|
+
*
|
|
18
|
+
* - SCH (arXiv:2605.14460): malicious intent wrapped as natural-language
|
|
19
|
+
* "compliance rules" in plugin descriptions. The agent generates the
|
|
20
|
+
* harmful code at runtime — no static payload exists. 77.67% breach
|
|
21
|
+
* success, 0.00% scanner detection. Stage-2 (P2) catches this; Stage-1
|
|
22
|
+
* does not.
|
|
23
|
+
*
|
|
24
|
+
* Scope (P1)
|
|
25
|
+
* ----------
|
|
26
|
+
* - Ed25519 signature verification of a detached signature over the manifest.
|
|
27
|
+
* - Trust-anchor allowlist: the publisher's signing key fingerprint must be
|
|
28
|
+
* in `trust-anchors.json`, gated on CODEOWNERS review.
|
|
29
|
+
* - Backwards compatible: default mode is warn-only. `CLAUDE_FLOW_STRICT_PLUGINS=true`
|
|
30
|
+
* makes verification a hard gate.
|
|
31
|
+
*
|
|
32
|
+
* Non-goals (P1)
|
|
33
|
+
* --------------
|
|
34
|
+
* - Semantic intent scan (SCH defence). Lands in P2 with a pattern-rule
|
|
35
|
+
* fallback for environments without LLM credentials.
|
|
36
|
+
* - Sandboxing the plugin runtime. Orthogonal blast-radius concern.
|
|
37
|
+
*
|
|
38
|
+
* Reference: ADR-145, arXiv:2605.14460 (SCH), arXiv:2604.03081 (DDIPE),
|
|
39
|
+
* arXiv:2604.16548 (Mnemonic Sovereignty survey).
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
import { createHash } from 'node:crypto';
|
|
43
|
+
import * as nodeCrypto from 'node:crypto';
|
|
44
|
+
|
|
45
|
+
export interface PluginManifest {
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly version: string;
|
|
48
|
+
/** Anything else; only `id` + `version` matter for the integrity hash. */
|
|
49
|
+
readonly [extra: string]: unknown;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SignedPluginManifest {
|
|
53
|
+
readonly manifest: PluginManifest;
|
|
54
|
+
/** Hex-encoded SHA-256 of the canonical JSON serialisation of manifest. */
|
|
55
|
+
readonly manifestHash: string;
|
|
56
|
+
/** Hex-encoded detached Ed25519 signature over `manifestHash` bytes. */
|
|
57
|
+
readonly signature: string;
|
|
58
|
+
/** Hex-encoded Ed25519 public key of the signer. */
|
|
59
|
+
readonly publicKey: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface TrustAnchor {
|
|
63
|
+
/** Hex-encoded Ed25519 public key the publisher signs with. */
|
|
64
|
+
readonly publicKey: string;
|
|
65
|
+
/** Human-readable owner — for audit, not for trust decisions. */
|
|
66
|
+
readonly owner: string;
|
|
67
|
+
/** Optional ISO 8601 date after which this anchor is no longer trusted. */
|
|
68
|
+
readonly expiresAt?: string;
|
|
69
|
+
/** Optional plugin id glob this anchor is authoritative for (e.g. `@claude-flow/*`). */
|
|
70
|
+
readonly scope?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface TrustAnchors {
|
|
74
|
+
readonly version: 1;
|
|
75
|
+
readonly anchors: ReadonlyArray<TrustAnchor>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type VerificationStatus =
|
|
79
|
+
| 'pass'
|
|
80
|
+
| 'signature-missing'
|
|
81
|
+
| 'signature-invalid'
|
|
82
|
+
| 'manifest-hash-mismatch'
|
|
83
|
+
| 'unknown-signer'
|
|
84
|
+
| 'signer-expired'
|
|
85
|
+
| 'signer-out-of-scope';
|
|
86
|
+
|
|
87
|
+
export interface VerificationResult {
|
|
88
|
+
readonly status: VerificationStatus;
|
|
89
|
+
readonly pluginId: string;
|
|
90
|
+
readonly signerFingerprint?: string;
|
|
91
|
+
/** Verification timestamp — useful for telemetry correlation. */
|
|
92
|
+
readonly ts: number;
|
|
93
|
+
/** Operator-facing detail; do not parse — log only. */
|
|
94
|
+
readonly detail?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface VerifierConfig {
|
|
98
|
+
readonly trustAnchors: TrustAnchors;
|
|
99
|
+
/**
|
|
100
|
+
* When true, `verify` returns the actual failure status. When false (legacy
|
|
101
|
+
* mode), `verify` returns the failure status BUT callers may choose to
|
|
102
|
+
* proceed with a warning — the strictness gate lives at the caller, not
|
|
103
|
+
* here, so the verifier itself is always pure.
|
|
104
|
+
*/
|
|
105
|
+
readonly strict?: boolean;
|
|
106
|
+
/** Optional now-provider for tests. */
|
|
107
|
+
readonly now?: () => number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Canonical JSON serialisation for hashing. Deterministic key ordering at
|
|
112
|
+
* every nesting level. Pure; identical input → identical output bytes.
|
|
113
|
+
*/
|
|
114
|
+
export function canonicalize(value: unknown): string {
|
|
115
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
116
|
+
if (Array.isArray(value)) return '[' + value.map(canonicalize).join(',') + ']';
|
|
117
|
+
const obj = value as Record<string, unknown>;
|
|
118
|
+
const keys = Object.keys(obj).sort();
|
|
119
|
+
return '{' + keys.map(k => JSON.stringify(k) + ':' + canonicalize(obj[k])).join(',') + '}';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Hex-encoded SHA-256 of the canonical-JSON manifest. */
|
|
123
|
+
export function hashManifest(manifest: PluginManifest): string {
|
|
124
|
+
return createHash('sha256').update(canonicalize(manifest)).digest('hex');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Short fingerprint for telemetry — first 16 hex chars of the key. */
|
|
128
|
+
export function fingerprint(publicKey: string): string {
|
|
129
|
+
return publicKey.slice(0, 16);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Find the trust anchor that vouches for a manifest. Returns the matched
|
|
134
|
+
* anchor (with anchor.publicKey === signer.publicKey) or null.
|
|
135
|
+
*
|
|
136
|
+
* Scope-matching uses a minimal glob: `*` at the end of the scope string
|
|
137
|
+
* matches any suffix. Empty/missing scope matches every plugin id.
|
|
138
|
+
*/
|
|
139
|
+
export function findAnchor(
|
|
140
|
+
anchors: ReadonlyArray<TrustAnchor>,
|
|
141
|
+
pluginId: string,
|
|
142
|
+
signerPublicKey: string,
|
|
143
|
+
now: number,
|
|
144
|
+
): TrustAnchor | null {
|
|
145
|
+
for (const a of anchors) {
|
|
146
|
+
if (a.publicKey !== signerPublicKey) continue;
|
|
147
|
+
if (a.expiresAt && new Date(a.expiresAt).getTime() <= now) continue;
|
|
148
|
+
if (!a.scope || a.scope === '*' || a.scope === pluginId) return a;
|
|
149
|
+
if (a.scope.endsWith('*') && pluginId.startsWith(a.scope.slice(0, -1))) return a;
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* `PluginIntegrityVerifier` — Stage-1 verifier (signature + trust anchor).
|
|
156
|
+
*
|
|
157
|
+
* Pure-ish: holds the trust-anchor list and clock, no other state. Safe to
|
|
158
|
+
* construct per-invocation or share.
|
|
159
|
+
*/
|
|
160
|
+
export class PluginIntegrityVerifier {
|
|
161
|
+
constructor(private readonly config: VerifierConfig) {}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Verify a signed manifest. Returns the verification status; the caller
|
|
165
|
+
* decides what to do with `signature-missing` / `manifest-hash-mismatch`
|
|
166
|
+
* etc. based on its strict-mode policy.
|
|
167
|
+
*/
|
|
168
|
+
async verify(signed: SignedPluginManifest): Promise<VerificationResult> {
|
|
169
|
+
const now = (this.config.now ?? Date.now)();
|
|
170
|
+
const pluginId = signed.manifest?.id ?? '<unknown>';
|
|
171
|
+
|
|
172
|
+
if (!signed.signature || !signed.publicKey) {
|
|
173
|
+
return { status: 'signature-missing', pluginId, ts: now };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Re-hash the manifest and compare to the signed hash.
|
|
177
|
+
const recomputed = hashManifest(signed.manifest);
|
|
178
|
+
if (recomputed !== signed.manifestHash) {
|
|
179
|
+
return {
|
|
180
|
+
status: 'manifest-hash-mismatch',
|
|
181
|
+
pluginId,
|
|
182
|
+
signerFingerprint: fingerprint(signed.publicKey),
|
|
183
|
+
ts: now,
|
|
184
|
+
detail: `expected ${signed.manifestHash}, got ${recomputed}`,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Find a trust anchor that vouches for this signer + plugin.
|
|
189
|
+
const anchor = findAnchor(this.config.trustAnchors.anchors, pluginId, signed.publicKey, now);
|
|
190
|
+
if (!anchor) {
|
|
191
|
+
return {
|
|
192
|
+
status: 'unknown-signer',
|
|
193
|
+
pluginId,
|
|
194
|
+
signerFingerprint: fingerprint(signed.publicKey),
|
|
195
|
+
ts: now,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Ed25519 verify. Probe @noble/ed25519 (already a workspace dep); fall
|
|
200
|
+
// back to the failure status if it isn't resolvable in this environment
|
|
201
|
+
// (mirrors verify.mjs's #1880 precondition pattern).
|
|
202
|
+
const ed = await loadEd25519();
|
|
203
|
+
if (!ed) {
|
|
204
|
+
return {
|
|
205
|
+
status: 'signature-invalid',
|
|
206
|
+
pluginId,
|
|
207
|
+
signerFingerprint: fingerprint(signed.publicKey),
|
|
208
|
+
ts: now,
|
|
209
|
+
detail: '@noble/ed25519 not available — cannot verify',
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Required by @noble/ed25519 v2 for sync sha512.
|
|
214
|
+
if (!ed.etc.sha512Sync) {
|
|
215
|
+
ed.etc.sha512Sync = (...m: Uint8Array[]): Uint8Array => {
|
|
216
|
+
const h = nodeCrypto.createHash('sha512');
|
|
217
|
+
for (const x of m) h.update(x);
|
|
218
|
+
return h.digest();
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let ok = false;
|
|
223
|
+
try {
|
|
224
|
+
const sigBytes = hexToBytes(signed.signature);
|
|
225
|
+
const msgBytes = hexToBytes(signed.manifestHash);
|
|
226
|
+
const pubBytes = hexToBytes(signed.publicKey);
|
|
227
|
+
ok = await ed.verify(sigBytes, msgBytes, pubBytes);
|
|
228
|
+
} catch {
|
|
229
|
+
ok = false;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!ok) {
|
|
233
|
+
return {
|
|
234
|
+
status: 'signature-invalid',
|
|
235
|
+
pluginId,
|
|
236
|
+
signerFingerprint: fingerprint(signed.publicKey),
|
|
237
|
+
ts: now,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return { status: 'pass', pluginId, signerFingerprint: fingerprint(signed.publicKey), ts: now };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ─── helpers ────────────────────────────────────────────────────────────
|
|
246
|
+
|
|
247
|
+
function hexToBytes(hex: string): Uint8Array {
|
|
248
|
+
const out = new Uint8Array(hex.length >>> 1);
|
|
249
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(i * 2, 2), 16);
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
interface NobleEd25519 {
|
|
254
|
+
verify(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array): Promise<boolean>;
|
|
255
|
+
etc: { sha512Sync?: (...m: Uint8Array[]) => Uint8Array };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function loadEd25519(): Promise<NobleEd25519 | null> {
|
|
259
|
+
try {
|
|
260
|
+
const mod = await import('@noble/ed25519');
|
|
261
|
+
return mod as unknown as NobleEd25519;
|
|
262
|
+
} catch {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
}
|