diff --git a/.changeset/quiet-ravens-observe.md b/.changeset/quiet-ravens-observe.md new file mode 100644 index 0000000..389c535 --- /dev/null +++ b/.changeset/quiet-ravens-observe.md @@ -0,0 +1,5 @@ +--- +'@webdecoy/node': minor +--- + +Add privacy-bounded model-plane offensive toolchain evidence and optional reviewed HexStrike AI orchestrator identity for WebDecoy correlation. diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index a52ea99..cc1e031 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -103,6 +103,33 @@ credential is sent. A presentation request is made only when the candidate is an exact local match for the inert token. Retrieval alone remains an ordinary decoy event, and this API never blocks or grants access. +### Correlate an offensive model toolchain + +Instrument an authorized model/MCP gateway with the reviewed helper. It maps +known tool names into generic families and sends only bounded counts and +digests. Raw prompts, arguments, results, targets, credentials, and run IDs are +not included. Use a deployment-held random secret of at least 32 characters for +`correlationSecret`; do not reuse an API key. + +```ts +const result = await wd.reportOffensiveToolchain({ + sensor: 'mcp-gateway', + runId: internalRunId, + correlationSecret: process.env.WEBDECOY_CORRELATION_SECRET!, + invocations: [ + { tool: 'nmap_scan', redactedArgumentCount: 2 }, + { tool: 'nuclei_scan', redactedArgumentCount: 1 }, + ], +}); +``` + +One tool family is retained for coverage but does not create a correlation. +Two or more reviewed families can create a generic toolchain association. Set +`orchestrator: 'hexstrike_ai'` only inside an integration that has independently +verified the official `hexstrike-ai-mcp` orchestrator; common Nmap or Nuclei use +alone never becomes HexStrike attribution. This API records evidence and never +blocks or grants access. + ### Monitor first `protect()` only returns a decision. It never writes a response, so nothing is blocked until your code acts on `decision.allowed`. The framework adapters and `createFetchGuard()` follow the same rule: they start in **monitor mode** (`mode: 'monitor'`), record the decision and serve every request. Set `mode: 'enforce'` only after you have reviewed what would have been blocked. diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 4a9f0b7..4de9607 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -33,6 +33,9 @@ export type { LocalAnalysis, SDKDetectionRequest, SDKDetectionResponse, + OffensiveToolFamily, + OffensiveToolchainObservation, + FrameworkEvidenceObservation, ProtectResult, ProtectOptions, SSRFCanary, @@ -45,6 +48,13 @@ export type { HoneyCredentialReceipt, } from './types'; +export { createOffensiveToolchainEvidence } from './offensive-toolchain'; +export type { + OffensiveToolInvocation, + OffensiveToolchainEvidenceInput, + OffensiveToolchainEvidence, +} from './offensive-toolchain'; + // The decision `protect()` returns. Exported as a value because the class // carries the narrowing helpers (`isDenied()`, `deniedBy()`) that keep an // adapter's blocked path from being typed `any`. diff --git a/packages/webdecoy/src/offensive-toolchain.test.ts b/packages/webdecoy/src/offensive-toolchain.test.ts new file mode 100644 index 0000000..fafb37b --- /dev/null +++ b/packages/webdecoy/src/offensive-toolchain.test.ts @@ -0,0 +1,153 @@ +import { createHash, createHmac, webcrypto } from 'crypto'; +import { createOffensiveToolchainEvidence } from './offensive-toolchain'; +import { WebDecoy } from './sdk'; + +const correlationSecret = 'test-correlation-secret-at-least-32-characters'; + +beforeAll(() => { + if (!globalThis.crypto) Object.defineProperty(globalThis, 'crypto', { value: webcrypto }); +}); + +describe('createOffensiveToolchainEvidence', () => { + it('returns only bounded generic families and keyed digests', async () => { + const evidence = await createOffensiveToolchainEvidence({ + sensor: 'mcp-proxy', + runId: 'customer-secret-run-id', + correlationSecret, + invocations: [ + { tool: 'nmap_scan', redactedArgumentCount: 2 }, + { tool: 'nuclei_scan', redactedArgumentCount: 1 }, + { tool: 'private_custom_tool', redactedArgumentCount: 99 }, + ], + }); + expect(evidence.framework_evidence).toBeUndefined(); + expect(evidence.offensive_toolchain).toMatchObject({ + schema_version: 1, + registry_revision: 1, + plane: 'model_api', + sensor: 'mcp-proxy', + tool_families: ['network_reconnaissance', 'vulnerability_scanning'], + invocation_count: 2, + redacted_argument_count: 3, + dropped_tool_count: 1, + }); + expect(evidence.offensive_toolchain.run_correlation_id).toBe( + createHmac('sha256', correlationSecret).update('customer-secret-run-id').digest('hex') + ); + expect(evidence.offensive_toolchain.family_set_sha256).toBe( + createHash('sha256').update('network_reconnaissance\nvulnerability_scanning').digest('hex') + ); + const wire = JSON.stringify(evidence); + for (const forbidden of [ + 'customer-secret-run-id', + correlationSecret, + 'private_custom_tool', + 'arguments', + 'targets', + ]) { + expect(wire).not.toContain(forbidden); + } + }); + + it('adds HexStrike identity only when explicitly requested', async () => { + const evidence = await createOffensiveToolchainEvidence({ + sensor: 'hexstrike-sidecar', + runId: 'run-1', + correlationSecret, + orchestrator: 'hexstrike_ai', + invocations: [{ tool: 'nmap_scan' }, { tool: 'metasploit_run' }], + }); + expect(evidence.framework_evidence).toMatchObject({ + schema_version: 1, + registry_revision: 5, + framework: 'hexstrike_ai', + plane: 'model_api', + evidence: [{ family_id: 'orchestrator_identity', count: 1 }], + }); + expect(evidence.framework_evidence?.evidence[0].sha256).toBe( + '18ff7e9eabdbb58d0a3b4330674499a234b0d49cd3f3b3efbe16713a8c5d5e79' + ); + expect(evidence.framework_evidence?.observation_sha256).toBe( + 'c2d8db3fd71f1f8a6502c0c326f9f439f5563f776cae57377ecbf58c5a3ffb3f' + ); + }); + + it('does not manufacture coordination from one family or unknown tools', async () => { + const oneFamily = await createOffensiveToolchainEvidence({ + sensor: 'mcp-proxy', + runId: 'run-1', + correlationSecret, + invocations: [{ tool: 'nmap_scan' }, { tool: 'nmap_advanced_scan' }, { tool: 'unknown' }], + }); + expect(oneFamily.offensive_toolchain.tool_families).toEqual(['network_reconnaissance']); + expect(oneFamily.offensive_toolchain.invocation_count).toBe(2); + expect(oneFamily.offensive_toolchain.dropped_tool_count).toBe(1); + + await expect( + createOffensiveToolchainEvidence({ + sensor: 'mcp-proxy', + runId: 'run-2', + correlationSecret, + invocations: [{ tool: 'unknown' }], + }) + ).rejects.toThrow('no reviewed offensive tools'); + }); + + it('rejects weak correlation secrets and unbounded reporter labels', async () => { + const base = { + sensor: 'mcp-proxy', + runId: 'run-1', + correlationSecret, + invocations: [{ tool: 'nmap_scan' }], + }; + await expect( + createOffensiveToolchainEvidence({ ...base, correlationSecret: 'too-short' }) + ).rejects.toThrow('correlationSecret'); + await expect( + createOffensiveToolchainEvidence({ ...base, sensor: 'customer email@example.com' }) + ).rejects.toThrow('stable identifier'); + await expect( + createOffensiveToolchainEvidence({ + ...base, + invocations: [{ tool: 'x'.repeat(129) }], + }) + ).rejects.toThrow('tool must be 1-128 characters'); + }); + + it('reports the bounded envelope through the authenticated SDK route', async () => { + const calls: unknown[] = []; + const previousFetch = globalThis.fetch; + globalThis.fetch = jest.fn(async (_url: string | URL | Request, init?: RequestInit) => { + calls.push(JSON.parse(String(init?.body))); + return new Response( + JSON.stringify({ + decision: 'allow', + confidence: 90, + threat_level: 'LOW', + bot_detected: true, + detection_id: 'toolchain-detection', + rule_enforced: false, + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + }) as typeof fetch; + try { + const sdk = new WebDecoy({ apiKey: 'sk_test_toolchain' }); + const response = await sdk.reportOffensiveToolchain({ + sensor: 'mcp-proxy', + runId: 'raw-run-id', + correlationSecret, + invocations: [{ tool: 'nmap_scan' }, { tool: 'nuclei_scan' }], + }); + expect(response.detection_id).toBe('toolchain-detection'); + expect(calls).toHaveLength(1); + expect((calls[0] as { request_metadata: { ip: string } }).request_metadata.ip).toBe('0.0.0.0'); + const wire = JSON.stringify(calls[0]); + expect(wire).toContain('offensive_toolchain'); + expect(wire).not.toContain('raw-run-id'); + expect(wire).not.toContain(correlationSecret); + } finally { + globalThis.fetch = previousFetch; + } + }); +}); diff --git a/packages/webdecoy/src/offensive-toolchain.ts b/packages/webdecoy/src/offensive-toolchain.ts new file mode 100644 index 0000000..e41e987 --- /dev/null +++ b/packages/webdecoy/src/offensive-toolchain.ts @@ -0,0 +1,148 @@ +import { hmacSha256Hex, sha256Hex } from './webcrypto'; +import type { + FrameworkEvidenceObservation, + OffensiveToolFamily, + OffensiveToolchainObservation, +} from './types'; + +const TOOLCHAIN_REGISTRY_REVISION = 1; +const FRAMEWORK_REGISTRY_REVISION = 5; + +const reviewedTools: Readonly> = Object.freeze({ + nmap_scan: 'network_reconnaissance', + nmap_advanced_scan: 'network_reconnaissance', + masscan_scan: 'network_reconnaissance', + nuclei_scan: 'vulnerability_scanning', + sqlmap_scan: 'injection_testing', + metasploit_run: 'exploitation', +}); + +export interface OffensiveToolInvocation { + /** Reviewed tool identifier. Unknown identifiers are counted and dropped. */ + tool: string; + /** Number of argument values the sensor removed before reporting. */ + redactedArgumentCount?: number; +} + +export interface OffensiveToolchainEvidenceInput { + /** Stable name for the authenticated model-plane sensor, at most 128 characters. */ + sensor: string; + /** Raw run ID used only as HMAC input. It is never returned. */ + runId: string; + /** Deployment-held HMAC secret used to pseudonymize run IDs. */ + correlationSecret: string; + invocations: readonly OffensiveToolInvocation[]; + /** Set only when instrumenting the official HexStrike AI MCP orchestrator. */ + orchestrator?: 'hexstrike_ai'; +} + +export interface OffensiveToolchainEvidence { + offensive_toolchain: OffensiveToolchainObservation; + framework_evidence?: FrameworkEvidenceObservation; +} + +/** + * Build the strict model-plane evidence accepted by WebDecoy ingest. + * + * Tool arguments, results, prompts, credentials and targets are intentionally + * absent from this API. Unknown tool names are counted and discarded. One + * recognized family can be reported for coverage but does not correlate; the + * backend requires coordinated use of at least two reviewed families. + */ +export async function createOffensiveToolchainEvidence( + input: OffensiveToolchainEvidenceInput +): Promise { + const sensor = input.sensor.trim(); + if (!/^[a-z0-9][a-z0-9_.-]{0,127}$/i.test(sensor)) { + throw new Error('sensor must be a 1-128 character stable identifier'); + } + if (!input.runId || input.runId.length > 1024) { + throw new Error('runId must be 1-1024 characters'); + } + if (input.correlationSecret.length < 32 || input.correlationSecret.length > 4096) { + throw new Error('correlationSecret must be 32-4096 characters'); + } + if ( + !Array.isArray(input.invocations) || + input.invocations.length === 0 || + input.invocations.length > 256 + ) { + throw new Error('invocations must contain 1-256 entries'); + } + + const sequence: OffensiveToolFamily[] = []; + let redactedArgumentCount = 0; + let droppedToolCount = 0; + for (const invocation of input.invocations) { + if (!invocation.tool || invocation.tool.length > 128) { + throw new Error('tool must be 1-128 characters'); + } + const redacted = invocation.redactedArgumentCount ?? 0; + if (!Number.isInteger(redacted) || redacted < 0 || redacted > 1024) { + throw new Error('redactedArgumentCount must be an integer from 0 through 1024'); + } + const family = reviewedTools[invocation.tool.trim().toLowerCase()]; + if (!family) { + droppedToolCount++; + continue; + } + sequence.push(family); + redactedArgumentCount += redacted; + if (redactedArgumentCount > 1024) throw new Error('redacted argument count exceeds 1024'); + } + if (sequence.length === 0) throw new Error('no reviewed offensive tools were observed'); + + const families = [...new Set(sequence)].sort(); + const offensive_toolchain: OffensiveToolchainObservation = { + schema_version: 1, + registry_revision: TOOLCHAIN_REGISTRY_REVISION, + plane: 'model_api', + sensor, + run_correlation_id: await hmacSha256Hex(input.correlationSecret, input.runId), + tool_families: families, + invocation_count: sequence.length, + family_set_sha256: await fingerprintIDs(families), + sequence_sha256: await sha256Hex(sequence.join('\n')), + redacted_argument_count: redactedArgumentCount, + dropped_tool_count: droppedToolCount, + }; + + const evidence: OffensiveToolchainEvidence = { offensive_toolchain }; + if (input.orchestrator === 'hexstrike_ai') { + evidence.framework_evidence = await hexStrikeEvidence(); + } + return evidence; +} + +async function hexStrikeEvidence(): Promise { + const family = { + family_id: 'orchestrator_identity', + count: 1, + sha256: await fingerprintIDs(['hexstrike-ai-mcp']), + }; + return { + schema_version: 1, + registry_revision: FRAMEWORK_REGISTRY_REVISION, + framework: 'hexstrike_ai', + plane: 'model_api', + evidence: [family], + observation_sha256: await fingerprintEvidence([family]), + }; +} + +async function fingerprintIDs(values: readonly string[]): Promise { + const canonical = [ + ...new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean)), + ].sort(); + return sha256Hex(canonical.join('\n')); +} + +async function fingerprintEvidence( + evidence: ReadonlyArray<{ family_id: string; count: number; sha256: string }> +): Promise { + const canonical = evidence.map( + (value) => + `${value.family_id.trim().toLowerCase()}\0${value.count}\0${value.sha256.trim().toLowerCase()}` + ); + return fingerprintIDs(canonical); +} diff --git a/packages/webdecoy/src/sdk.ts b/packages/webdecoy/src/sdk.ts index d45e682..eebbaf5 100644 --- a/packages/webdecoy/src/sdk.ts +++ b/packages/webdecoy/src/sdk.ts @@ -40,6 +40,8 @@ import { HoneyCredentialReceipt, } from './types'; import { hmacSha256Hex, randomHex, timingSafeEqualStr } from './webcrypto'; +import { createOffensiveToolchainEvidence } from './offensive-toolchain'; +import type { OffensiveToolchainEvidenceInput } from './offensive-toolchain'; export class WebDecoy { private client: WebDecoyClient | null; @@ -404,6 +406,41 @@ export class WebDecoy { return hmacSha256Hex(this.config.apiKey!, `webdecoy/honey-credential/v1\u0000${tokenId}\u0000${bearer}`); } + /** + * Report a privacy-bounded model-plane tool run. The helper sends only + * reviewed generic families, counts, and digests; it never sends prompts, + * arguments, results, credentials, targets, or the raw run ID. + */ + async reportOffensiveToolchain( + input: OffensiveToolchainEvidenceInput + ): Promise { + if (!this.client) { + throw new Error('An apiKey is required to report an offensive toolchain'); + } + const evidence = await createOffensiveToolchainEvidence(input); + return this.client.detect({ + request_metadata: { + method: 'MODEL', + path: '/model-toolchain', + // The existing SDK route requires an address. Model-plane evidence has + // no target client IP, so use the unspecified address rather than + // inventing an identity that could enter actor correlation. + ip: '0.0.0.0', + headers: {}, + timestamp: Date.now(), + }, + local_analysis: { + suspicious_headers: false, + missing_sec_ch_ua: false, + datacenter_ip: false, + local_score: 0, + needs_verification: true, + flags: ['model_plane_toolchain'], + }, + ...evidence, + }); + } + /** * Whether this SDK instance has filter rules that need async enrichment */ diff --git a/packages/webdecoy/src/types.ts b/packages/webdecoy/src/types.ts index 219eec0..0144a97 100644 --- a/packages/webdecoy/src/types.ts +++ b/packages/webdecoy/src/types.ts @@ -306,6 +306,40 @@ export interface LocalAnalysis { export interface SDKDetectionRequest { request_metadata: RequestMetadata; local_analysis: LocalAnalysis; + /** Privacy-bounded model-plane tool orchestration; never raw arguments or results. */ + offensive_toolchain?: OffensiveToolchainObservation; + /** Reviewed framework identity evidence produced by an SDK helper. */ + framework_evidence?: FrameworkEvidenceObservation; +} + +export type OffensiveToolFamily = + | 'network_reconnaissance' + | 'vulnerability_scanning' + | 'injection_testing' + | 'exploitation'; + +export interface OffensiveToolchainObservation { + schema_version: 1; + registry_revision: 1; + plane: 'model_api'; + sensor: string; + /** HMAC-SHA-256 digest; never the raw run or conversation ID. */ + run_correlation_id: string; + tool_families: OffensiveToolFamily[]; + invocation_count: number; + family_set_sha256: string; + sequence_sha256: string; + redacted_argument_count: number; + dropped_tool_count: number; +} + +export interface FrameworkEvidenceObservation { + schema_version: 1; + registry_revision: number; + framework: string; + plane: 'model_api'; + evidence: Array<{ family_id: string; count: number; sha256: string }>; + observation_sha256: string; } /**