@stackwright-pro/mcp 0.2.0-alpha.40 → 0.2.0-alpha.49
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/dist/integrity.d.mts +29 -1
- package/dist/integrity.d.ts +29 -1
- package/dist/integrity.js +46 -8
- package/dist/integrity.js.map +1 -1
- package/dist/integrity.mjs +45 -8
- package/dist/integrity.mjs.map +1 -1
- package/dist/server.js +813 -147
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +826 -144
- package/dist/server.mjs.map +1 -1
- package/package.json +6 -6
package/dist/integrity.d.mts
CHANGED
|
@@ -27,6 +27,34 @@ interface VerifyAllOttersResult {
|
|
|
27
27
|
* canonical checksums. Returns lists of verified, failed, and unknown files.
|
|
28
28
|
*/
|
|
29
29
|
declare function verifyAllOtters(otterDir: string): VerifyAllOttersResult;
|
|
30
|
+
/**
|
|
31
|
+
* Structured audit event parameters for an integrity failure.
|
|
32
|
+
* Kept as a plain interface so callers can pass partial results without
|
|
33
|
+
* constructing the full VerifyAllOttersResult.
|
|
34
|
+
*/
|
|
35
|
+
interface IntegrityAuditEvent {
|
|
36
|
+
otterDir: string;
|
|
37
|
+
failed: Array<{
|
|
38
|
+
filename: string;
|
|
39
|
+
error: string;
|
|
40
|
+
}>;
|
|
41
|
+
unknown: string[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Emit a structured INTEGRITY_FAIL audit event to stderr.
|
|
45
|
+
*
|
|
46
|
+
* Writes a single line to process.stderr in the format:
|
|
47
|
+
* INTEGRITY_FAIL {"level":"AUDIT","event":"INTEGRITY_FAIL",...}
|
|
48
|
+
*
|
|
49
|
+
* The line prefix "INTEGRITY_FAIL" (without JSON) allows log shippers
|
|
50
|
+
* (FluentBit, syslog, CloudWatch Logs, Splunk) to match and route the
|
|
51
|
+
* event to a dedicated audit stream using a simple string filter, even
|
|
52
|
+
* before attempting JSON parsing.
|
|
53
|
+
*
|
|
54
|
+
* Exported for unit testing. Do not call directly in production code —
|
|
55
|
+
* use registerIntegrityTools() which calls this automatically.
|
|
56
|
+
*/
|
|
57
|
+
declare function emitIntegrityAuditEvent(params: IntegrityAuditEvent): void;
|
|
30
58
|
declare function registerIntegrityTools(server: McpServer): void;
|
|
31
59
|
|
|
32
|
-
export { type VerifyAllOttersResult, type VerifyOtterFileResult, computeSha256, registerIntegrityTools, verifyAllOtters, verifyOtterFile };
|
|
60
|
+
export { type IntegrityAuditEvent, type VerifyAllOttersResult, type VerifyOtterFileResult, computeSha256, emitIntegrityAuditEvent, registerIntegrityTools, verifyAllOtters, verifyOtterFile };
|
package/dist/integrity.d.ts
CHANGED
|
@@ -27,6 +27,34 @@ interface VerifyAllOttersResult {
|
|
|
27
27
|
* canonical checksums. Returns lists of verified, failed, and unknown files.
|
|
28
28
|
*/
|
|
29
29
|
declare function verifyAllOtters(otterDir: string): VerifyAllOttersResult;
|
|
30
|
+
/**
|
|
31
|
+
* Structured audit event parameters for an integrity failure.
|
|
32
|
+
* Kept as a plain interface so callers can pass partial results without
|
|
33
|
+
* constructing the full VerifyAllOttersResult.
|
|
34
|
+
*/
|
|
35
|
+
interface IntegrityAuditEvent {
|
|
36
|
+
otterDir: string;
|
|
37
|
+
failed: Array<{
|
|
38
|
+
filename: string;
|
|
39
|
+
error: string;
|
|
40
|
+
}>;
|
|
41
|
+
unknown: string[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Emit a structured INTEGRITY_FAIL audit event to stderr.
|
|
45
|
+
*
|
|
46
|
+
* Writes a single line to process.stderr in the format:
|
|
47
|
+
* INTEGRITY_FAIL {"level":"AUDIT","event":"INTEGRITY_FAIL",...}
|
|
48
|
+
*
|
|
49
|
+
* The line prefix "INTEGRITY_FAIL" (without JSON) allows log shippers
|
|
50
|
+
* (FluentBit, syslog, CloudWatch Logs, Splunk) to match and route the
|
|
51
|
+
* event to a dedicated audit stream using a simple string filter, even
|
|
52
|
+
* before attempting JSON parsing.
|
|
53
|
+
*
|
|
54
|
+
* Exported for unit testing. Do not call directly in production code —
|
|
55
|
+
* use registerIntegrityTools() which calls this automatically.
|
|
56
|
+
*/
|
|
57
|
+
declare function emitIntegrityAuditEvent(params: IntegrityAuditEvent): void;
|
|
30
58
|
declare function registerIntegrityTools(server: McpServer): void;
|
|
31
59
|
|
|
32
|
-
export { type VerifyAllOttersResult, type VerifyOtterFileResult, computeSha256, registerIntegrityTools, verifyAllOtters, verifyOtterFile };
|
|
60
|
+
export { type IntegrityAuditEvent, type VerifyAllOttersResult, type VerifyOtterFileResult, computeSha256, emitIntegrityAuditEvent, registerIntegrityTools, verifyAllOtters, verifyOtterFile };
|
package/dist/integrity.js
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var integrity_exports = {};
|
|
22
22
|
__export(integrity_exports, {
|
|
23
23
|
computeSha256: () => computeSha256,
|
|
24
|
+
emitIntegrityAuditEvent: () => emitIntegrityAuditEvent,
|
|
24
25
|
registerIntegrityTools: () => registerIntegrityTools,
|
|
25
26
|
verifyAllOtters: () => verifyAllOtters,
|
|
26
27
|
verifyOtterFile: () => verifyOtterFile
|
|
@@ -32,7 +33,7 @@ var import_path = require("path");
|
|
|
32
33
|
var _checksums = /* @__PURE__ */ new Map([
|
|
33
34
|
[
|
|
34
35
|
"stackwright-pro-api-otter.json",
|
|
35
|
-
"
|
|
36
|
+
"ed667124af3f025e090c0e65d0a86f0ef08fea06c0029b8fd0edf6df33df9f9c"
|
|
36
37
|
],
|
|
37
38
|
[
|
|
38
39
|
"stackwright-pro-auth-otter.json",
|
|
@@ -40,7 +41,7 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
40
41
|
],
|
|
41
42
|
[
|
|
42
43
|
"stackwright-pro-dashboard-otter.json",
|
|
43
|
-
"
|
|
44
|
+
"5e930b4092b9002e3c1a413b36418e49c865199af12a546890ccf7f9e56a5593"
|
|
44
45
|
],
|
|
45
46
|
[
|
|
46
47
|
"stackwright-pro-data-otter.json",
|
|
@@ -48,11 +49,11 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
48
49
|
],
|
|
49
50
|
[
|
|
50
51
|
"stackwright-pro-designer-otter.json",
|
|
51
|
-
"
|
|
52
|
+
"e80d4e7bab87d8647debadb238a58aac498ec5074ff25b21abd3b13ff778bf71"
|
|
52
53
|
],
|
|
53
54
|
[
|
|
54
55
|
"stackwright-pro-foreman-otter.json",
|
|
55
|
-
"
|
|
56
|
+
"02dd2485562361f2f3cfd998981349020d7599dcd2d969bb022f9f6d537f3517"
|
|
56
57
|
],
|
|
57
58
|
[
|
|
58
59
|
"stackwright-pro-page-otter.json",
|
|
@@ -60,11 +61,11 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
60
61
|
],
|
|
61
62
|
[
|
|
62
63
|
"stackwright-pro-theme-otter.json",
|
|
63
|
-
"
|
|
64
|
+
"d3a15871b71a466c12c4711fe37cbb018c768cb99eff15c40dbbc7061d4e966b"
|
|
64
65
|
],
|
|
65
66
|
[
|
|
66
67
|
"stackwright-pro-workflow-otter.json",
|
|
67
|
-
"
|
|
68
|
+
"2ce1bcbb5c45dbb214499ea08c7175f8b743b51b8cb2ad539faf7df11edcf88a"
|
|
68
69
|
]
|
|
69
70
|
]);
|
|
70
71
|
Object.freeze(_checksums);
|
|
@@ -144,6 +145,18 @@ function verifyOtterFile(filePath) {
|
|
|
144
145
|
return { verified: true, filename };
|
|
145
146
|
}
|
|
146
147
|
function verifyAllOtters(otterDir) {
|
|
148
|
+
if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
|
|
149
|
+
return {
|
|
150
|
+
verified: [],
|
|
151
|
+
failed: [
|
|
152
|
+
{
|
|
153
|
+
filename: "<directory>",
|
|
154
|
+
error: `Security: path traversal sequence detected in otter directory parameter`
|
|
155
|
+
}
|
|
156
|
+
],
|
|
157
|
+
unknown: []
|
|
158
|
+
};
|
|
159
|
+
}
|
|
147
160
|
const verified = [];
|
|
148
161
|
const failed = [];
|
|
149
162
|
const unknown = [];
|
|
@@ -197,6 +210,21 @@ function resolveOtterDir() {
|
|
|
197
210
|
}
|
|
198
211
|
return null;
|
|
199
212
|
}
|
|
213
|
+
function emitIntegrityAuditEvent(params) {
|
|
214
|
+
const record = JSON.stringify({
|
|
215
|
+
level: "AUDIT",
|
|
216
|
+
event: "INTEGRITY_FAIL",
|
|
217
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
218
|
+
source: "stackwright_pro_verify_otter_integrity",
|
|
219
|
+
otterDir: params.otterDir,
|
|
220
|
+
failedCount: params.failed.length,
|
|
221
|
+
unknownCount: params.unknown.length,
|
|
222
|
+
failures: params.failed,
|
|
223
|
+
unknown: params.unknown
|
|
224
|
+
});
|
|
225
|
+
process.stderr.write(`INTEGRITY_FAIL ${record}
|
|
226
|
+
`);
|
|
227
|
+
}
|
|
200
228
|
function registerIntegrityTools(server) {
|
|
201
229
|
server.tool(
|
|
202
230
|
"stackwright_pro_verify_otter_integrity",
|
|
@@ -220,6 +248,13 @@ function registerIntegrityTools(server) {
|
|
|
220
248
|
}
|
|
221
249
|
const result = verifyAllOtters(resolved);
|
|
222
250
|
const allGood = result.failed.length === 0 && result.unknown.length === 0;
|
|
251
|
+
if (!allGood) {
|
|
252
|
+
emitIntegrityAuditEvent({
|
|
253
|
+
otterDir: resolved,
|
|
254
|
+
failed: result.failed,
|
|
255
|
+
unknown: result.unknown
|
|
256
|
+
});
|
|
257
|
+
}
|
|
223
258
|
return {
|
|
224
259
|
content: [
|
|
225
260
|
{
|
|
@@ -233,11 +268,13 @@ function registerIntegrityTools(server) {
|
|
|
233
268
|
verified: result.verified,
|
|
234
269
|
failed: result.failed,
|
|
235
270
|
unknown: result.unknown,
|
|
236
|
-
|
|
271
|
+
...allGood ? {} : {
|
|
272
|
+
error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
|
|
273
|
+
}
|
|
237
274
|
})
|
|
238
275
|
}
|
|
239
276
|
],
|
|
240
|
-
isError:
|
|
277
|
+
isError: !allGood
|
|
241
278
|
};
|
|
242
279
|
}
|
|
243
280
|
);
|
|
@@ -245,6 +282,7 @@ function registerIntegrityTools(server) {
|
|
|
245
282
|
// Annotate the CommonJS export names for ESM import in node:
|
|
246
283
|
0 && (module.exports = {
|
|
247
284
|
computeSha256,
|
|
285
|
+
emitIntegrityAuditEvent,
|
|
248
286
|
registerIntegrityTools,
|
|
249
287
|
verifyAllOtters,
|
|
250
288
|
verifyOtterFile
|
package/dist/integrity.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/integrity.ts"],"sourcesContent":["/**\n * Otter Integrity Verification\n * ============================\n * Protects the Pro Otter Raft from disk-based prompt injection / jailbreak attacks.\n *\n * TypeScript port of python/src/stackwright_pro/raft/integrity.py — this lets\n * the MCP package verify otter files without a Python dependency.\n *\n * Certificate-pinned canonical checksums — hardcoded in the MCP package.\n *\n * These are NOT read from disk. An attacker who modifies otter JSON files\n * in @stackwright-pro/otters cannot also modify these constants without\n * compromising the separately-published @stackwright-pro/mcp package.\n *\n * To update: node scripts/sync-mcp-checksums.cjs\n * (reads from packages/otters/src/checksums.json, writes this file)\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport { readFileSync, readdirSync, lstatSync } from 'fs';\nimport { join, basename } from 'path';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// ---------------------------------------------------------------------------\n// Certificate-pinned canonical checksums — frozen Map, immutable by design.\n// DO NOT read these from disk — that would defeat the entire purpose.\n// Object.freeze prevents property mutation at runtime; ReadonlyMap prevents\n// .set() / .delete() at compile time (belt-and-suspenders).\n// ---------------------------------------------------------------------------\n\nconst _checksums = new Map<string, string>([\n [\n 'stackwright-pro-api-otter.json',\n '1fd28747ff43121533d40d6446f2d2670d6247afb04e3025cbbcb9ace0e7d1e2',\n ],\n [\n 'stackwright-pro-auth-otter.json',\n 'b5e901262d7b3f26ef390f1d3c9aadfa68376c05f5057edc241eb37b32b40afd',\n ],\n [\n 'stackwright-pro-dashboard-otter.json',\n 'a9e50f26e8b2b687910685f15104b4e76a74ad2e1e5a6021237e1eeb1cbde2ae',\n ],\n [\n 'stackwright-pro-data-otter.json',\n '04b07f982f73a2904a1d92c6af3c58ecc132b474c57cab3eaec8566d718d2623',\n ],\n [\n 'stackwright-pro-designer-otter.json',\n '41c5b6b9f1f0f6eb0851e473f9d7d6ebd6a7e00dafd5cdeb8a8b12b0b756e245',\n ],\n [\n 'stackwright-pro-foreman-otter.json',\n '7c8af9ce5b157ad3030f0255218a6ea923df18a36fe44db9bd5f04897434fc05',\n ],\n [\n 'stackwright-pro-page-otter.json',\n 'd672dc4dfd6a3b6d66c6cec93c8db6075dcd4c8f1e8d15e2704aca2fca6856a6',\n ],\n [\n 'stackwright-pro-theme-otter.json',\n '3a37d4bd696f142c4a4278ef653984fca4b776caa610182c2cb82f6732ef9b62',\n ],\n [\n 'stackwright-pro-workflow-otter.json',\n 'fa2bae06e0f9e6b844008adc933d24b6a210708c0812ce068fc43733ee98b98e',\n ],\n]);\nObject.freeze(_checksums);\nconst CANONICAL_CHECKSUMS: ReadonlyMap<string, string> = _checksums;\n\n// ---------------------------------------------------------------------------\n// Import-time format validation — malformed constants are a packaging bug,\n// not a runtime surprise. Fail fast, fail loud.\n// ---------------------------------------------------------------------------\n\nconst SHA256_HEX_RE = /^[0-9a-f]{64}$/;\n\nfor (const [name, digest] of CANONICAL_CHECKSUMS) {\n if (!SHA256_HEX_RE.test(digest)) {\n throw new Error(\n `Malformed SHA-256 in CANONICAL_CHECKSUMS for \"${name}\": ` +\n `expected 64 hex chars, got ${digest.length}: \"${digest}\"`\n );\n }\n}\n\n// 1 MB — generous headroom for agent definitions; anything larger is suspicious.\nconst MAX_OTTER_BYTES = 1 * 1024 * 1024;\n\n// ---------------------------------------------------------------------------\n// Core functions (exported for direct testing — no MCP server needed)\n// ---------------------------------------------------------------------------\n\n/** Compute the hex-encoded SHA-256 digest of raw bytes. Pure, no I/O. */\nexport function computeSha256(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/** Constant-time comparison of two hex digest strings. */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));\n}\n\n// ---------------------------------------------------------------------------\n// Single-file verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyOtterFileResult {\n verified: boolean;\n filename: string;\n error?: string;\n}\n\n/**\n * Read a single otter JSON file, check its size, compute its SHA-256,\n * and constant-time compare against the canonical checksum.\n *\n * Single read → hash → decode. No TOCTOU window.\n */\nexport function verifyOtterFile(filePath: string): VerifyOtterFileResult {\n const filename = basename(filePath);\n\n // Fast-fail on unknown filenames before any I/O\n const expected = CANONICAL_CHECKSUMS.get(filename);\n if (expected === undefined) {\n return { verified: false, filename, error: `Unknown otter file: not in canonical set` };\n }\n\n // Symlink guard — refuse to follow symlinks (prevents symlink-based swaps)\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot stat file: ${msg}` };\n }\n\n if (stat.isSymbolicLink()) {\n return { verified: false, filename, error: 'Refusing to verify symlink' };\n }\n\n // Stat-based size pre-check — don't materialise oversized payloads\n const size = stat.size;\n\n if (size > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`,\n };\n }\n\n // Single read — used for hashing and UTF-8 validation (zero TOCTOU window)\n let raw: Buffer;\n try {\n raw = readFileSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot read file: ${msg}` };\n }\n\n // Belt-and-suspenders: re-check length after read in case of a race\n if (raw.length > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`,\n };\n }\n\n // Hash the raw bytes\n const actual = computeSha256(raw);\n\n // Constant-time comparison prevents timing-oracle attacks\n if (!safeEqual(actual, expected)) {\n return {\n verified: false,\n filename,\n error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}…, got ${actual.substring(0, 8)}…`,\n };\n }\n\n // UTF-8 validation — binary injection guard\n try {\n const decoder = new TextDecoder('utf-8', { fatal: true });\n decoder.decode(raw);\n } catch {\n return {\n verified: false,\n filename,\n error: 'File is not valid UTF-8 — may be corrupted or contain binary injection',\n };\n }\n\n return { verified: true, filename };\n}\n\n// ---------------------------------------------------------------------------\n// Directory-level verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyAllOttersResult {\n verified: string[];\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Scan a directory for `*-otter.json` files, verify each one against\n * canonical checksums. Returns lists of verified, failed, and unknown files.\n */\nexport function verifyAllOtters(otterDir: string): VerifyAllOttersResult {\n const verified: string[] = [];\n const failed: Array<{ filename: string; error: string }> = [];\n const unknown: string[] = [];\n\n let entries: string[];\n try {\n entries = readdirSync(otterDir);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n verified: [],\n failed: [{ filename: '<directory>', error: `Cannot read directory: ${msg}` }],\n unknown: [],\n };\n }\n\n const otterFiles = entries.filter((f) => f.endsWith('-otter.json'));\n\n for (const filename of otterFiles) {\n const filePath = join(otterDir, filename);\n\n // Skip symlinks at the directory-scan level too\n try {\n if (lstatSync(filePath).isSymbolicLink()) {\n failed.push({ filename, error: 'Skipped: symlink' });\n continue;\n }\n } catch {\n // verifyOtterFile will handle stat errors\n }\n\n const result = verifyOtterFile(filePath);\n\n if (result.verified) {\n verified.push(result.filename);\n } else if (result.error?.startsWith('Unknown otter file')) {\n unknown.push(result.filename);\n } else {\n failed.push({ filename: result.filename, error: result.error ?? 'Unknown error' });\n }\n }\n\n // Check for missing canonical files — ones we expect but didn't find on disk\n for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {\n if (!otterFiles.includes(canonicalName)) {\n failed.push({ filename: canonicalName, error: 'Missing from directory' });\n }\n }\n\n return { verified, failed, unknown };\n}\n\n// ---------------------------------------------------------------------------\n// Otter directory resolution\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SEARCH_PATHS = ['node_modules/@stackwright-pro/otters/src/', 'packages/otters/src/'];\n\nfunction resolveOtterDir(): string | null {\n const cwd = process.cwd();\n for (const relative of DEFAULT_SEARCH_PATHS) {\n const candidate = join(cwd, relative);\n try {\n lstatSync(candidate);\n return candidate;\n } catch {\n // Not found, try next\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// MCP tool registration\n// ---------------------------------------------------------------------------\n\nexport function registerIntegrityTools(server: McpServer): void {\n server.tool(\n 'stackwright_pro_verify_otter_integrity',\n 'Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.',\n {},\n async () => {\n const resolved = resolveOtterDir();\n\n if (!resolved) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n error: true,\n message:\n 'Could not locate otter directory. Searched: ' + DEFAULT_SEARCH_PATHS.join(', '),\n }),\n },\n ],\n isError: true,\n };\n }\n\n const result = verifyAllOtters(resolved);\n\n const allGood = result.failed.length === 0 && result.unknown.length === 0;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n otterDir: resolved,\n totalCanonical: CANONICAL_CHECKSUMS.size,\n verifiedCount: result.verified.length,\n failedCount: result.failed.length,\n unknownCount: result.unknown.length,\n verified: result.verified,\n failed: result.failed,\n unknown: result.unknown,\n warning:\n result.failed.length > 0\n ? 'SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon.'\n : undefined,\n }),\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;AAAA,UACH;AAAA,QACF;AAAA,QACA,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/integrity.ts"],"sourcesContent":["/**\n * Otter Integrity Verification\n * ============================\n * Protects the Pro Otter Raft from disk-based prompt injection / jailbreak attacks.\n *\n * TypeScript port of python/src/stackwright_pro/raft/integrity.py — this lets\n * the MCP package verify otter files without a Python dependency.\n *\n * Certificate-pinned canonical checksums — hardcoded in the MCP package.\n *\n * These are NOT read from disk. An attacker who modifies otter JSON files\n * in @stackwright-pro/otters cannot also modify these constants without\n * compromising the separately-published @stackwright-pro/mcp package.\n *\n * To update: node scripts/sync-mcp-checksums.cjs\n * (reads from packages/otters/src/checksums.json, writes this file)\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport { readFileSync, readdirSync, lstatSync } from 'fs';\nimport { join, basename } from 'path';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// ---------------------------------------------------------------------------\n// Certificate-pinned canonical checksums — frozen Map, immutable by design.\n// DO NOT read these from disk — that would defeat the entire purpose.\n// Object.freeze prevents property mutation at runtime; ReadonlyMap prevents\n// .set() / .delete() at compile time (belt-and-suspenders).\n// ---------------------------------------------------------------------------\n\nconst _checksums = new Map<string, string>([\n [\n 'stackwright-pro-api-otter.json',\n 'ed667124af3f025e090c0e65d0a86f0ef08fea06c0029b8fd0edf6df33df9f9c',\n ],\n [\n 'stackwright-pro-auth-otter.json',\n 'b5e901262d7b3f26ef390f1d3c9aadfa68376c05f5057edc241eb37b32b40afd',\n ],\n [\n 'stackwright-pro-dashboard-otter.json',\n '5e930b4092b9002e3c1a413b36418e49c865199af12a546890ccf7f9e56a5593',\n ],\n [\n 'stackwright-pro-data-otter.json',\n '04b07f982f73a2904a1d92c6af3c58ecc132b474c57cab3eaec8566d718d2623',\n ],\n [\n 'stackwright-pro-designer-otter.json',\n 'e80d4e7bab87d8647debadb238a58aac498ec5074ff25b21abd3b13ff778bf71',\n ],\n [\n 'stackwright-pro-foreman-otter.json',\n '02dd2485562361f2f3cfd998981349020d7599dcd2d969bb022f9f6d537f3517',\n ],\n [\n 'stackwright-pro-page-otter.json',\n 'd672dc4dfd6a3b6d66c6cec93c8db6075dcd4c8f1e8d15e2704aca2fca6856a6',\n ],\n [\n 'stackwright-pro-theme-otter.json',\n 'd3a15871b71a466c12c4711fe37cbb018c768cb99eff15c40dbbc7061d4e966b',\n ],\n [\n 'stackwright-pro-workflow-otter.json',\n '2ce1bcbb5c45dbb214499ea08c7175f8b743b51b8cb2ad539faf7df11edcf88a',\n ],\n]);\nObject.freeze(_checksums);\nconst CANONICAL_CHECKSUMS: ReadonlyMap<string, string> = _checksums;\n\n// ---------------------------------------------------------------------------\n// Import-time format validation — malformed constants are a packaging bug,\n// not a runtime surprise. Fail fast, fail loud.\n// ---------------------------------------------------------------------------\n\nconst SHA256_HEX_RE = /^[0-9a-f]{64}$/;\n\nfor (const [name, digest] of CANONICAL_CHECKSUMS) {\n if (!SHA256_HEX_RE.test(digest)) {\n throw new Error(\n `Malformed SHA-256 in CANONICAL_CHECKSUMS for \"${name}\": ` +\n `expected 64 hex chars, got ${digest.length}: \"${digest}\"`\n );\n }\n}\n\n// 1 MB — generous headroom for agent definitions; anything larger is suspicious.\nconst MAX_OTTER_BYTES = 1 * 1024 * 1024;\n\n// ---------------------------------------------------------------------------\n// Core functions (exported for direct testing — no MCP server needed)\n// ---------------------------------------------------------------------------\n\n/** Compute the hex-encoded SHA-256 digest of raw bytes. Pure, no I/O. */\nexport function computeSha256(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/** Constant-time comparison of two hex digest strings. */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));\n}\n\n// ---------------------------------------------------------------------------\n// Single-file verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyOtterFileResult {\n verified: boolean;\n filename: string;\n error?: string;\n}\n\n/**\n * Read a single otter JSON file, check its size, compute its SHA-256,\n * and constant-time compare against the canonical checksum.\n *\n * Single read → hash → decode. No TOCTOU window.\n */\nexport function verifyOtterFile(filePath: string): VerifyOtterFileResult {\n const filename = basename(filePath);\n\n // Fast-fail on unknown filenames before any I/O\n const expected = CANONICAL_CHECKSUMS.get(filename);\n if (expected === undefined) {\n return { verified: false, filename, error: `Unknown otter file: not in canonical set` };\n }\n\n // Symlink guard — refuse to follow symlinks (prevents symlink-based swaps)\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot stat file: ${msg}` };\n }\n\n if (stat.isSymbolicLink()) {\n return { verified: false, filename, error: 'Refusing to verify symlink' };\n }\n\n // Stat-based size pre-check — don't materialise oversized payloads\n const size = stat.size;\n\n if (size > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`,\n };\n }\n\n // Single read — used for hashing and UTF-8 validation (zero TOCTOU window)\n let raw: Buffer;\n try {\n raw = readFileSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot read file: ${msg}` };\n }\n\n // Belt-and-suspenders: re-check length after read in case of a race\n if (raw.length > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`,\n };\n }\n\n // Hash the raw bytes\n const actual = computeSha256(raw);\n\n // Constant-time comparison prevents timing-oracle attacks\n if (!safeEqual(actual, expected)) {\n return {\n verified: false,\n filename,\n error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}…, got ${actual.substring(0, 8)}…`,\n };\n }\n\n // UTF-8 validation — binary injection guard\n try {\n const decoder = new TextDecoder('utf-8', { fatal: true });\n decoder.decode(raw);\n } catch {\n return {\n verified: false,\n filename,\n error: 'File is not valid UTF-8 — may be corrupted or contain binary injection',\n };\n }\n\n return { verified: true, filename };\n}\n\n// ---------------------------------------------------------------------------\n// Directory-level verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyAllOttersResult {\n verified: string[];\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Scan a directory for `*-otter.json` files, verify each one against\n * canonical checksums. Returns lists of verified, failed, and unknown files.\n */\nexport function verifyAllOtters(otterDir: string): VerifyAllOttersResult {\n // ---------------------------------------------------------------------------\n // Path traversal guard — reject any input containing \"..\" sequences before\n // any I/O. An attacker controlling this parameter could otherwise scan\n // directories outside the expected otter install locations.\n // ---------------------------------------------------------------------------\n if (/(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)/.test(otterDir) || otterDir.includes('..')) {\n return {\n verified: [],\n failed: [\n {\n filename: '<directory>',\n error: `Security: path traversal sequence detected in otter directory parameter`,\n },\n ],\n unknown: [],\n };\n }\n\n const verified: string[] = [];\n const failed: Array<{ filename: string; error: string }> = [];\n const unknown: string[] = [];\n\n let entries: string[];\n try {\n entries = readdirSync(otterDir);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n verified: [],\n failed: [{ filename: '<directory>', error: `Cannot read directory: ${msg}` }],\n unknown: [],\n };\n }\n\n const otterFiles = entries.filter((f) => f.endsWith('-otter.json'));\n\n for (const filename of otterFiles) {\n const filePath = join(otterDir, filename);\n\n // Skip symlinks at the directory-scan level too\n try {\n if (lstatSync(filePath).isSymbolicLink()) {\n failed.push({ filename, error: 'Skipped: symlink' });\n continue;\n }\n } catch {\n // verifyOtterFile will handle stat errors\n }\n\n const result = verifyOtterFile(filePath);\n\n if (result.verified) {\n verified.push(result.filename);\n } else if (result.error?.startsWith('Unknown otter file')) {\n unknown.push(result.filename);\n } else {\n failed.push({ filename: result.filename, error: result.error ?? 'Unknown error' });\n }\n }\n\n // Check for missing canonical files — ones we expect but didn't find on disk\n for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {\n if (!otterFiles.includes(canonicalName)) {\n failed.push({ filename: canonicalName, error: 'Missing from directory' });\n }\n }\n\n return { verified, failed, unknown };\n}\n\n// ---------------------------------------------------------------------------\n// Otter directory resolution\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SEARCH_PATHS = ['node_modules/@stackwright-pro/otters/src/', 'packages/otters/src/'];\n\nfunction resolveOtterDir(): string | null {\n const cwd = process.cwd();\n for (const relative of DEFAULT_SEARCH_PATHS) {\n const candidate = join(cwd, relative);\n try {\n lstatSync(candidate);\n return candidate;\n } catch {\n // Not found, try next\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Audit stream — SOC2 / FedRAMP / DoD ATO compliance\n// ---------------------------------------------------------------------------\n\n/**\n * Structured audit event parameters for an integrity failure.\n * Kept as a plain interface so callers can pass partial results without\n * constructing the full VerifyAllOttersResult.\n */\nexport interface IntegrityAuditEvent {\n otterDir: string;\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Emit a structured INTEGRITY_FAIL audit event to stderr.\n *\n * Writes a single line to process.stderr in the format:\n * INTEGRITY_FAIL {\"level\":\"AUDIT\",\"event\":\"INTEGRITY_FAIL\",...}\n *\n * The line prefix \"INTEGRITY_FAIL\" (without JSON) allows log shippers\n * (FluentBit, syslog, CloudWatch Logs, Splunk) to match and route the\n * event to a dedicated audit stream using a simple string filter, even\n * before attempting JSON parsing.\n *\n * Exported for unit testing. Do not call directly in production code —\n * use registerIntegrityTools() which calls this automatically.\n */\nexport function emitIntegrityAuditEvent(params: IntegrityAuditEvent): void {\n const record = JSON.stringify({\n level: 'AUDIT',\n event: 'INTEGRITY_FAIL',\n timestamp: new Date().toISOString(),\n source: 'stackwright_pro_verify_otter_integrity',\n otterDir: params.otterDir,\n failedCount: params.failed.length,\n unknownCount: params.unknown.length,\n failures: params.failed,\n unknown: params.unknown,\n });\n process.stderr.write(`INTEGRITY_FAIL ${record}\\n`);\n}\n\n// ---------------------------------------------------------------------------\n// MCP tool registration\n// ---------------------------------------------------------------------------\n\nexport function registerIntegrityTools(server: McpServer): void {\n server.tool(\n 'stackwright_pro_verify_otter_integrity',\n 'Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.',\n {},\n async () => {\n const resolved = resolveOtterDir();\n\n if (!resolved) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n error: true,\n message:\n 'Could not locate otter directory. Searched: ' + DEFAULT_SEARCH_PATHS.join(', '),\n }),\n },\n ],\n isError: true,\n };\n }\n\n const result = verifyAllOtters(resolved);\n\n const allGood = result.failed.length === 0 && result.unknown.length === 0;\n\n // Emit to dedicated audit stream for SOC2/FedRAMP/DoD ATO compliance\n if (!allGood) {\n emitIntegrityAuditEvent({\n otterDir: resolved,\n failed: result.failed,\n unknown: result.unknown,\n });\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n otterDir: resolved,\n totalCanonical: CANONICAL_CHECKSUMS.size,\n verifiedCount: result.verified.length,\n failedCount: result.failed.length,\n unknownCount: result.unknown.length,\n verified: result.verified,\n failed: result.failed,\n unknown: result.unknown,\n ...(allGood\n ? {}\n : {\n error:\n 'INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed — otter files may have been tampered with.',\n }),\n }),\n },\n ],\n isError: !allGood,\n };\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,oBAA4C;AAC5C,gBAAqD;AACrD,kBAA+B;AAU/B,IAAM,aAAa,oBAAI,IAAoB;AAAA,EACzC;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA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OAAO;AAAA,UACf,SAAS,OAAO;AAAA,QAClB,CAAC;AAAA,MACH;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AAAA,YACN,MAAM,KAAK,UAAU;AAAA,cACnB,UAAU;AAAA,cACV,gBAAgB,oBAAoB;AAAA,cACpC,eAAe,OAAO,SAAS;AAAA,cAC/B,aAAa,OAAO,OAAO;AAAA,cAC3B,cAAc,OAAO,QAAQ;AAAA,cAC7B,UAAU,OAAO;AAAA,cACjB,QAAQ,OAAO;AAAA,cACf,SAAS,OAAO;AAAA,cAChB,GAAI,UACA,CAAC,IACD;AAAA,gBACE,OACE;AAAA,cACJ;AAAA,YACN,CAAC;AAAA,UACH;AAAA,QACF;AAAA,QACA,SAAS,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/integrity.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { join, basename } from "path";
|
|
|
5
5
|
var _checksums = /* @__PURE__ */ new Map([
|
|
6
6
|
[
|
|
7
7
|
"stackwright-pro-api-otter.json",
|
|
8
|
-
"
|
|
8
|
+
"ed667124af3f025e090c0e65d0a86f0ef08fea06c0029b8fd0edf6df33df9f9c"
|
|
9
9
|
],
|
|
10
10
|
[
|
|
11
11
|
"stackwright-pro-auth-otter.json",
|
|
@@ -13,7 +13,7 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
13
13
|
],
|
|
14
14
|
[
|
|
15
15
|
"stackwright-pro-dashboard-otter.json",
|
|
16
|
-
"
|
|
16
|
+
"5e930b4092b9002e3c1a413b36418e49c865199af12a546890ccf7f9e56a5593"
|
|
17
17
|
],
|
|
18
18
|
[
|
|
19
19
|
"stackwright-pro-data-otter.json",
|
|
@@ -21,11 +21,11 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
21
21
|
],
|
|
22
22
|
[
|
|
23
23
|
"stackwright-pro-designer-otter.json",
|
|
24
|
-
"
|
|
24
|
+
"e80d4e7bab87d8647debadb238a58aac498ec5074ff25b21abd3b13ff778bf71"
|
|
25
25
|
],
|
|
26
26
|
[
|
|
27
27
|
"stackwright-pro-foreman-otter.json",
|
|
28
|
-
"
|
|
28
|
+
"02dd2485562361f2f3cfd998981349020d7599dcd2d969bb022f9f6d537f3517"
|
|
29
29
|
],
|
|
30
30
|
[
|
|
31
31
|
"stackwright-pro-page-otter.json",
|
|
@@ -33,11 +33,11 @@ var _checksums = /* @__PURE__ */ new Map([
|
|
|
33
33
|
],
|
|
34
34
|
[
|
|
35
35
|
"stackwright-pro-theme-otter.json",
|
|
36
|
-
"
|
|
36
|
+
"d3a15871b71a466c12c4711fe37cbb018c768cb99eff15c40dbbc7061d4e966b"
|
|
37
37
|
],
|
|
38
38
|
[
|
|
39
39
|
"stackwright-pro-workflow-otter.json",
|
|
40
|
-
"
|
|
40
|
+
"2ce1bcbb5c45dbb214499ea08c7175f8b743b51b8cb2ad539faf7df11edcf88a"
|
|
41
41
|
]
|
|
42
42
|
]);
|
|
43
43
|
Object.freeze(_checksums);
|
|
@@ -117,6 +117,18 @@ function verifyOtterFile(filePath) {
|
|
|
117
117
|
return { verified: true, filename };
|
|
118
118
|
}
|
|
119
119
|
function verifyAllOtters(otterDir) {
|
|
120
|
+
if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
|
|
121
|
+
return {
|
|
122
|
+
verified: [],
|
|
123
|
+
failed: [
|
|
124
|
+
{
|
|
125
|
+
filename: "<directory>",
|
|
126
|
+
error: `Security: path traversal sequence detected in otter directory parameter`
|
|
127
|
+
}
|
|
128
|
+
],
|
|
129
|
+
unknown: []
|
|
130
|
+
};
|
|
131
|
+
}
|
|
120
132
|
const verified = [];
|
|
121
133
|
const failed = [];
|
|
122
134
|
const unknown = [];
|
|
@@ -170,6 +182,21 @@ function resolveOtterDir() {
|
|
|
170
182
|
}
|
|
171
183
|
return null;
|
|
172
184
|
}
|
|
185
|
+
function emitIntegrityAuditEvent(params) {
|
|
186
|
+
const record = JSON.stringify({
|
|
187
|
+
level: "AUDIT",
|
|
188
|
+
event: "INTEGRITY_FAIL",
|
|
189
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
190
|
+
source: "stackwright_pro_verify_otter_integrity",
|
|
191
|
+
otterDir: params.otterDir,
|
|
192
|
+
failedCount: params.failed.length,
|
|
193
|
+
unknownCount: params.unknown.length,
|
|
194
|
+
failures: params.failed,
|
|
195
|
+
unknown: params.unknown
|
|
196
|
+
});
|
|
197
|
+
process.stderr.write(`INTEGRITY_FAIL ${record}
|
|
198
|
+
`);
|
|
199
|
+
}
|
|
173
200
|
function registerIntegrityTools(server) {
|
|
174
201
|
server.tool(
|
|
175
202
|
"stackwright_pro_verify_otter_integrity",
|
|
@@ -193,6 +220,13 @@ function registerIntegrityTools(server) {
|
|
|
193
220
|
}
|
|
194
221
|
const result = verifyAllOtters(resolved);
|
|
195
222
|
const allGood = result.failed.length === 0 && result.unknown.length === 0;
|
|
223
|
+
if (!allGood) {
|
|
224
|
+
emitIntegrityAuditEvent({
|
|
225
|
+
otterDir: resolved,
|
|
226
|
+
failed: result.failed,
|
|
227
|
+
unknown: result.unknown
|
|
228
|
+
});
|
|
229
|
+
}
|
|
196
230
|
return {
|
|
197
231
|
content: [
|
|
198
232
|
{
|
|
@@ -206,17 +240,20 @@ function registerIntegrityTools(server) {
|
|
|
206
240
|
verified: result.verified,
|
|
207
241
|
failed: result.failed,
|
|
208
242
|
unknown: result.unknown,
|
|
209
|
-
|
|
243
|
+
...allGood ? {} : {
|
|
244
|
+
error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
|
|
245
|
+
}
|
|
210
246
|
})
|
|
211
247
|
}
|
|
212
248
|
],
|
|
213
|
-
isError:
|
|
249
|
+
isError: !allGood
|
|
214
250
|
};
|
|
215
251
|
}
|
|
216
252
|
);
|
|
217
253
|
}
|
|
218
254
|
export {
|
|
219
255
|
computeSha256,
|
|
256
|
+
emitIntegrityAuditEvent,
|
|
220
257
|
registerIntegrityTools,
|
|
221
258
|
verifyAllOtters,
|
|
222
259
|
verifyOtterFile
|
package/dist/integrity.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/integrity.ts"],"sourcesContent":["/**\n * Otter Integrity Verification\n * ============================\n * Protects the Pro Otter Raft from disk-based prompt injection / jailbreak attacks.\n *\n * TypeScript port of python/src/stackwright_pro/raft/integrity.py — this lets\n * the MCP package verify otter files without a Python dependency.\n *\n * Certificate-pinned canonical checksums — hardcoded in the MCP package.\n *\n * These are NOT read from disk. An attacker who modifies otter JSON files\n * in @stackwright-pro/otters cannot also modify these constants without\n * compromising the separately-published @stackwright-pro/mcp package.\n *\n * To update: node scripts/sync-mcp-checksums.cjs\n * (reads from packages/otters/src/checksums.json, writes this file)\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport { readFileSync, readdirSync, lstatSync } from 'fs';\nimport { join, basename } from 'path';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// ---------------------------------------------------------------------------\n// Certificate-pinned canonical checksums — frozen Map, immutable by design.\n// DO NOT read these from disk — that would defeat the entire purpose.\n// Object.freeze prevents property mutation at runtime; ReadonlyMap prevents\n// .set() / .delete() at compile time (belt-and-suspenders).\n// ---------------------------------------------------------------------------\n\nconst _checksums = new Map<string, string>([\n [\n 'stackwright-pro-api-otter.json',\n '1fd28747ff43121533d40d6446f2d2670d6247afb04e3025cbbcb9ace0e7d1e2',\n ],\n [\n 'stackwright-pro-auth-otter.json',\n 'b5e901262d7b3f26ef390f1d3c9aadfa68376c05f5057edc241eb37b32b40afd',\n ],\n [\n 'stackwright-pro-dashboard-otter.json',\n 'a9e50f26e8b2b687910685f15104b4e76a74ad2e1e5a6021237e1eeb1cbde2ae',\n ],\n [\n 'stackwright-pro-data-otter.json',\n '04b07f982f73a2904a1d92c6af3c58ecc132b474c57cab3eaec8566d718d2623',\n ],\n [\n 'stackwright-pro-designer-otter.json',\n '41c5b6b9f1f0f6eb0851e473f9d7d6ebd6a7e00dafd5cdeb8a8b12b0b756e245',\n ],\n [\n 'stackwright-pro-foreman-otter.json',\n '7c8af9ce5b157ad3030f0255218a6ea923df18a36fe44db9bd5f04897434fc05',\n ],\n [\n 'stackwright-pro-page-otter.json',\n 'd672dc4dfd6a3b6d66c6cec93c8db6075dcd4c8f1e8d15e2704aca2fca6856a6',\n ],\n [\n 'stackwright-pro-theme-otter.json',\n '3a37d4bd696f142c4a4278ef653984fca4b776caa610182c2cb82f6732ef9b62',\n ],\n [\n 'stackwright-pro-workflow-otter.json',\n 'fa2bae06e0f9e6b844008adc933d24b6a210708c0812ce068fc43733ee98b98e',\n ],\n]);\nObject.freeze(_checksums);\nconst CANONICAL_CHECKSUMS: ReadonlyMap<string, string> = _checksums;\n\n// ---------------------------------------------------------------------------\n// Import-time format validation — malformed constants are a packaging bug,\n// not a runtime surprise. Fail fast, fail loud.\n// ---------------------------------------------------------------------------\n\nconst SHA256_HEX_RE = /^[0-9a-f]{64}$/;\n\nfor (const [name, digest] of CANONICAL_CHECKSUMS) {\n if (!SHA256_HEX_RE.test(digest)) {\n throw new Error(\n `Malformed SHA-256 in CANONICAL_CHECKSUMS for \"${name}\": ` +\n `expected 64 hex chars, got ${digest.length}: \"${digest}\"`\n );\n }\n}\n\n// 1 MB — generous headroom for agent definitions; anything larger is suspicious.\nconst MAX_OTTER_BYTES = 1 * 1024 * 1024;\n\n// ---------------------------------------------------------------------------\n// Core functions (exported for direct testing — no MCP server needed)\n// ---------------------------------------------------------------------------\n\n/** Compute the hex-encoded SHA-256 digest of raw bytes. Pure, no I/O. */\nexport function computeSha256(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/** Constant-time comparison of two hex digest strings. */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));\n}\n\n// ---------------------------------------------------------------------------\n// Single-file verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyOtterFileResult {\n verified: boolean;\n filename: string;\n error?: string;\n}\n\n/**\n * Read a single otter JSON file, check its size, compute its SHA-256,\n * and constant-time compare against the canonical checksum.\n *\n * Single read → hash → decode. No TOCTOU window.\n */\nexport function verifyOtterFile(filePath: string): VerifyOtterFileResult {\n const filename = basename(filePath);\n\n // Fast-fail on unknown filenames before any I/O\n const expected = CANONICAL_CHECKSUMS.get(filename);\n if (expected === undefined) {\n return { verified: false, filename, error: `Unknown otter file: not in canonical set` };\n }\n\n // Symlink guard — refuse to follow symlinks (prevents symlink-based swaps)\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot stat file: ${msg}` };\n }\n\n if (stat.isSymbolicLink()) {\n return { verified: false, filename, error: 'Refusing to verify symlink' };\n }\n\n // Stat-based size pre-check — don't materialise oversized payloads\n const size = stat.size;\n\n if (size > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`,\n };\n }\n\n // Single read — used for hashing and UTF-8 validation (zero TOCTOU window)\n let raw: Buffer;\n try {\n raw = readFileSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot read file: ${msg}` };\n }\n\n // Belt-and-suspenders: re-check length after read in case of a race\n if (raw.length > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`,\n };\n }\n\n // Hash the raw bytes\n const actual = computeSha256(raw);\n\n // Constant-time comparison prevents timing-oracle attacks\n if (!safeEqual(actual, expected)) {\n return {\n verified: false,\n filename,\n error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}…, got ${actual.substring(0, 8)}…`,\n };\n }\n\n // UTF-8 validation — binary injection guard\n try {\n const decoder = new TextDecoder('utf-8', { fatal: true });\n decoder.decode(raw);\n } catch {\n return {\n verified: false,\n filename,\n error: 'File is not valid UTF-8 — may be corrupted or contain binary injection',\n };\n }\n\n return { verified: true, filename };\n}\n\n// ---------------------------------------------------------------------------\n// Directory-level verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyAllOttersResult {\n verified: string[];\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Scan a directory for `*-otter.json` files, verify each one against\n * canonical checksums. Returns lists of verified, failed, and unknown files.\n */\nexport function verifyAllOtters(otterDir: string): VerifyAllOttersResult {\n const verified: string[] = [];\n const failed: Array<{ filename: string; error: string }> = [];\n const unknown: string[] = [];\n\n let entries: string[];\n try {\n entries = readdirSync(otterDir);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n verified: [],\n failed: [{ filename: '<directory>', error: `Cannot read directory: ${msg}` }],\n unknown: [],\n };\n }\n\n const otterFiles = entries.filter((f) => f.endsWith('-otter.json'));\n\n for (const filename of otterFiles) {\n const filePath = join(otterDir, filename);\n\n // Skip symlinks at the directory-scan level too\n try {\n if (lstatSync(filePath).isSymbolicLink()) {\n failed.push({ filename, error: 'Skipped: symlink' });\n continue;\n }\n } catch {\n // verifyOtterFile will handle stat errors\n }\n\n const result = verifyOtterFile(filePath);\n\n if (result.verified) {\n verified.push(result.filename);\n } else if (result.error?.startsWith('Unknown otter file')) {\n unknown.push(result.filename);\n } else {\n failed.push({ filename: result.filename, error: result.error ?? 'Unknown error' });\n }\n }\n\n // Check for missing canonical files — ones we expect but didn't find on disk\n for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {\n if (!otterFiles.includes(canonicalName)) {\n failed.push({ filename: canonicalName, error: 'Missing from directory' });\n }\n }\n\n return { verified, failed, unknown };\n}\n\n// ---------------------------------------------------------------------------\n// Otter directory resolution\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SEARCH_PATHS = ['node_modules/@stackwright-pro/otters/src/', 'packages/otters/src/'];\n\nfunction resolveOtterDir(): string | null {\n const cwd = process.cwd();\n for (const relative of DEFAULT_SEARCH_PATHS) {\n const candidate = join(cwd, relative);\n try {\n lstatSync(candidate);\n return candidate;\n } catch {\n // Not found, try next\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// MCP tool registration\n// ---------------------------------------------------------------------------\n\nexport function registerIntegrityTools(server: McpServer): void {\n server.tool(\n 'stackwright_pro_verify_otter_integrity',\n 'Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.',\n {},\n async () => {\n const resolved = resolveOtterDir();\n\n if (!resolved) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n error: true,\n message:\n 'Could not locate otter directory. Searched: ' + DEFAULT_SEARCH_PATHS.join(', '),\n }),\n },\n ],\n isError: true,\n };\n }\n\n const result = verifyAllOtters(resolved);\n\n const allGood = result.failed.length === 0 && result.unknown.length === 0;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n otterDir: resolved,\n totalCanonical: CANONICAL_CHECKSUMS.size,\n verifiedCount: result.verified.length,\n failedCount: result.failed.length,\n unknownCount: result.unknown.length,\n verified: result.verified,\n failed: result.failed,\n unknown: result.unknown,\n warning:\n result.failed.length > 0\n ? 'SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon.'\n : undefined,\n }),\n },\n ],\n isError: false,\n };\n }\n );\n}\n"],"mappings":";AAiBA,SAAS,YAAY,uBAAuB;AAC5C,SAAS,cAAc,aAAa,iBAAiB;AACrD,SAAS,MAAM,gBAAgB;AAU/B,IAAM,aAAa,oBAAI,IAAoB;AAAA,EACzC;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;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;AACF,gBAAU,SAAS;AACnB,aAAO;AAAA,IACT,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,uBAAuB,QAAyB;AAC9D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,CAAC;AAAA,IACD,YAAY;AACV,YAAM,WAAW,gBAAgB;AAEjC,UAAI,CAAC,UAAU;AACb,eAAO;AAAA,UACL,SAAS;AAAA,YACP;AAAA,cACE,MAAM;AAAA,cACN,MAAM,KAAK,UAAU;AAAA,gBACnB,OAAO;AAAA,gBACP,SACE,iDAAiD,qBAAqB,KAAK,IAAI;AAAA,cACnF,CAAC;AAAA,YACH;AAAA,UACF;AAAA,UACA,SAAS;AAAA,QACX;AAAA,MACF;AAEA,YAAM,SAAS,gBAAgB,QAAQ;AAEvC,YAAM,UAAU,OAAO,OAAO,WAAW,KAAK,OAAO,QAAQ,WAAW;AAExE,aAAO;AAAA,QACL,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AAAA,YACN,MAAM,KAAK,UAAU;AAAA,cACnB,UAAU;AAAA,cACV,gBAAgB,oBAAoB;AAAA,cACpC,eAAe,OAAO,SAAS;AAAA,cAC/B,aAAa,OAAO,OAAO;AAAA,cAC3B,cAAc,OAAO,QAAQ;AAAA,cAC7B,UAAU,OAAO;AAAA,cACjB,QAAQ,OAAO;AAAA,cACf,SAAS,OAAO;AAAA,cAChB,SACE,OAAO,OAAO,SAAS,IACnB,yFACA;AAAA,YACR,CAAC;AAAA,UACH;AAAA,QACF;AAAA,QACA,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/integrity.ts"],"sourcesContent":["/**\n * Otter Integrity Verification\n * ============================\n * Protects the Pro Otter Raft from disk-based prompt injection / jailbreak attacks.\n *\n * TypeScript port of python/src/stackwright_pro/raft/integrity.py — this lets\n * the MCP package verify otter files without a Python dependency.\n *\n * Certificate-pinned canonical checksums — hardcoded in the MCP package.\n *\n * These are NOT read from disk. An attacker who modifies otter JSON files\n * in @stackwright-pro/otters cannot also modify these constants without\n * compromising the separately-published @stackwright-pro/mcp package.\n *\n * To update: node scripts/sync-mcp-checksums.cjs\n * (reads from packages/otters/src/checksums.json, writes this file)\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport { readFileSync, readdirSync, lstatSync } from 'fs';\nimport { join, basename } from 'path';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\n// ---------------------------------------------------------------------------\n// Certificate-pinned canonical checksums — frozen Map, immutable by design.\n// DO NOT read these from disk — that would defeat the entire purpose.\n// Object.freeze prevents property mutation at runtime; ReadonlyMap prevents\n// .set() / .delete() at compile time (belt-and-suspenders).\n// ---------------------------------------------------------------------------\n\nconst _checksums = new Map<string, string>([\n [\n 'stackwright-pro-api-otter.json',\n 'ed667124af3f025e090c0e65d0a86f0ef08fea06c0029b8fd0edf6df33df9f9c',\n ],\n [\n 'stackwright-pro-auth-otter.json',\n 'b5e901262d7b3f26ef390f1d3c9aadfa68376c05f5057edc241eb37b32b40afd',\n ],\n [\n 'stackwright-pro-dashboard-otter.json',\n '5e930b4092b9002e3c1a413b36418e49c865199af12a546890ccf7f9e56a5593',\n ],\n [\n 'stackwright-pro-data-otter.json',\n '04b07f982f73a2904a1d92c6af3c58ecc132b474c57cab3eaec8566d718d2623',\n ],\n [\n 'stackwright-pro-designer-otter.json',\n 'e80d4e7bab87d8647debadb238a58aac498ec5074ff25b21abd3b13ff778bf71',\n ],\n [\n 'stackwright-pro-foreman-otter.json',\n '02dd2485562361f2f3cfd998981349020d7599dcd2d969bb022f9f6d537f3517',\n ],\n [\n 'stackwright-pro-page-otter.json',\n 'd672dc4dfd6a3b6d66c6cec93c8db6075dcd4c8f1e8d15e2704aca2fca6856a6',\n ],\n [\n 'stackwright-pro-theme-otter.json',\n 'd3a15871b71a466c12c4711fe37cbb018c768cb99eff15c40dbbc7061d4e966b',\n ],\n [\n 'stackwright-pro-workflow-otter.json',\n '2ce1bcbb5c45dbb214499ea08c7175f8b743b51b8cb2ad539faf7df11edcf88a',\n ],\n]);\nObject.freeze(_checksums);\nconst CANONICAL_CHECKSUMS: ReadonlyMap<string, string> = _checksums;\n\n// ---------------------------------------------------------------------------\n// Import-time format validation — malformed constants are a packaging bug,\n// not a runtime surprise. Fail fast, fail loud.\n// ---------------------------------------------------------------------------\n\nconst SHA256_HEX_RE = /^[0-9a-f]{64}$/;\n\nfor (const [name, digest] of CANONICAL_CHECKSUMS) {\n if (!SHA256_HEX_RE.test(digest)) {\n throw new Error(\n `Malformed SHA-256 in CANONICAL_CHECKSUMS for \"${name}\": ` +\n `expected 64 hex chars, got ${digest.length}: \"${digest}\"`\n );\n }\n}\n\n// 1 MB — generous headroom for agent definitions; anything larger is suspicious.\nconst MAX_OTTER_BYTES = 1 * 1024 * 1024;\n\n// ---------------------------------------------------------------------------\n// Core functions (exported for direct testing — no MCP server needed)\n// ---------------------------------------------------------------------------\n\n/** Compute the hex-encoded SHA-256 digest of raw bytes. Pure, no I/O. */\nexport function computeSha256(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/** Constant-time comparison of two hex digest strings. */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));\n}\n\n// ---------------------------------------------------------------------------\n// Single-file verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyOtterFileResult {\n verified: boolean;\n filename: string;\n error?: string;\n}\n\n/**\n * Read a single otter JSON file, check its size, compute its SHA-256,\n * and constant-time compare against the canonical checksum.\n *\n * Single read → hash → decode. No TOCTOU window.\n */\nexport function verifyOtterFile(filePath: string): VerifyOtterFileResult {\n const filename = basename(filePath);\n\n // Fast-fail on unknown filenames before any I/O\n const expected = CANONICAL_CHECKSUMS.get(filename);\n if (expected === undefined) {\n return { verified: false, filename, error: `Unknown otter file: not in canonical set` };\n }\n\n // Symlink guard — refuse to follow symlinks (prevents symlink-based swaps)\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot stat file: ${msg}` };\n }\n\n if (stat.isSymbolicLink()) {\n return { verified: false, filename, error: 'Refusing to verify symlink' };\n }\n\n // Stat-based size pre-check — don't materialise oversized payloads\n const size = stat.size;\n\n if (size > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`,\n };\n }\n\n // Single read — used for hashing and UTF-8 validation (zero TOCTOU window)\n let raw: Buffer;\n try {\n raw = readFileSync(filePath);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { verified: false, filename, error: `Cannot read file: ${msg}` };\n }\n\n // Belt-and-suspenders: re-check length after read in case of a race\n if (raw.length > MAX_OTTER_BYTES) {\n return {\n verified: false,\n filename,\n error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`,\n };\n }\n\n // Hash the raw bytes\n const actual = computeSha256(raw);\n\n // Constant-time comparison prevents timing-oracle attacks\n if (!safeEqual(actual, expected)) {\n return {\n verified: false,\n filename,\n error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}…, got ${actual.substring(0, 8)}…`,\n };\n }\n\n // UTF-8 validation — binary injection guard\n try {\n const decoder = new TextDecoder('utf-8', { fatal: true });\n decoder.decode(raw);\n } catch {\n return {\n verified: false,\n filename,\n error: 'File is not valid UTF-8 — may be corrupted or contain binary injection',\n };\n }\n\n return { verified: true, filename };\n}\n\n// ---------------------------------------------------------------------------\n// Directory-level verification\n// ---------------------------------------------------------------------------\n\nexport interface VerifyAllOttersResult {\n verified: string[];\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Scan a directory for `*-otter.json` files, verify each one against\n * canonical checksums. Returns lists of verified, failed, and unknown files.\n */\nexport function verifyAllOtters(otterDir: string): VerifyAllOttersResult {\n // ---------------------------------------------------------------------------\n // Path traversal guard — reject any input containing \"..\" sequences before\n // any I/O. An attacker controlling this parameter could otherwise scan\n // directories outside the expected otter install locations.\n // ---------------------------------------------------------------------------\n if (/(?:^|[/\\\\])\\.\\.(?:[/\\\\]|$)/.test(otterDir) || otterDir.includes('..')) {\n return {\n verified: [],\n failed: [\n {\n filename: '<directory>',\n error: `Security: path traversal sequence detected in otter directory parameter`,\n },\n ],\n unknown: [],\n };\n }\n\n const verified: string[] = [];\n const failed: Array<{ filename: string; error: string }> = [];\n const unknown: string[] = [];\n\n let entries: string[];\n try {\n entries = readdirSync(otterDir);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n verified: [],\n failed: [{ filename: '<directory>', error: `Cannot read directory: ${msg}` }],\n unknown: [],\n };\n }\n\n const otterFiles = entries.filter((f) => f.endsWith('-otter.json'));\n\n for (const filename of otterFiles) {\n const filePath = join(otterDir, filename);\n\n // Skip symlinks at the directory-scan level too\n try {\n if (lstatSync(filePath).isSymbolicLink()) {\n failed.push({ filename, error: 'Skipped: symlink' });\n continue;\n }\n } catch {\n // verifyOtterFile will handle stat errors\n }\n\n const result = verifyOtterFile(filePath);\n\n if (result.verified) {\n verified.push(result.filename);\n } else if (result.error?.startsWith('Unknown otter file')) {\n unknown.push(result.filename);\n } else {\n failed.push({ filename: result.filename, error: result.error ?? 'Unknown error' });\n }\n }\n\n // Check for missing canonical files — ones we expect but didn't find on disk\n for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {\n if (!otterFiles.includes(canonicalName)) {\n failed.push({ filename: canonicalName, error: 'Missing from directory' });\n }\n }\n\n return { verified, failed, unknown };\n}\n\n// ---------------------------------------------------------------------------\n// Otter directory resolution\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SEARCH_PATHS = ['node_modules/@stackwright-pro/otters/src/', 'packages/otters/src/'];\n\nfunction resolveOtterDir(): string | null {\n const cwd = process.cwd();\n for (const relative of DEFAULT_SEARCH_PATHS) {\n const candidate = join(cwd, relative);\n try {\n lstatSync(candidate);\n return candidate;\n } catch {\n // Not found, try next\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Audit stream — SOC2 / FedRAMP / DoD ATO compliance\n// ---------------------------------------------------------------------------\n\n/**\n * Structured audit event parameters for an integrity failure.\n * Kept as a plain interface so callers can pass partial results without\n * constructing the full VerifyAllOttersResult.\n */\nexport interface IntegrityAuditEvent {\n otterDir: string;\n failed: Array<{ filename: string; error: string }>;\n unknown: string[];\n}\n\n/**\n * Emit a structured INTEGRITY_FAIL audit event to stderr.\n *\n * Writes a single line to process.stderr in the format:\n * INTEGRITY_FAIL {\"level\":\"AUDIT\",\"event\":\"INTEGRITY_FAIL\",...}\n *\n * The line prefix \"INTEGRITY_FAIL\" (without JSON) allows log shippers\n * (FluentBit, syslog, CloudWatch Logs, Splunk) to match and route the\n * event to a dedicated audit stream using a simple string filter, even\n * before attempting JSON parsing.\n *\n * Exported for unit testing. Do not call directly in production code —\n * use registerIntegrityTools() which calls this automatically.\n */\nexport function emitIntegrityAuditEvent(params: IntegrityAuditEvent): void {\n const record = JSON.stringify({\n level: 'AUDIT',\n event: 'INTEGRITY_FAIL',\n timestamp: new Date().toISOString(),\n source: 'stackwright_pro_verify_otter_integrity',\n otterDir: params.otterDir,\n failedCount: params.failed.length,\n unknownCount: params.unknown.length,\n failures: params.failed,\n unknown: params.unknown,\n });\n process.stderr.write(`INTEGRITY_FAIL ${record}\\n`);\n}\n\n// ---------------------------------------------------------------------------\n// MCP tool registration\n// ---------------------------------------------------------------------------\n\nexport function registerIntegrityTools(server: McpServer): void {\n server.tool(\n 'stackwright_pro_verify_otter_integrity',\n 'Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.',\n {},\n async () => {\n const resolved = resolveOtterDir();\n\n if (!resolved) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n error: true,\n message:\n 'Could not locate otter directory. Searched: ' + DEFAULT_SEARCH_PATHS.join(', '),\n }),\n },\n ],\n isError: true,\n };\n }\n\n const result = verifyAllOtters(resolved);\n\n const allGood = result.failed.length === 0 && result.unknown.length === 0;\n\n // Emit to dedicated audit stream for SOC2/FedRAMP/DoD ATO compliance\n if (!allGood) {\n emitIntegrityAuditEvent({\n otterDir: resolved,\n failed: result.failed,\n unknown: result.unknown,\n });\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n otterDir: resolved,\n totalCanonical: CANONICAL_CHECKSUMS.size,\n verifiedCount: result.verified.length,\n failedCount: result.failed.length,\n unknownCount: result.unknown.length,\n verified: result.verified,\n failed: result.failed,\n unknown: result.unknown,\n ...(allGood\n ? {}\n : {\n error:\n 'INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed — otter files may have been tampered with.',\n }),\n }),\n },\n ],\n isError: !allGood,\n };\n }\n );\n}\n"],"mappings":";AAiBA,SAAS,YAAY,uBAAuB;AAC5C,SAAS,cAAc,aAAa,iBAAiB;AACrD,SAAS,MAAM,gBAAgB;AAU/B,IAAM,aAAa,oBAAI,IAAoB;AAAA,EACzC;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AACF,CAAC;AACD,OAAO,OAAO,UAAU;AACxB,IAAM,sBAAmD;AAOzD,IAAM,gBAAgB;A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