Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-ravens-observe.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 27 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export type {
LocalAnalysis,
SDKDetectionRequest,
SDKDetectionResponse,
OffensiveToolFamily,
OffensiveToolchainObservation,
FrameworkEvidenceObservation,
ProtectResult,
ProtectOptions,
SSRFCanary,
Expand All @@ -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`.
Expand Down
153 changes: 153 additions & 0 deletions packages/webdecoy/src/offensive-toolchain.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
});
148 changes: 148 additions & 0 deletions packages/webdecoy/src/offensive-toolchain.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, OffensiveToolFamily>> = 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<OffensiveToolchainEvidence> {
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<FrameworkEvidenceObservation> {
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<string> {
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<string> {
const canonical = evidence.map(
(value) =>
`${value.family_id.trim().toLowerCase()}\0${value.count}\0${value.sha256.trim().toLowerCase()}`
);
return fingerprintIDs(canonical);
}
Loading
Loading