@profullstack/threatcrush 0.7.1 → 0.7.2
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/daemon.js +1 -1
- package/dist/daemon.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/daemon.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js","../src/daemon/index.ts","../src/daemon/paths.ts","../src/daemon/pidfile.ts","../src/daemon/ipc-server.ts","../src/daemon/event-bus.ts","../src/core/state.ts","../src/daemon/module-host.ts","../src/daemon/watchers/log-watcher.ts","../src/core/log-parser.ts","../src/daemon/watchers/journal-watcher.ts","../src/modules/network-monitor/index.ts","../src/modules/dns-monitor/index.ts","../src/core/config.ts","../src/daemon/alerts/smtp.ts","../src/daemon/alerts/discord.ts","../src/daemon/alerts/pagerduty.ts","../src/daemon/alerts/index.ts","../src/core/cli-config.ts","../src/commands/scan.ts","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js","../src/core/logger.ts","../src/core/run-result.ts","../../../packages/scan/src/types.ts","../../../packages/scan/src/code-rules.ts","../../../packages/scan/src/manifest-rules.ts","../../../packages/scan/src/secret-rules.ts","../../../packages/scan/src/text.ts","../../../packages/scan/src/node/walk.ts","../../../packages/scan/src/node/dependencies.ts","../../../packages/scan/src/node/sarif.ts","../src/commands/pentest.ts","../src/daemon/workers/runs-worker.ts","../src/daemon/rules/engine.ts","../src/daemon/rules/loader.ts","../src/daemon/rules/default-rules.ts","../src/daemon/firewall/adapters.ts","../src/daemon/firewall/remediation.ts","../src/core/telemetry.ts","../src/daemon-entry.ts"],"sourcesContent":["'use strict'\nconst ParserEND = 0x110000\nclass ParserError extends Error {\n /* istanbul ignore next */\n constructor (msg, filename, linenumber) {\n super('[ParserError] ' + msg, filename, linenumber)\n this.name = 'ParserError'\n this.code = 'ParserError'\n if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError)\n }\n}\nclass State {\n constructor (parser) {\n this.parser = parser\n this.buf = ''\n this.returned = null\n this.result = null\n this.resultTable = null\n this.resultArr = null\n }\n}\nclass Parser {\n constructor () {\n this.pos = 0\n this.col = 0\n this.line = 0\n this.obj = {}\n this.ctx = this.obj\n this.stack = []\n this._buf = ''\n this.char = null\n this.ii = 0\n this.state = new State(this.parseStart)\n }\n\n parse (str) {\n /* istanbul ignore next */\n if (str.length === 0 || str.length == null) return\n\n this._buf = String(str)\n this.ii = -1\n this.char = -1\n let getNext\n while (getNext === false || this.nextChar()) {\n getNext = this.runOne()\n }\n this._buf = null\n }\n nextChar () {\n if (this.char === 0x0A) {\n ++this.line\n this.col = -1\n }\n ++this.ii\n this.char = this._buf.codePointAt(this.ii)\n ++this.pos\n ++this.col\n return this.haveBuffer()\n }\n haveBuffer () {\n return this.ii < this._buf.length\n }\n runOne () {\n return this.state.parser.call(this, this.state.returned)\n }\n finish () {\n this.char = ParserEND\n let last\n do {\n last = this.state.parser\n this.runOne()\n } while (this.state.parser !== last)\n\n this.ctx = null\n this.state = null\n this._buf = null\n\n return this.obj\n }\n next (fn) {\n /* istanbul ignore next */\n if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn))\n this.state.parser = fn\n }\n goto (fn) {\n this.next(fn)\n return this.runOne()\n }\n call (fn, returnWith) {\n if (returnWith) this.next(returnWith)\n this.stack.push(this.state)\n this.state = new State(fn)\n }\n callNow (fn, returnWith) {\n this.call(fn, returnWith)\n return this.runOne()\n }\n return (value) {\n /* istanbul ignore next */\n if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'))\n if (value === undefined) value = this.state.buf\n this.state = this.stack.pop()\n this.state.returned = value\n }\n returnNow (value) {\n this.return(value)\n return this.runOne()\n }\n consume () {\n /* istanbul ignore next */\n if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'))\n this.state.buf += this._buf[this.ii]\n }\n error (err) {\n err.line = this.line\n err.col = this.col\n err.pos = this.pos\n return err\n }\n /* istanbul ignore next */\n parseStart () {\n throw new ParserError('Must declare a parseStart method')\n }\n}\nParser.END = ParserEND\nParser.Error = ParserError\nmodule.exports = Parser\n","'use strict'\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nmodule.exports = (d, num) => {\n num = String(num)\n while (num.length < d) num = '0' + num\n return num\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass FloatingDateTime extends Date {\n constructor (value) {\n super(value + 'Z')\n this.isFloating = true\n }\n toISOString () {\n const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n return `${date}T${time}`\n }\n}\n\nmodule.exports = value => {\n const date = new FloatingDateTime(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\nconst DateTime = global.Date\n\nclass Date extends DateTime {\n constructor (value) {\n super(value)\n this.isDate = true\n }\n toISOString () {\n return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass Time extends Date {\n constructor (value) {\n super(`0000-01-01T${value}Z`)\n this.isTime = true\n }\n toISOString () {\n return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Time(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\n/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */\nmodule.exports = makeParserClass(require('./parser.js'))\nmodule.exports.makeParserClass = makeParserClass\n\nclass TomlError extends Error {\n constructor (msg) {\n super(msg)\n this.name = 'TomlError'\n /* istanbul ignore next */\n if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError)\n this.fromTOML = true\n this.wrapped = null\n }\n}\nTomlError.wrap = err => {\n const terr = new TomlError(err.message)\n terr.code = err.code\n terr.wrapped = err\n return terr\n}\nmodule.exports.TomlError = TomlError\n\nconst createDateTime = require('./create-datetime.js')\nconst createDateTimeFloat = require('./create-datetime-float.js')\nconst createDate = require('./create-date.js')\nconst createTime = require('./create-time.js')\n\nconst CTRL_I = 0x09\nconst CTRL_J = 0x0A\nconst CTRL_M = 0x0D\nconst CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL\nconst CHAR_SP = 0x20\nconst CHAR_QUOT = 0x22\nconst CHAR_NUM = 0x23\nconst CHAR_APOS = 0x27\nconst CHAR_PLUS = 0x2B\nconst CHAR_COMMA = 0x2C\nconst CHAR_HYPHEN = 0x2D\nconst CHAR_PERIOD = 0x2E\nconst CHAR_0 = 0x30\nconst CHAR_1 = 0x31\nconst CHAR_7 = 0x37\nconst CHAR_9 = 0x39\nconst CHAR_COLON = 0x3A\nconst CHAR_EQUALS = 0x3D\nconst CHAR_A = 0x41\nconst CHAR_E = 0x45\nconst CHAR_F = 0x46\nconst CHAR_T = 0x54\nconst CHAR_U = 0x55\nconst CHAR_Z = 0x5A\nconst CHAR_LOWBAR = 0x5F\nconst CHAR_a = 0x61\nconst CHAR_b = 0x62\nconst CHAR_e = 0x65\nconst CHAR_f = 0x66\nconst CHAR_i = 0x69\nconst CHAR_l = 0x6C\nconst CHAR_n = 0x6E\nconst CHAR_o = 0x6F\nconst CHAR_r = 0x72\nconst CHAR_s = 0x73\nconst CHAR_t = 0x74\nconst CHAR_u = 0x75\nconst CHAR_x = 0x78\nconst CHAR_z = 0x7A\nconst CHAR_LCUB = 0x7B\nconst CHAR_RCUB = 0x7D\nconst CHAR_LSQB = 0x5B\nconst CHAR_BSOL = 0x5C\nconst CHAR_RSQB = 0x5D\nconst CHAR_DEL = 0x7F\nconst SURROGATE_FIRST = 0xD800\nconst SURROGATE_LAST = 0xDFFF\n\nconst escapes = {\n [CHAR_b]: '\\u0008',\n [CHAR_t]: '\\u0009',\n [CHAR_n]: '\\u000A',\n [CHAR_f]: '\\u000C',\n [CHAR_r]: '\\u000D',\n [CHAR_QUOT]: '\\u0022',\n [CHAR_BSOL]: '\\u005C'\n}\n\nfunction isDigit (cp) {\n return cp >= CHAR_0 && cp <= CHAR_9\n}\nfunction isHexit (cp) {\n return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9)\n}\nfunction isBit (cp) {\n return cp === CHAR_1 || cp === CHAR_0\n}\nfunction isOctit (cp) {\n return (cp >= CHAR_0 && cp <= CHAR_7)\n}\nfunction isAlphaNumQuoteHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_APOS\n || cp === CHAR_QUOT\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nfunction isAlphaNumHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nconst _type = Symbol('type')\nconst _declared = Symbol('declared')\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst defineProperty = Object.defineProperty\nconst descriptor = {configurable: true, enumerable: true, writable: true, value: undefined}\n\nfunction hasKey (obj, key) {\n if (hasOwnProperty.call(obj, key)) return true\n if (key === '__proto__') defineProperty(obj, '__proto__', descriptor)\n return false\n}\n\nconst INLINE_TABLE = Symbol('inline-table')\nfunction InlineTable () {\n return Object.defineProperties({}, {\n [_type]: {value: INLINE_TABLE}\n })\n}\nfunction isInlineTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_TABLE\n}\n\nconst TABLE = Symbol('table')\nfunction Table () {\n return Object.defineProperties({}, {\n [_type]: {value: TABLE},\n [_declared]: {value: false, writable: true}\n })\n}\nfunction isTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === TABLE\n}\n\nconst _contentType = Symbol('content-type')\nconst INLINE_LIST = Symbol('inline-list')\nfunction InlineList (type) {\n return Object.defineProperties([], {\n [_type]: {value: INLINE_LIST},\n [_contentType]: {value: type}\n })\n}\nfunction isInlineList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_LIST\n}\n\nconst LIST = Symbol('list')\nfunction List () {\n return Object.defineProperties([], {\n [_type]: {value: LIST}\n })\n}\nfunction isList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === LIST\n}\n\n// in an eval, to let bundlers not slurp in a util proxy\nlet _custom\ntry {\n const utilInspect = eval(\"require('util').inspect\")\n _custom = utilInspect.custom\n} catch (_) {\n /* eval require not available in transpiled bundle */\n}\n/* istanbul ignore next */\nconst _inspect = _custom || 'inspect'\n\nclass BoxedBigInt {\n constructor (value) {\n try {\n this.value = global.BigInt.asIntN(64, value)\n } catch (_) {\n /* istanbul ignore next */\n this.value = null\n }\n Object.defineProperty(this, _type, {value: INTEGER})\n }\n isNaN () {\n return this.value === null\n }\n /* istanbul ignore next */\n toString () {\n return String(this.value)\n }\n /* istanbul ignore next */\n [_inspect] () {\n return `[BigInt: ${this.toString()}]}`\n }\n valueOf () {\n return this.value\n }\n}\n\nconst INTEGER = Symbol('integer')\nfunction Integer (value) {\n let num = Number(value)\n // -0 is a float thing, not an int thing\n if (Object.is(num, -0)) num = 0\n /* istanbul ignore else */\n if (global.BigInt && !Number.isSafeInteger(num)) {\n return new BoxedBigInt(value)\n } else {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(num), {\n isNaN: {value: function () { return isNaN(this) }},\n [_type]: {value: INTEGER},\n [_inspect]: {value: () => `[Integer: ${value}]`}\n })\n }\n}\nfunction isInteger (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INTEGER\n}\n\nconst FLOAT = Symbol('float')\nfunction Float (value) {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(value), {\n [_type]: {value: FLOAT},\n [_inspect]: {value: () => `[Float: ${value}]`}\n })\n}\nfunction isFloat (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === FLOAT\n}\n\nfunction tomlType (value) {\n const type = typeof value\n if (type === 'object') {\n /* istanbul ignore if */\n if (value === null) return 'null'\n if (value instanceof Date) return 'datetime'\n /* istanbul ignore else */\n if (_type in value) {\n switch (value[_type]) {\n case INLINE_TABLE: return 'inline-table'\n case INLINE_LIST: return 'inline-list'\n /* istanbul ignore next */\n case TABLE: return 'table'\n /* istanbul ignore next */\n case LIST: return 'list'\n case FLOAT: return 'float'\n case INTEGER: return 'integer'\n }\n }\n }\n return type\n}\n\nfunction makeParserClass (Parser) {\n class TOMLParser extends Parser {\n constructor () {\n super()\n this.ctx = this.obj = Table()\n }\n\n /* MATCH HELPER */\n atEndOfWord () {\n return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine()\n }\n atEndOfLine () {\n return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M\n }\n\n parseStart () {\n if (this.char === Parser.END) {\n return null\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseTableOrList)\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (isAlphaNumQuoteHyphen(this.char)) {\n return this.callNow(this.parseAssignStatement)\n } else {\n throw this.error(new TomlError(`Unknown character \"${this.char}\"`))\n }\n }\n\n // HELPER, this strips any whitespace and comments to the end of the line\n // then RETURNS. Last state in a production.\n parseWhitespaceToEOL () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.goto(this.parseComment)\n } else if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n } else {\n throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'))\n }\n }\n\n /* ASSIGNMENT: key = value */\n parseAssignStatement () {\n return this.callNow(this.parseAssign, this.recordAssignStatement)\n }\n recordAssignStatement (kv) {\n let target = this.ctx\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n // unbox our numbers\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseWhitespaceToEOL)\n }\n\n /* ASSSIGNMENT expression, key = value possibly inside an inline table */\n parseAssign () {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n recordAssignKeyword (key) {\n if (this.state.resultTable) {\n this.state.resultTable.push(key)\n } else {\n this.state.resultTable = [key]\n }\n return this.goto(this.parseAssignKeywordPreDot)\n }\n parseAssignKeywordPreDot () {\n if (this.char === CHAR_PERIOD) {\n return this.next(this.parseAssignKeywordPostDot)\n } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.goto(this.parseAssignEqual)\n }\n }\n parseAssignKeywordPostDot () {\n if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n }\n\n parseAssignEqual () {\n if (this.char === CHAR_EQUALS) {\n return this.next(this.parseAssignPreValue)\n } else {\n throw this.error(new TomlError('Invalid character, expected \"=\"'))\n }\n }\n parseAssignPreValue () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseValue, this.recordAssignValue)\n }\n }\n recordAssignValue (value) {\n return this.returnNow({key: this.state.resultTable, value: value})\n }\n\n /* COMMENTS: #...eol */\n parseComment () {\n do {\n if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n }\n } while (this.nextChar())\n }\n\n /* TABLES AND LISTS, [foo] and [[foo]] */\n parseTableOrList () {\n if (this.char === CHAR_LSQB) {\n this.next(this.parseList)\n } else {\n return this.goto(this.parseTable)\n }\n }\n\n /* TABLE [foo.bar.baz] */\n parseTable () {\n this.ctx = this.obj\n return this.goto(this.parseTableNext)\n }\n parseTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseTableMore)\n }\n }\n parseTableMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n } else {\n this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table()\n this.ctx[_declared] = true\n }\n return this.next(this.parseWhitespaceToEOL)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n return this.next(this.parseTableNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* LIST [[a.b.c]] */\n parseList () {\n this.ctx = this.obj\n return this.goto(this.parseListNext)\n }\n parseListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseListMore)\n }\n }\n parseListMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx[keyword] = List()\n }\n if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isList(this.ctx[keyword])) {\n const next = Table()\n this.ctx[keyword].push(next)\n this.ctx = next\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListEnd)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isInlineTable(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline table\"))\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n parseListEnd (keyword) {\n if (this.char === CHAR_RSQB) {\n return this.next(this.parseWhitespaceToEOL)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* VALUE string, number, boolean, inline list, inline object */\n parseValue () {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key without value'))\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseDoubleString)\n } if (this.char === CHAR_APOS) {\n return this.next(this.parseSingleString)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n return this.goto(this.parseNumberSign)\n } else if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseNumberOrDateTime)\n } else if (this.char === CHAR_t || this.char === CHAR_f) {\n return this.goto(this.parseBoolean)\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseInlineList, this.recordValue)\n } else if (this.char === CHAR_LCUB) {\n return this.call(this.parseInlineTable, this.recordValue)\n } else {\n throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'))\n }\n }\n recordValue (value) {\n return this.returnNow(value)\n }\n\n parseInf () {\n if (this.char === CHAR_n) {\n return this.next(this.parseInf2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n parseInf2 () {\n if (this.char === CHAR_f) {\n if (this.state.buf === '-') {\n return this.return(-Infinity)\n } else {\n return this.return(Infinity)\n }\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n\n parseNan () {\n if (this.char === CHAR_a) {\n return this.next(this.parseNan2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n parseNan2 () {\n if (this.char === CHAR_n) {\n return this.return(NaN)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n\n /* KEYS, barewords or basic, literal, or dotted */\n parseKeyword () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseBasicString)\n } else if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralString)\n } else {\n return this.goto(this.parseBareKey)\n }\n }\n\n /* KEYS: barewords */\n parseBareKey () {\n do {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key ended without value'))\n } else if (isAlphaNumHyphen(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 0) {\n throw this.error(new TomlError('Empty bare keys are not allowed'))\n } else {\n return this.returnNow()\n }\n } while (this.nextChar())\n }\n\n /* STRINGS, single quoted (literal) */\n parseSingleString () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiStringMaybe)\n } else {\n return this.goto(this.parseLiteralString)\n }\n }\n parseLiteralString () {\n do {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiStringMaybe () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseLiteralMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseLiteralMultiStringContent)\n } else {\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiStringContent () {\n do {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiEnd () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd2)\n } else {\n this.state.buf += \"'\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiEnd2 () {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else {\n this.state.buf += \"''\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n\n /* STRINGS double quoted */\n parseDoubleString () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiStringMaybe)\n } else {\n return this.goto(this.parseBasicString)\n }\n }\n parseBasicString () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseEscape, this.recordEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n recordEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseBasicString)\n }\n parseMultiStringMaybe () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseMultiStringContent)\n } else {\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiStringContent () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n errorControlCharInString () {\n let displayCode = '\\\\u00'\n if (this.char < 16) {\n displayCode += '0'\n }\n displayCode += this.char.toString(16)\n\n return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))\n }\n recordMultiEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseMultiStringContent)\n }\n parseMultiEnd () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd2)\n } else {\n this.state.buf += '\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEnd2 () {\n if (this.char === CHAR_QUOT) {\n return this.return()\n } else {\n this.state.buf += '\"\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEscape () {\n if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else if (this.char === CHAR_SP || this.char === CTRL_I) {\n return this.next(this.parsePreMultiTrim)\n } else {\n return this.goto(this.parseEscape)\n }\n }\n parsePreMultiTrim () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else {\n throw this.error(new TomlError(\"Can't escape whitespace\"))\n }\n }\n parseMultiTrim () {\n // explicitly whitespace here, END should follow the same path as chars\n if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else {\n return this.returnNow()\n }\n }\n parseEscape () {\n if (this.char in escapes) {\n return this.return(escapes[this.char])\n } else if (this.char === CHAR_u) {\n return this.call(this.parseSmallUnicode, this.parseUnicodeReturn)\n } else if (this.char === CHAR_U) {\n return this.call(this.parseLargeUnicode, this.parseUnicodeReturn)\n } else {\n throw this.error(new TomlError('Unknown escape character: ' + this.char))\n }\n }\n parseUnicodeReturn (char) {\n try {\n const codePoint = parseInt(char, 16)\n if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {\n throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'))\n }\n return this.returnNow(String.fromCodePoint(codePoint))\n } catch (err) {\n throw this.error(TomlError.wrap(err))\n }\n }\n parseSmallUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 4) return this.return()\n }\n }\n parseLargeUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 8) return this.return()\n }\n }\n\n /* NUMBERS */\n parseNumberSign () {\n this.consume()\n return this.next(this.parseMaybeSignedInfOrNan)\n }\n parseMaybeSignedInfOrNan () {\n if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else {\n return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart)\n }\n }\n parseNumberIntegerStart () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberIntegerExponentOrDecimal)\n } else {\n return this.goto(this.parseNumberInteger)\n }\n }\n parseNumberIntegerExponentOrDecimal () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseNumberInteger () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseNoUnder () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNoUnderHexOctBinLiteral () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNumberFloat () {\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n parseNumberExponentSign () {\n if (isDigit(this.char)) {\n return this.goto(this.parseNumberExponent)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.call(this.parseNoUnder, this.parseNumberExponent)\n } else {\n throw this.error(new TomlError('Unexpected character, expected -, + or digit'))\n }\n }\n parseNumberExponent () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n\n /* NUMBERS or DATETIMES */\n parseNumberOrDateTime () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberBaseOrDateTime)\n } else {\n return this.goto(this.parseNumberOrDateTimeOnly)\n }\n }\n parseNumberOrDateTimeOnly () {\n // note, if two zeros are in a row then it MUST be a date\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length > 4) this.next(this.parseNumberInteger)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseDateTimeOnly () {\n if (this.state.buf.length < 4) {\n if (isDigit(this.char)) {\n return this.consume()\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n throw this.error(new TomlError('Expected digit while parsing year part of a date'))\n }\n } else {\n if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else {\n throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'))\n }\n }\n }\n parseNumberBaseOrDateTime () {\n if (this.char === CHAR_b) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin)\n } else if (this.char === CHAR_o) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct)\n } else if (this.char === CHAR_x) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex)\n } else if (this.char === CHAR_PERIOD) {\n return this.goto(this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseDateTimeOnly)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseIntegerHex () {\n if (isHexit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerOct () {\n if (isOctit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerBin () {\n if (isBit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n\n /* DATETIME */\n parseDateTime () {\n // we enter here having just consumed the year and about to consume the hyphen\n if (this.state.buf.length < 4) {\n throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateMonth)\n }\n parseDateMonth () {\n if (this.char === CHAR_HYPHEN) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateDay)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseDateDay () {\n if (this.char === CHAR_T || this.char === CHAR_SP) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseStartTimeHour)\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result + '-' + this.state.buf))\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseStartTimeHour () {\n if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result))\n } else {\n return this.goto(this.parseTimeHour)\n }\n }\n parseTimeHour () {\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result += 'T' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeMin)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeZoneOrFraction)\n }\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n\n parseOnlyTimeHour () {\n /* istanbul ignore else */\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeMin)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n return this.next(this.parseOnlyTimeFractionMaybe)\n }\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeFractionMaybe () {\n this.state.result += ':' + this.state.buf\n if (this.char === CHAR_PERIOD) {\n this.state.buf = ''\n this.next(this.parseOnlyTimeFraction)\n } else {\n return this.return(createTime(this.state.result))\n }\n }\n parseOnlyTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.atEndOfWord()) {\n if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'))\n return this.returnNow(createTime(this.state.result + '.' + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n\n parseTimeZoneOrFraction () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n this.next(this.parseDateTimeFraction)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseDateTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 1) {\n throw this.error(new TomlError('Expected digit in milliseconds'))\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseTimeZoneHour () {\n if (isDigit(this.char)) {\n this.consume()\n // FIXME: No more regexps\n if (/\\d\\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n parseTimeZoneSep () {\n if (this.char === CHAR_COLON) {\n this.consume()\n this.next(this.parseTimeZoneMin)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected colon'))\n }\n }\n parseTimeZoneMin () {\n if (isDigit(this.char)) {\n this.consume()\n if (/\\d\\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n\n /* BOOLEAN */\n parseBoolean () {\n /* istanbul ignore else */\n if (this.char === CHAR_t) {\n this.consume()\n return this.next(this.parseTrue_r)\n } else if (this.char === CHAR_f) {\n this.consume()\n return this.next(this.parseFalse_a)\n }\n }\n parseTrue_r () {\n if (this.char === CHAR_r) {\n this.consume()\n return this.next(this.parseTrue_u)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_u () {\n if (this.char === CHAR_u) {\n this.consume()\n return this.next(this.parseTrue_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_e () {\n if (this.char === CHAR_e) {\n return this.return(true)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_a () {\n if (this.char === CHAR_a) {\n this.consume()\n return this.next(this.parseFalse_l)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_l () {\n if (this.char === CHAR_l) {\n this.consume()\n return this.next(this.parseFalse_s)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_s () {\n if (this.char === CHAR_s) {\n this.consume()\n return this.next(this.parseFalse_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_e () {\n if (this.char === CHAR_e) {\n return this.return(false)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n /* INLINE LISTS */\n parseInlineList () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_RSQB) {\n return this.return(this.state.resultArr || InlineList())\n } else {\n return this.callNow(this.parseValue, this.recordInlineListValue)\n }\n }\n recordInlineListValue (value) {\n if (this.state.resultArr) {\n const listType = this.state.resultArr[_contentType]\n const valueType = tomlType(value)\n if (listType !== valueType) {\n throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))\n }\n } else {\n this.state.resultArr = InlineList(tomlType(value))\n }\n if (isFloat(value) || isInteger(value)) {\n // unbox now that we've verified they're ok\n this.state.resultArr.push(value.valueOf())\n } else {\n this.state.resultArr.push(value)\n }\n return this.goto(this.parseInlineListNext)\n }\n parseInlineListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineList)\n } else if (this.char === CHAR_RSQB) {\n return this.goto(this.parseInlineList)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n\n /* INLINE TABLE */\n parseInlineTable () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_RCUB) {\n return this.return(this.state.resultTable || InlineTable())\n } else {\n if (!this.state.resultTable) this.state.resultTable = InlineTable()\n return this.callNow(this.parseAssign, this.recordInlineTableValue)\n }\n }\n recordInlineTableValue (kv) {\n let target = this.state.resultTable\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseInlineTableNext)\n }\n parseInlineTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineTable)\n } else if (this.char === CHAR_RCUB) {\n return this.goto(this.parseInlineTable)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n }\n return TOMLParser\n}\n","'use strict'\nmodule.exports = prettyError\n\nfunction prettyError (err, buf) {\n /* istanbul ignore if */\n if (err.pos == null || err.line == null) return err\n let msg = err.message\n msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\\n`\n\n /* istanbul ignore else */\n if (buf && buf.split) {\n const lines = buf.split(/\\n/)\n const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length\n let linePadding = ' '\n while (linePadding.length < lineNumWidth) linePadding += ' '\n for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {\n let lineNum = String(ii + 1)\n if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum\n if (err.line === ii) {\n msg += lineNum + '> ' + lines[ii] + '\\n'\n msg += linePadding + ' '\n for (let hh = 0; hh < err.col; ++hh) {\n msg += ' '\n }\n msg += '^\\n'\n } else {\n msg += lineNum + ': ' + lines[ii] + '\\n'\n }\n }\n }\n err.message = msg + '\\n'\n return err\n}\n","'use strict'\nmodule.exports = parseString\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseString (str) {\n if (global.Buffer && global.Buffer.isBuffer(str)) {\n str = str.toString('utf8')\n }\n const parser = new TOMLParser()\n try {\n parser.parse(str)\n return parser.finish()\n } catch (err) {\n throw prettyError(err, str)\n }\n}\n","'use strict'\nmodule.exports = parseAsync\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseAsync (str, opts) {\n if (!opts) opts = {}\n const index = 0\n const blocksize = opts.blocksize || 40960\n const parser = new TOMLParser()\n return new Promise((resolve, reject) => {\n setImmediate(parseAsyncNext, index, blocksize, resolve, reject)\n })\n function parseAsyncNext (index, blocksize, resolve, reject) {\n if (index >= str.length) {\n try {\n return resolve(parser.finish())\n } catch (err) {\n return reject(prettyError(err, str))\n }\n }\n try {\n parser.parse(str.slice(index, index + blocksize))\n setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject)\n } catch (err) {\n reject(prettyError(err, str))\n }\n }\n}\n","'use strict'\nmodule.exports = parseStream\n\nconst stream = require('stream')\nconst TOMLParser = require('./lib/toml-parser.js')\n\nfunction parseStream (stm) {\n if (stm) {\n return parseReadable(stm)\n } else {\n return parseTransform(stm)\n }\n}\n\nfunction parseReadable (stm) {\n const parser = new TOMLParser()\n stm.setEncoding('utf8')\n return new Promise((resolve, reject) => {\n let readable\n let ended = false\n let errored = false\n function finish () {\n ended = true\n if (readable) return\n try {\n resolve(parser.finish())\n } catch (err) {\n reject(err)\n }\n }\n function error (err) {\n errored = true\n reject(err)\n }\n stm.once('end', finish)\n stm.once('error', error)\n readNext()\n\n function readNext () {\n readable = true\n let data\n while ((data = stm.read()) !== null) {\n try {\n parser.parse(data)\n } catch (err) {\n return error(err)\n }\n }\n readable = false\n /* istanbul ignore if */\n if (ended) return finish()\n /* istanbul ignore if */\n if (errored) return\n stm.once('readable', readNext)\n }\n })\n}\n\nfunction parseTransform () {\n const parser = new TOMLParser()\n return new stream.Transform({\n objectMode: true,\n transform (chunk, encoding, cb) {\n try {\n parser.parse(chunk.toString(encoding))\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n },\n flush (cb) {\n try {\n this.push(parser.finish())\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n }\n })\n}\n","'use strict'\nmodule.exports = require('./parse-string.js')\nmodule.exports.async = require('./parse-async.js')\nmodule.exports.stream = require('./parse-stream.js')\nmodule.exports.prettyError = require('./parse-pretty-error.js')\n","'use strict'\nmodule.exports = stringify\nmodule.exports.value = stringifyInline\n\nfunction stringify (obj) {\n if (obj === null) throw typeError('null')\n if (obj === void (0)) throw typeError('undefined')\n if (typeof obj !== 'object') throw typeError(typeof obj)\n\n if (typeof obj.toJSON === 'function') obj = obj.toJSON()\n if (obj == null) return null\n const type = tomlType(obj)\n if (type !== 'table') throw typeError(type)\n return stringifyObject('', '', obj)\n}\n\nfunction typeError (type) {\n return new Error('Can only stringify objects, not ' + type)\n}\n\nfunction arrayOneTypeError () {\n return new Error(\"Array values can't have mixed types\")\n}\n\nfunction getInlineKeys (obj) {\n return Object.keys(obj).filter(key => isInline(obj[key]))\n}\nfunction getComplexKeys (obj) {\n return Object.keys(obj).filter(key => !isInline(obj[key]))\n}\n\nfunction toJSON (obj) {\n let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}\n for (let prop of Object.keys(obj)) {\n if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {\n nobj[prop] = obj[prop].toJSON()\n } else {\n nobj[prop] = obj[prop]\n }\n }\n return nobj\n}\n\nfunction stringifyObject (prefix, indent, obj) {\n obj = toJSON(obj)\n var inlineKeys\n var complexKeys\n inlineKeys = getInlineKeys(obj)\n complexKeys = getComplexKeys(obj)\n var result = []\n var inlineIndent = indent || ''\n inlineKeys.forEach(key => {\n var type = tomlType(obj[key])\n if (type !== 'undefined' && type !== 'null') {\n result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))\n }\n })\n if (result.length > 0) result.push('')\n var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''\n complexKeys.forEach(key => {\n result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))\n })\n return result.join('\\n')\n}\n\nfunction isInline (value) {\n switch (tomlType(value)) {\n case 'undefined':\n case 'null':\n case 'integer':\n case 'nan':\n case 'float':\n case 'boolean':\n case 'string':\n case 'datetime':\n return true\n case 'array':\n return value.length === 0 || tomlType(value[0]) !== 'table'\n case 'table':\n return Object.keys(value).length === 0\n /* istanbul ignore next */\n default:\n return false\n }\n}\n\nfunction tomlType (value) {\n if (value === undefined) {\n return 'undefined'\n } else if (value === null) {\n return 'null'\n /* eslint-disable valid-typeof */\n } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {\n return 'integer'\n } else if (typeof value === 'number') {\n return 'float'\n } else if (typeof value === 'boolean') {\n return 'boolean'\n } else if (typeof value === 'string') {\n return 'string'\n } else if ('toISOString' in value) {\n return isNaN(value) ? 'undefined' : 'datetime'\n } else if (Array.isArray(value)) {\n return 'array'\n } else {\n return 'table'\n }\n}\n\nfunction stringifyKey (key) {\n var keyStr = String(key)\n if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {\n return keyStr\n } else {\n return stringifyBasicString(keyStr)\n }\n}\n\nfunction stringifyBasicString (str) {\n return '\"' + escapeString(str).replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction stringifyLiteralString (str) {\n return \"'\" + str + \"'\"\n}\n\nfunction numpad (num, str) {\n while (str.length < num) str = '0' + str\n return str\n}\n\nfunction escapeString (str) {\n return str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/[\\b]/g, '\\\\b')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\f/g, '\\\\f')\n .replace(/\\r/g, '\\\\r')\n /* eslint-disable no-control-regex */\n .replace(/([\\u0000-\\u001f\\u007f])/, c => '\\\\u' + numpad(4, c.codePointAt(0).toString(16)))\n /* eslint-enable no-control-regex */\n}\n\nfunction stringifyMultilineString (str) {\n let escaped = str.split(/\\n/).map(str => {\n return escapeString(str).replace(/\"(?=\"\")/g, '\\\\\"')\n }).join('\\n')\n if (escaped.slice(-1) === '\"') escaped += '\\\\\\n'\n return '\"\"\"\\n' + escaped + '\"\"\"'\n}\n\nfunction stringifyAnyInline (value, multilineOk) {\n let type = tomlType(value)\n if (type === 'string') {\n if (multilineOk && /\\n/.test(value)) {\n type = 'string-multiline'\n } else if (!/[\\b\\t\\n\\f\\r']/.test(value) && /\"/.test(value)) {\n type = 'string-literal'\n }\n }\n return stringifyInline(value, type)\n}\n\nfunction stringifyInline (value, type) {\n /* istanbul ignore if */\n if (!type) type = tomlType(value)\n switch (type) {\n case 'string-multiline':\n return stringifyMultilineString(value)\n case 'string':\n return stringifyBasicString(value)\n case 'string-literal':\n return stringifyLiteralString(value)\n case 'integer':\n return stringifyInteger(value)\n case 'float':\n return stringifyFloat(value)\n case 'boolean':\n return stringifyBoolean(value)\n case 'datetime':\n return stringifyDatetime(value)\n case 'array':\n return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))\n case 'table':\n return stringifyInlineTable(value)\n /* istanbul ignore next */\n default:\n throw typeError(type)\n }\n}\n\nfunction stringifyInteger (value) {\n /* eslint-disable security/detect-unsafe-regex */\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, '_')\n}\n\nfunction stringifyFloat (value) {\n if (value === Infinity) {\n return 'inf'\n } else if (value === -Infinity) {\n return '-inf'\n } else if (Object.is(value, NaN)) {\n return 'nan'\n } else if (Object.is(value, -0)) {\n return '-0.0'\n }\n var chunks = String(value).split('.')\n var int = chunks[0]\n var dec = chunks[1] || 0\n return stringifyInteger(int) + '.' + dec\n}\n\nfunction stringifyBoolean (value) {\n return String(value)\n}\n\nfunction stringifyDatetime (value) {\n return value.toISOString()\n}\n\nfunction isNumber (type) {\n return type === 'float' || type === 'integer'\n}\nfunction arrayType (values) {\n var contentType = tomlType(values[0])\n if (values.every(_ => tomlType(_) === contentType)) return contentType\n // mixed integer/float, emit as floats\n if (values.every(_ => isNumber(tomlType(_)))) return 'float'\n return 'mixed'\n}\nfunction validateArray (values) {\n const type = arrayType(values)\n if (type === 'mixed') {\n throw arrayOneTypeError()\n }\n return type\n}\n\nfunction stringifyInlineArray (values) {\n values = toJSON(values)\n const type = validateArray(values)\n var result = '['\n var stringified = values.map(_ => stringifyInline(_, type))\n if (stringified.join(', ').length > 60 || /\\n/.test(stringified)) {\n result += '\\n ' + stringified.join(',\\n ') + '\\n'\n } else {\n result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')\n }\n return result + ']'\n}\n\nfunction stringifyInlineTable (value) {\n value = toJSON(value)\n var result = []\n Object.keys(value).forEach(key => {\n result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))\n })\n return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'\n}\n\nfunction stringifyComplex (prefix, indent, key, value) {\n var valueType = tomlType(value)\n /* istanbul ignore else */\n if (valueType === 'array') {\n return stringifyArrayOfTables(prefix, indent, key, value)\n } else if (valueType === 'table') {\n return stringifyComplexTable(prefix, indent, key, value)\n } else {\n throw typeError(valueType)\n }\n}\n\nfunction stringifyArrayOfTables (prefix, indent, key, values) {\n values = toJSON(values)\n validateArray(values)\n var firstValueType = tomlType(values[0])\n /* istanbul ignore if */\n if (firstValueType !== 'table') throw typeError(firstValueType)\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n values.forEach(table => {\n if (result.length > 0) result += '\\n'\n result += indent + '[[' + fullKey + ']]\\n'\n result += stringifyObject(fullKey + '.', indent, table)\n })\n return result\n}\n\nfunction stringifyComplexTable (prefix, indent, key, value) {\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n if (getInlineKeys(value).length > 0) {\n result += indent + '[' + fullKey + ']\\n'\n }\n return result + stringifyObject(fullKey + '.', indent, value)\n}\n","'use strict'\nexports.parse = require('./parse.js')\nexports.stringify = require('./stringify.js')\n","import { appendFileSync, existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PATHS, ensureRuntimeDirs } from './paths.js';\nimport { findRunningDaemon, removePidFile, writePidFile } from './pidfile.js';\nimport { IpcServer } from './ipc-server.js';\nimport { ModuleHost } from './module-host.js';\nimport { AlertDispatcher } from './alerts/index.js';\nimport { RunsWorker } from './workers/runs-worker.js';\nimport { RuleEngine } from './rules/engine.js';\nimport { loadAllRules } from './rules/loader.js';\nimport { detectFirewallAdapter } from './firewall/adapters.js';\nimport { RemediationManager } from './firewall/remediation.js';\nimport { bus } from './event-bus.js';\nimport { initStateDB, closeDB } from '../core/state.js';\nimport { loadConfig } from '../core/config.js';\nimport { captureException, flushTelemetry, initTelemetry } from '../core/telemetry.js';\nimport type { ThreatEvent } from '../types/events.js';\n\nfunction readVersion(): string {\n try {\n const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));\n return pkg.version || '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction logLine(line: string): void {\n try {\n appendFileSync(PATHS.logFile, `${new Date().toISOString()} ${line}\\n`);\n } catch {\n // best-effort\n }\n}\n\nexport async function runDaemon(): Promise<void> {\n if (findRunningDaemon()) {\n console.error(`threatcrushd already running (pid file at ${PATHS.pidFile}).`);\n process.exit(1);\n }\n\n ensureRuntimeDirs();\n writePidFile();\n\n await initTelemetry('daemon');\n process.on('uncaughtException', (err) => {\n logLine(`[daemon] uncaughtException: ${err.message}`);\n captureException(err);\n });\n process.on('unhandledRejection', (reason) => {\n logLine(`[daemon] unhandledRejection: ${String(reason)}`);\n captureException(reason);\n });\n\n const version = readVersion();\n logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);\n\n try {\n initStateDB(PATHS.stateDb);\n } catch (err) {\n logLine(`[daemon] state db unavailable: ${(err as Error).message}`);\n }\n\n const config = loadConfig(existsSync(PATHS.configFile) ? PATHS.configFile : undefined);\n\n bus.on('event', (event: ThreatEvent) => {\n logLine(`[event] ${event.severity} ${event.module} ${event.message}`);\n });\n\n const moduleHost = new ModuleHost(bus);\n await moduleHost.start();\n\n // Detection rule engine (PRD 01)\n const ruleEngine = new RuleEngine((detection) => {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'rule-engine',\n category: (detection.raw_metadata?.category as any) || 'system',\n severity: detection.severity,\n message: `[DETECTION] ${detection.title}`,\n source_ip: detection.source_ip,\n details: {\n rule_id: detection.rule_id,\n username: detection.username,\n ...detection.raw_metadata,\n },\n };\n bus.publish(event);\n });\n ruleEngine.loadRules(loadAllRules());\n bus.on('event', (event) => {\n if (event.module !== 'rule-engine') ruleEngine.evaluate(event);\n });\n logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);\n setInterval(() => ruleEngine.cleanup(), 300_000);\n\n // Firewall auto-remediation (PRD 02)\n const firewallAdapter = detectFirewallAdapter();\n const remediation = new RemediationManager(firewallAdapter, bus, (config as any).remediation);\n bus.on('event', (event) => {\n if (event.module !== 'firewall-rules') {\n void remediation.handleDetection(event);\n }\n });\n logLine(`[daemon] firewall remediation active (backend=${firewallAdapter.name}, dry_run=${(config as any).remediation?.dry_run ?? true})`);\n\n new AlertDispatcher(bus, config);\n\n const runsWorker = new RunsWorker(bus);\n try {\n await runsWorker.start();\n } catch (err) {\n logLine(`[daemon] runs-worker failed to start: ${(err as Error).message}`);\n }\n\n const ipc = new IpcServer(version, moduleHost);\n await ipc.start();\n logLine(`[daemon] ipc listening on ${PATHS.socket}`);\n\n const shutdown = async (signal: string) => {\n logLine(`[daemon] received ${signal}, shutting down`);\n try { remediation.stop(); } catch {}\n try { runsWorker.stop(); } catch {}\n try { await moduleHost.stop(); } catch {}\n try { await ipc.stop(); } catch {}\n try { closeDB(); } catch {}\n try { await flushTelemetry(); } catch {}\n removePidFile();\n process.exit(0);\n };\n\n process.on('SIGINT', () => { void shutdown('SIGINT'); });\n process.on('SIGTERM', () => { void shutdown('SIGTERM'); });\n process.on('SIGHUP', () => { void shutdown('SIGHUP'); });\n\n // keep-alive\n setInterval(() => {}, 1 << 30);\n}\n\n// Note: auto-boot is handled by `src/daemon-entry.ts` so that importing this\n// module from the CLI bundle never accidentally starts a daemon.\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nfunction isRoot(): boolean {\n return (\n process.platform === 'linux' &&\n typeof process.getuid === 'function' &&\n process.getuid() === 0\n );\n}\n\nconst userBase = join(homedir(), '.threatcrush');\n\nconst SYSTEM_PATHS = {\n mode: 'system' as const,\n configDir: '/etc/threatcrush',\n configFile: '/etc/threatcrush/threatcrushd.conf',\n confD: '/etc/threatcrush/threatcrushd.conf.d',\n moduleDir: '/etc/threatcrush/modules',\n logDir: '/var/log/threatcrush',\n logFile: '/var/log/threatcrush/threatcrushd.log',\n stateDir: '/var/lib/threatcrush',\n stateDb: '/var/lib/threatcrush/state.db',\n runDir: '/var/run/threatcrush',\n pidFile: '/var/run/threatcrush/threatcrushd.pid',\n socket: '/var/run/threatcrush/threatcrushd.sock',\n};\n\nconst USER_PATHS = {\n mode: 'user' as const,\n configDir: userBase,\n configFile: join(userBase, 'threatcrushd.conf'),\n confD: join(userBase, 'threatcrushd.conf.d'),\n moduleDir: join(userBase, 'modules'),\n logDir: join(userBase, 'logs'),\n logFile: join(userBase, 'logs', 'threatcrushd.log'),\n stateDir: join(userBase, 'state'),\n stateDb: join(userBase, 'state', 'state.db'),\n runDir: join(userBase, 'run'),\n pidFile: join(userBase, 'run', 'threatcrushd.pid'),\n socket: join(userBase, 'run', 'threatcrushd.sock'),\n};\n\n// System paths (config/log/state/run under /etc and /var) are root-owned, so we\n// only run in system mode when actually root. Choosing system mode because\n// /etc/threatcrush happened to be writable, or because a stale system socket\n// existed, made `threatcrush start` as a normal user crash with EACCES trying\n// to open /var/log/threatcrush/threatcrushd.log. A non-root user always runs a\n// self-contained daemon under ~/.threatcrush instead.\nexport const PATHS = isRoot() ? SYSTEM_PATHS : USER_PATHS;\n\n// A non-root client command (status/stop/logs/tail) should still be able to\n// reach a daemon that root started. Prefer this process's own socket, but fall\n// back to the other mode's socket when only that one is present.\nexport function resolveClientSocket(): string {\n if (existsSync(PATHS.socket)) return PATHS.socket;\n const other = PATHS.mode === 'system' ? USER_PATHS.socket : SYSTEM_PATHS.socket;\n if (existsSync(other)) return other;\n return PATHS.socket;\n}\n\nexport function ensureRuntimeDirs(): void {\n for (const dir of [PATHS.configDir, PATHS.confD, PATHS.moduleDir, PATHS.logDir, PATHS.stateDir, PATHS.runDir]) {\n try {\n mkdirSync(dir, { recursive: true });\n } catch {\n // best-effort\n }\n }\n}\n","import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { PATHS, ensureRuntimeDirs } from './paths.js';\n\nexport function writePidFile(): void {\n ensureRuntimeDirs();\n writeFileSync(PATHS.pidFile, String(process.pid), 'utf-8');\n}\n\nexport function readPidFile(): number | null {\n if (!existsSync(PATHS.pidFile)) return null;\n const raw = readFileSync(PATHS.pidFile, 'utf-8').trim();\n const pid = parseInt(raw, 10);\n return Number.isFinite(pid) ? pid : null;\n}\n\nexport function removePidFile(): void {\n try {\n if (existsSync(PATHS.pidFile)) unlinkSync(PATHS.pidFile);\n } catch {\n // ignore\n }\n}\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means the process exists but the current user can't signal it\n // (common: a non-root client checking on a system-mode daemon running as\n // root). Only ESRCH means the process is actually gone.\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'EPERM';\n }\n}\n\nexport function findRunningDaemon(): number | null {\n const pid = readPidFile();\n if (pid && isProcessAlive(pid)) return pid;\n if (pid) removePidFile();\n return null;\n}\n","import { createServer, Server, Socket } from 'node:net';\nimport { existsSync, unlinkSync } from 'node:fs';\nimport type { ThreatEvent } from '../types/events.js';\nimport { PATHS } from './paths.js';\nimport { bus } from './event-bus.js';\nimport { getRecentEvents, getTopSources, getEventCount, getThreatCount } from '../core/state.js';\nimport type {\n IpcRequest,\n IpcResponse,\n IpcPush,\n DaemonStatusReply,\n} from './ipc-protocol.js';\nimport type { ModuleHost } from './module-host.js';\n\ninterface ClientState {\n id: number;\n socket: Socket;\n buffer: string;\n subscriptions: Set<'event' | 'module'>;\n}\n\nexport class IpcServer {\n private server: Server | null = null;\n private clients = new Map<number, ClientState>();\n private nextClientId = 1;\n private startedAt = new Date();\n private counters = { events: 0, threats: 0, alerts: 0 };\n\n constructor(\n private version: string,\n private moduleHost: ModuleHost,\n ) {\n bus.on('event', (event: ThreatEvent) => {\n this.counters.events++;\n if (event.severity === 'medium' || event.severity === 'high' || event.severity === 'critical') {\n this.counters.threats++;\n }\n this.broadcast({ push: 'event', payload: event }, 'event');\n });\n bus.on('alert', () => {\n this.counters.alerts++;\n });\n bus.on('module', (info) => {\n this.broadcast({ push: 'module', payload: info }, 'module');\n });\n }\n\n async start(): Promise<void> {\n if (existsSync(PATHS.socket)) {\n try { unlinkSync(PATHS.socket); } catch {}\n }\n return new Promise((resolve, reject) => {\n this.server = createServer((sock) => this.handleClient(sock));\n this.server.on('error', reject);\n this.server.listen(PATHS.socket, () => {\n const nodeFs = require('node:fs') as typeof import('node:fs');\n try { nodeFs.chmodSync(PATHS.socket, 0o660); } catch {}\n // When the daemon runs as root (system mode under systemd), regroup\n // the socket to `adm` so users in that group can talk to the daemon\n // without sudo. We use this group because it's the same one that\n // already governs read access to /var/log/{auth,syslog,nginx} — the\n // intent is \"people who can already inspect logs can talk to the\n // agent that watches them.\"\n const isRoot = process.platform === 'linux'\n && typeof process.getuid === 'function'\n && process.getuid() === 0;\n if (isRoot) {\n try {\n const { gid } = nodeFs.statSync('/var/log/auth.log');\n nodeFs.chownSync(PATHS.socket, 0, gid);\n } catch {\n // adm group not present, or /var/log/auth.log missing — leave as root:root\n }\n }\n resolve();\n });\n });\n }\n\n async stop(): Promise<void> {\n for (const c of this.clients.values()) {\n try { c.socket.destroy(); } catch {}\n }\n this.clients.clear();\n return new Promise((resolve) => {\n if (!this.server) {\n try { if (existsSync(PATHS.socket)) unlinkSync(PATHS.socket); } catch {}\n return resolve();\n }\n this.server.close(() => {\n try { if (existsSync(PATHS.socket)) unlinkSync(PATHS.socket); } catch {}\n resolve();\n });\n });\n }\n\n private handleClient(socket: Socket): void {\n const id = this.nextClientId++;\n const state: ClientState = { id, socket, buffer: '', subscriptions: new Set() };\n this.clients.set(id, state);\n\n socket.setEncoding('utf-8');\n socket.on('data', (chunk) => {\n state.buffer += chunk.toString();\n let idx;\n while ((idx = state.buffer.indexOf('\\n')) >= 0) {\n const line = state.buffer.slice(0, idx);\n state.buffer = state.buffer.slice(idx + 1);\n if (!line.trim()) continue;\n this.handleLine(state, line).catch((err) => {\n this.send(state, { id: 0, ok: false, error: String(err?.message || err) });\n });\n }\n });\n\n socket.on('close', () => { this.clients.delete(id); });\n socket.on('error', () => { this.clients.delete(id); });\n }\n\n private async handleLine(client: ClientState, line: string): Promise<void> {\n let req: IpcRequest;\n try {\n req = JSON.parse(line) as IpcRequest;\n } catch {\n return this.send(client, { id: 0, ok: false, error: 'invalid json' });\n }\n\n switch (req.method) {\n case 'ping':\n return this.send(client, { id: req.id, ok: true, result: 'pong' });\n\n case 'status': {\n const status: DaemonStatusReply = {\n pid: process.pid,\n startedAt: this.startedAt.toISOString(),\n uptimeSeconds: Math.floor((Date.now() - this.startedAt.getTime()) / 1000),\n version: this.version,\n mode: PATHS.mode,\n paths: {\n config: PATHS.configFile,\n log: PATHS.logFile,\n state: PATHS.stateDb,\n socket: PATHS.socket,\n },\n modules: this.moduleHost.summary(),\n counters: { ...this.counters },\n };\n return this.send(client, { id: req.id, ok: true, result: status });\n }\n\n case 'recent_events': {\n const limit = req.params?.limit ?? 50;\n const events = getRecentEvents(limit);\n return this.send(client, { id: req.id, ok: true, result: events });\n }\n\n case 'top_sources': {\n const limit = req.params?.limit ?? 10;\n return this.send(client, { id: req.id, ok: true, result: getTopSources(limit) });\n }\n\n case 'counters': {\n return this.send(client, {\n id: req.id,\n ok: true,\n result: {\n total: getEventCount(),\n threats: getThreatCount(),\n last24h: getEventCount(new Date(Date.now() - 86400000)),\n threats24h: getThreatCount(new Date(Date.now() - 86400000)),\n },\n });\n }\n\n case 'module_list':\n return this.send(client, { id: req.id, ok: true, result: this.moduleHost.summary() });\n\n case 'subscribe':\n for (const ch of req.params.channels) client.subscriptions.add(ch);\n return this.send(client, { id: req.id, ok: true, result: { subscribed: [...client.subscriptions] } });\n\n case 'shutdown':\n this.send(client, { id: req.id, ok: true, result: 'shutting down' });\n setTimeout(() => process.emit('SIGTERM' as NodeJS.Signals), 50);\n return;\n }\n }\n\n private send(client: ClientState, msg: IpcResponse | IpcPush): void {\n try {\n client.socket.write(JSON.stringify(msg) + '\\n');\n } catch {\n // client gone\n }\n }\n\n private broadcast(msg: IpcPush, channel: 'event' | 'module'): void {\n for (const client of this.clients.values()) {\n if (!client.subscriptions.has(channel)) continue;\n this.send(client, msg);\n }\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { ThreatEvent } from '../types/events.js';\n\nexport interface DaemonEvents {\n event: (event: ThreatEvent) => void;\n alert: (event: ThreatEvent) => void;\n module: (info: { name: string; status: string; detail?: string }) => void;\n}\n\nexport class EventBus extends EventEmitter {\n publish(event: ThreatEvent): void {\n this.emit('event', event);\n if (event.severity === 'high' || event.severity === 'critical') {\n this.emit('alert', event);\n }\n }\n\n announceModule(name: string, status: string, detail?: string): void {\n this.emit('module', { name, status, detail });\n }\n}\n\nexport const bus = new EventBus();\nbus.setMaxListeners(50);\n","import Database from 'better-sqlite3';\nimport type { ThreatEvent } from '../types/events.js';\n\nlet db: Database.Database | null = null;\nlet dbUnavailable = false;\n\nexport function isStateDbAvailable(): boolean {\n return db !== null;\n}\n\nexport function initStateDB(dbPath: string = '/var/lib/threatcrush/state.db'): Database.Database {\n if (db) return db;\n if (dbUnavailable) {\n throw new Error('state db unavailable (previous init failed)');\n }\n\n try {\n try {\n db = new Database(dbPath);\n } catch {\n // Fall back to in-memory if we can't write to the path\n db = new Database(':memory:');\n }\n } catch (err) {\n // Native binding missing or unloadable — mark DB unavailable so callers\n // can degrade gracefully instead of throwing on every IPC request.\n dbUnavailable = true;\n throw err;\n }\n\n db.pragma('journal_mode = WAL');\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n timestamp TEXT NOT NULL,\n module TEXT NOT NULL,\n category TEXT NOT NULL,\n severity TEXT NOT NULL,\n message TEXT NOT NULL,\n source_ip TEXT,\n details TEXT\n );\n\n CREATE TABLE IF NOT EXISTS module_state (\n module TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT,\n PRIMARY KEY (module, key)\n );\n\n CREATE TABLE IF NOT EXISTS stats (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);\n CREATE INDEX IF NOT EXISTS idx_events_module ON events(module);\n CREATE INDEX IF NOT EXISTS idx_events_severity ON events(severity);\n CREATE INDEX IF NOT EXISTS idx_events_source_ip ON events(source_ip);\n `);\n\n return db;\n}\n\nexport function insertEvent(event: ThreatEvent): number {\n const database = tryDb();\n if (!database) return -1;\n const stmt = database.prepare(`\n INSERT INTO events (timestamp, module, category, severity, message, source_ip, details)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n event.timestamp.toISOString(),\n event.module,\n event.category,\n event.severity,\n event.message,\n event.source_ip || null,\n event.details ? JSON.stringify(event.details) : null,\n );\n return result.lastInsertRowid as number;\n}\n\nfunction tryDb(): Database.Database | null {\n if (db) return db;\n if (dbUnavailable) return null;\n try {\n return initStateDB();\n } catch {\n return null;\n }\n}\n\nexport function getRecentEvents(limit: number = 50): ThreatEvent[] {\n const database = tryDb();\n if (!database) return [];\n const rows = database.prepare(`\n SELECT * FROM events ORDER BY timestamp DESC LIMIT ?\n `).all(limit) as any[];\n return rows.map(rowToEvent);\n}\n\nexport function getEventCount(since?: Date): number {\n const database = tryDb();\n if (!database) return 0;\n if (since) {\n return (database.prepare(`SELECT COUNT(*) as count FROM events WHERE timestamp >= ?`)\n .get(since.toISOString()) as any).count;\n }\n return (database.prepare(`SELECT COUNT(*) as count FROM events`).get() as any).count;\n}\n\nexport function getThreatCount(since?: Date): number {\n const database = tryDb();\n if (!database) return 0;\n const severities = \"('medium','high','critical')\";\n if (since) {\n return (database.prepare(\n `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities} AND timestamp >= ?`\n ).get(since.toISOString()) as any).count;\n }\n return (database.prepare(\n `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities}`\n ).get() as any).count;\n}\n\nexport function getTopSources(limit: number = 10): Array<{ ip: string; count: number }> {\n const database = tryDb();\n if (!database) return [];\n return database.prepare(`\n SELECT source_ip as ip, COUNT(*) as count FROM events\n WHERE source_ip IS NOT NULL\n GROUP BY source_ip ORDER BY count DESC LIMIT ?\n `).all(limit) as any[];\n}\n\nexport function getModuleState(module: string, key: string): unknown {\n const database = db || initStateDB();\n const row = database.prepare(`SELECT value FROM module_state WHERE module = ? AND key = ?`)\n .get(module, key) as any;\n if (!row) return undefined;\n try {\n return JSON.parse(row.value);\n } catch {\n return row.value;\n }\n}\n\nexport function setModuleState(module: string, key: string, value: unknown): void {\n const database = db || initStateDB();\n database.prepare(`\n INSERT OR REPLACE INTO module_state (module, key, value) VALUES (?, ?, ?)\n `).run(module, key, JSON.stringify(value));\n}\n\nfunction rowToEvent(row: any): ThreatEvent {\n return {\n id: row.id,\n timestamp: new Date(row.timestamp),\n module: row.module,\n category: row.category,\n severity: row.severity,\n message: row.message,\n source_ip: row.source_ip,\n details: row.details ? JSON.parse(row.details) : undefined,\n };\n}\n\nexport function closeDB(): void {\n if (db) {\n db.close();\n db = null;\n }\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport TOML from '@iarna/toml';\nimport type { EventBus } from './event-bus.js';\nimport { PATHS } from './paths.js';\nimport { LogWatcher } from './watchers/log-watcher.js';\nimport { JournalWatcher } from './watchers/journal-watcher.js';\nimport { NetworkMonitor } from '../modules/network-monitor/index.js';\nimport { DnsMonitor } from '../modules/dns-monitor/index.js';\nimport { loadModuleConfigs } from '../core/config.js';\nimport { getModuleState, setModuleState } from '../core/state.js';\nimport type { ModuleConfig, ModuleManifest } from '../types/config.js';\nimport type { ThreatEvent } from '../types/events.js';\nimport type { ModuleAlert, ThreatCrushModule } from '../types/module.js';\n\ninterface HostedModule {\n name: string;\n version: string;\n source: 'builtin' | 'installed';\n status: 'running' | 'loaded' | 'error' | 'disabled';\n events: number;\n detail?: string;\n path?: string;\n config?: ModuleConfig;\n instance?: ThreatCrushModule;\n}\n\nexport class ModuleHost {\n private modules = new Map<string, HostedModule>();\n private logWatcher: LogWatcher | null = null;\n private journalWatcher: JournalWatcher | null = null;\n private networkMonitor: NetworkMonitor | null = null;\n private dnsMonitor: DnsMonitor | null = null;\n\n constructor(private bus: EventBus) {\n bus.on('event', (event) => {\n const mod = this.modules.get(event.module);\n if (mod) mod.events++;\n for (const hosted of this.modules.values()) {\n if (hosted.status !== 'running' || !hosted.instance?.onEvent) continue;\n void hosted.instance.onEvent(event).catch((err) => {\n hosted.status = 'error';\n hosted.detail = `onEvent failed: ${String((err as Error).message || err)}`;\n this.bus.announceModule(hosted.name, 'error', hosted.detail);\n });\n }\n });\n }\n\n async start(): Promise<void> {\n this.registerBuiltins();\n await this.discoverAndStartInstalled();\n\n this.logWatcher = new LogWatcher(this.bus);\n const watched = this.logWatcher.start();\n\n for (const modName of this.logWatcher.activeModules()) {\n const mod = this.modules.get(modName);\n if (mod) {\n mod.status = 'running';\n mod.detail = `watching ${watched.length} log source(s)`;\n this.bus.announceModule(modName, 'running', mod.detail);\n }\n }\n\n this.journalWatcher = new JournalWatcher(this.bus);\n if (this.journalWatcher.start()) {\n const mod = this.modules.get('user-journal');\n if (mod) {\n mod.status = 'running';\n mod.detail = `tailing ${JournalWatcher.scopeArgs().includes('--user') ? 'user journal' : 'system journal'}`;\n this.bus.announceModule('user-journal', 'running', mod.detail);\n }\n }\n\n // Network monitor (PRD 04)\n this.networkMonitor = new NetworkMonitor(this.bus);\n if (this.networkMonitor.start()) {\n const nmod = this.modules.get('network-monitor');\n if (nmod) {\n nmod.status = 'running';\n nmod.detail = 'monitoring connections via conntrack/ss';\n this.bus.announceModule('network-monitor', 'running', nmod.detail);\n }\n }\n\n // DNS monitor (PRD 05)\n this.dnsMonitor = new DnsMonitor(this.bus);\n if (this.dnsMonitor.start()) {\n const dmod = this.modules.get('dns-monitor');\n if (dmod) {\n dmod.status = 'running';\n dmod.detail = 'monitoring DNS queries';\n this.bus.announceModule('dns-monitor', 'running', dmod.detail);\n }\n }\n }\n\n async stop(): Promise<void> {\n this.logWatcher?.stop();\n this.journalWatcher?.stop();\n this.networkMonitor?.stop();\n this.dnsMonitor?.stop();\n for (const mod of this.modules.values()) {\n try {\n if (mod.instance && mod.status === 'running') {\n await mod.instance.stop();\n }\n } catch (err) {\n mod.status = 'error';\n mod.detail = `stop failed: ${String((err as Error).message || err)}`;\n this.bus.announceModule(mod.name, 'error', mod.detail);\n continue;\n }\n mod.status = 'loaded';\n this.bus.announceModule(mod.name, 'stopped');\n }\n }\n\n summary(): Array<{ name: string; status: string; events: number; detail?: string }> {\n return [...this.modules.values()].map((m) => ({\n name: m.name,\n status: m.status,\n events: m.events,\n detail: m.detail,\n }));\n }\n\n private registerBuiltins(): void {\n const builtins: HostedModule[] = [\n { name: 'log-watcher', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'ssh-guard', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'user-journal', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'network-monitor', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'dns-monitor', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n ];\n for (const m of builtins) this.modules.set(m.name, m);\n }\n\n private async discoverAndStartInstalled(): Promise<void> {\n if (!existsSync(PATHS.moduleDir)) return;\n const configs = loadModuleConfigs(PATHS.confD);\n const entries = readdirSync(PATHS.moduleDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const manifestPath = join(PATHS.moduleDir, entry.name, 'mod.toml');\n if (!existsSync(manifestPath)) continue;\n try {\n const manifest = TOML.parse(readFileSync(manifestPath, 'utf-8')) as unknown as ModuleManifest;\n const name = manifest.module?.name || entry.name;\n const defaults = manifest.module?.config?.defaults || {};\n const config = {\n enabled: true,\n ...defaults,\n ...(configs.get(name) || {}),\n } as ModuleConfig;\n const hosted: HostedModule = {\n name,\n version: manifest.module?.version || '0.0.0',\n source: 'installed',\n status: config.enabled === false ? 'disabled' : 'loaded',\n events: 0,\n path: join(PATHS.moduleDir, entry.name),\n config,\n };\n this.modules.set(name, hosted);\n if (config.enabled === false) continue;\n await this.startInstalled(hosted);\n } catch (err) {\n const name = entry.name;\n this.modules.set(name, {\n name,\n version: '0.0.0',\n source: 'installed',\n status: 'error',\n events: 0,\n detail: `manifest load failed: ${String((err as Error).message || err)}`,\n path: join(PATHS.moduleDir, entry.name),\n });\n }\n }\n }\n\n private async startInstalled(hosted: HostedModule): Promise<void> {\n const entrypoint = this.installedEntrypoint(hosted.path!);\n if (!entrypoint) {\n hosted.status = 'loaded';\n hosted.detail = 'no built entrypoint found; run npm install && npm run build in the module directory';\n return;\n }\n\n try {\n const imported = await import(pathToFileURL(entrypoint).href);\n const exported = imported.default || imported.module || imported;\n const instance = typeof exported === 'function' ? new exported() : exported;\n if (!this.isThreatCrushModule(instance)) {\n throw new Error('entrypoint does not export a ThreatCrush module');\n }\n\n hosted.instance = instance;\n await instance.init(this.contextFor(hosted));\n await instance.start();\n hosted.status = 'running';\n hosted.detail = `started from ${entrypoint}`;\n this.bus.announceModule(hosted.name, 'running', hosted.detail);\n } catch (err) {\n hosted.status = 'error';\n hosted.detail = String((err as Error).message || err);\n this.bus.announceModule(hosted.name, 'error', hosted.detail);\n }\n }\n\n private installedEntrypoint(modulePath: string): string | null {\n const packageJson = join(modulePath, 'package.json');\n const candidates: string[] = [];\n if (existsSync(packageJson)) {\n try {\n const pkg = JSON.parse(readFileSync(packageJson, 'utf-8')) as { main?: string };\n if (pkg.main) candidates.push(join(modulePath, pkg.main));\n } catch {\n // fall through to conventional paths\n }\n }\n candidates.push(join(modulePath, 'dist', 'index.js'), join(modulePath, 'index.js'));\n return candidates.find((candidate) => existsSync(candidate)) || null;\n }\n\n private isThreatCrushModule(value: unknown): value is ThreatCrushModule {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as ThreatCrushModule).init === 'function' &&\n typeof (value as ThreatCrushModule).start === 'function' &&\n typeof (value as ThreatCrushModule).stop === 'function',\n );\n }\n\n private contextFor(hosted: HostedModule) {\n return {\n config: hosted.config || { enabled: true },\n logger: this.loggerFor(hosted.name),\n emit: (event: ThreatEvent) => this.bus.publish(event),\n subscribe: (eventType: string, handler: (event: ThreatEvent) => void) => {\n this.bus.on('event', (event) => {\n if (event.category === eventType || event.module === eventType) handler(event);\n });\n },\n alert: (alert: ModuleAlert) => {\n this.bus.emit('alert', alert.event || {\n timestamp: new Date(),\n module: hosted.name,\n category: 'system',\n severity: alert.severity,\n message: alert.title,\n details: alert.body ? { body: alert.body } : undefined,\n });\n },\n getState: (key: string) => getModuleState(hosted.name, key),\n setState: (key: string, value: unknown) => setModuleState(hosted.name, key, value),\n };\n }\n\n private loggerFor(moduleName: string) {\n return {\n debug: (msg: string, ...args: unknown[]) => console.debug(`[${moduleName}] ${msg}`, ...args),\n info: (msg: string, ...args: unknown[]) => console.info(`[${moduleName}] ${msg}`, ...args),\n warn: (msg: string, ...args: unknown[]) => console.warn(`[${moduleName}] ${msg}`, ...args),\n error: (msg: string, ...args: unknown[]) => console.error(`[${moduleName}] ${msg}`, ...args),\n };\n }\n}\n","import { existsSync, statSync, createReadStream, accessSync, constants } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { EventBus } from '../event-bus.js';\nimport { autoDetectParser, detectAttackPattern, parseAuthLog, parseNginxLog } from '../../core/log-parser.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventCategory, EventSeverity } from '../../types/events.js';\n\nexport interface LogSource {\n path: string;\n module: string;\n category: EventCategory;\n}\n\nexport const DEFAULT_SOURCES: LogSource[] = [\n { path: '/var/log/auth.log', module: 'ssh-guard', category: 'auth' },\n { path: '/var/log/secure', module: 'ssh-guard', category: 'auth' },\n { path: '/var/log/nginx/access.log', module: 'log-watcher', category: 'web' },\n { path: '/var/log/syslog', module: 'log-watcher', category: 'system' },\n];\n\nexport class LogWatcher {\n private timers = new Map<string, NodeJS.Timeout>();\n private positions = new Map<string, number>();\n private active = new Set<string>();\n\n constructor(private bus: EventBus, private sources: LogSource[] = DEFAULT_SOURCES) {}\n\n start(): string[] {\n const started: string[] = [];\n for (const src of this.sources) {\n if (!existsSync(src.path)) continue;\n try { accessSync(src.path, constants.R_OK); }\n catch { continue; }\n this.tail(src);\n started.push(src.path);\n }\n return started;\n }\n\n stop(): void {\n for (const t of this.timers.values()) clearInterval(t);\n this.timers.clear();\n this.positions.clear();\n this.active.clear();\n }\n\n activeModules(): string[] {\n return [...this.active];\n }\n\n private tail(src: LogSource): void {\n try {\n this.positions.set(src.path, statSync(src.path).size);\n } catch {\n this.positions.set(src.path, 0);\n }\n\n const timer = setInterval(() => this.poll(src), 1000);\n this.timers.set(src.path, timer);\n this.active.add(src.module);\n }\n\n private poll(src: LogSource): void {\n let stat;\n try { stat = statSync(src.path); } catch { return; }\n const prev = this.positions.get(src.path) ?? 0;\n\n if (stat.size < prev) {\n this.positions.set(src.path, 0); // rotated\n return;\n }\n if (stat.size === prev) return;\n\n const stream = createReadStream(src.path, { start: prev, encoding: 'utf-8' });\n stream.on('error', () => this.positions.set(src.path, stat.size));\n const rl = createInterface({ input: stream });\n rl.on('error', () => {});\n rl.on('line', (line) => {\n if (!line.trim()) return;\n this.process(line, src);\n });\n rl.on('close', () => this.positions.set(src.path, stat.size));\n }\n\n private process(line: string, src: LogSource): void {\n const parsed = autoDetectParser(line);\n if (!parsed) return;\n\n let severity: EventSeverity = 'info';\n let message = line;\n let sourceIp: string | undefined;\n\n if (parsed.source === 'auth') {\n const entry = parseAuthLog(line);\n if (!entry) return;\n sourceIp = entry.fields.ip;\n const msg = entry.fields.message;\n if (/failed password/i.test(msg)) {\n severity = 'high';\n message = `Failed SSH login for ${entry.fields.user || 'unknown'} from ${entry.fields.ip || 'unknown'}`;\n } else if (/invalid user/i.test(msg)) {\n severity = 'high';\n message = `Invalid SSH user: ${entry.fields.user || 'unknown'} from ${entry.fields.ip || 'unknown'}`;\n } else if (/accepted/i.test(msg)) {\n severity = 'info';\n message = `SSH login accepted for ${entry.fields.user || 'unknown'}`;\n } else {\n return;\n }\n } else if (parsed.source === 'nginx') {\n const entry = parseNginxLog(line);\n if (!entry) return;\n sourceIp = entry.fields.ip;\n const status = parseInt(entry.fields.status, 10);\n const attack = detectAttackPattern(entry.fields.path);\n if (attack) {\n severity = 'critical';\n message = `Attack [${attack.toUpperCase()}]: ${entry.fields.method} ${entry.fields.path}`;\n } else if (status >= 500) {\n severity = 'medium';\n message = `Server error ${status}: ${entry.fields.method} ${entry.fields.path}`;\n } else if (status >= 400) {\n severity = 'low';\n message = `Client error ${status}: ${entry.fields.method} ${entry.fields.path}`;\n } else {\n return;\n }\n } else {\n return;\n }\n\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: src.module,\n category: src.category,\n severity,\n message,\n source_ip: sourceIp,\n };\n\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n","import type { ParsedLogLine, NginxLogEntry, AuthLogEntry, SyslogEntry } from '../types/events.js';\n\n// Nginx combined log format:\n// 127.0.0.1 - - [04/Apr/2026:12:00:00 +0000] \"GET /path HTTP/1.1\" 200 1234 \"-\" \"Mozilla/5.0\"\nconst NGINX_REGEX = /^(\\S+) \\S+ \\S+ \\[([^\\]]+)\\] \"(\\S+) (\\S+) \\S+\" (\\d{3}) (\\d+) \"[^\"]*\" \"([^\"]*)\"/;\n\n// Auth.log format:\n// Apr 4 12:00:00 hostname sshd[1234]: Failed password for user from 1.2.3.4 port 22 ssh2\nconst AUTH_REGEX = /^(\\w+\\s+\\d+\\s+[\\d:]+)\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)/;\n\n// Syslog format:\n// Apr 4 12:00:00 hostname process[pid]: message\nconst SYSLOG_REGEX = /^(\\w+\\s+\\d+\\s+[\\d:]+)\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)/;\n\n// Extract IP from auth messages\nconst IP_REGEX = /(?:from|FROM)\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/;\nconst INVALID_USER_REGEX = /(?:for\\s+invalid\\s+user)\\s+(\\S+?)(?:\\s+from|\\s*$)/;\nconst USER_REGEX = /(?:for|user)\\s+(\\S+?)(?:\\s+from|\\s*$)/;\n\n// Attack pattern signatures\nexport const ATTACK_PATTERNS = {\n sqli: [\n /(?:union\\s+(?:all\\s+)?select)/i,\n /(?:select\\s+.*\\s+from\\s+)/i,\n /(?:insert\\s+into\\s+)/i,\n /(?:drop\\s+(?:table|database))/i,\n /(?:or\\s+1\\s*=\\s*1)/i,\n /(?:'\\s*(?:or|and)\\s+')/i,\n /(?:--\\s*$|;\\s*--)/,\n /(?:\\/\\*.*\\*\\/)/,\n ],\n xss: [\n /<script[^>]*>/i,\n /javascript\\s*:/i,\n /on(?:load|error|click|mouseover)\\s*=/i,\n /eval\\s*\\(/i,\n /document\\.(?:cookie|write|location)/i,\n ],\n path_traversal: [\n /\\.\\.\\//,\n /\\.\\.\\\\/, \n /etc\\/(?:passwd|shadow|hosts)/,\n /proc\\/self/,\n /windows\\/system32/i,\n ],\n rfi: [\n /(?:https?|ftp):\\/\\/.*\\?/i,\n /php:\\/\\/(?:input|filter)/i,\n /data:\\/\\//i,\n ],\n};\n\nexport function parseNginxLog(line: string): NginxLogEntry | null {\n const match = line.match(NGINX_REGEX);\n if (!match) return null;\n\n return {\n timestamp: parseNginxTimestamp(match[2]),\n raw: line,\n source: 'nginx',\n fields: {\n ip: match[1],\n method: match[3],\n path: match[4],\n status: match[5],\n size: match[6],\n user_agent: match[7],\n },\n };\n}\n\nexport function parseAuthLog(line: string): AuthLogEntry | null {\n const match = line.match(AUTH_REGEX);\n if (!match) return null;\n\n const ipMatch = match[3].match(IP_REGEX);\n const userMatch = match[3].match(INVALID_USER_REGEX) || match[3].match(USER_REGEX);\n\n return {\n timestamp: parseSyslogTimestamp(match[1]),\n raw: line,\n source: 'auth',\n fields: {\n process: match[2],\n message: match[3],\n ip: ipMatch?.[1],\n user: userMatch?.[1],\n },\n };\n}\n\nexport function parseSyslog(line: string): SyslogEntry | null {\n const match = line.match(SYSLOG_REGEX);\n if (!match) return null;\n\n return {\n timestamp: parseSyslogTimestamp(match[1]),\n raw: line,\n source: 'syslog',\n fields: {\n facility: 'syslog',\n process: match[2],\n message: match[3],\n },\n };\n}\n\nexport function detectAttackPattern(path: string): string | null {\n // nginx logs the request URI URL-encoded, so raw signatures like `<script`\n // or `or 1=1` never match an encoded payload (e.g. `%3Cscript%3E`,\n // `%27%20OR%201=1`). Test the raw value AND its URL-decoded forms so that\n // single- and double-encoded payloads are still caught. decodeURIComponent\n // throws on a malformed `%` sequence, so guard each decode.\n const candidates = new Set<string>([path]);\n let current = path;\n for (let i = 0; i < 2; i++) {\n let decoded: string | null = null;\n try {\n decoded = decodeURIComponent(current);\n } catch {\n decoded = null;\n }\n if (decoded === null || decoded === current) break;\n candidates.add(decoded);\n current = decoded;\n }\n\n for (const [type, patterns] of Object.entries(ATTACK_PATTERNS)) {\n for (const pattern of patterns) {\n for (const candidate of candidates) {\n if (pattern.test(candidate)) {\n return type;\n }\n }\n }\n }\n return null;\n}\n\nexport function autoDetectParser(line: string): ParsedLogLine | null {\n // Try nginx first (most specific format)\n const nginx = parseNginxLog(line);\n if (nginx) return nginx;\n\n // Try auth log\n const auth = parseAuthLog(line);\n if (auth) return auth;\n\n // Fall back to generic syslog\n return parseSyslog(line);\n}\n\nfunction parseNginxTimestamp(s: string): Date {\n // \"04/Apr/2026:12:00:00 +0000\"\n // new Date(<unparseable>) returns an Invalid Date instead of throwing, so the\n // old try/catch never triggered and an Invalid Date leaked into downstream\n // time-window logic. Check getTime() explicitly and fall back to now.\n const cleaned = s.replace(/(\\d{2})\\/(\\w{3})\\/(\\d{4}):/, '$2 $1, $3 ');\n const d = new Date(cleaned);\n return Number.isNaN(d.getTime()) ? new Date() : d;\n}\n\nfunction parseSyslogTimestamp(s: string): Date {\n // \"Apr 4 12:00:00\" — no year. Assume the most recent year that is not in the\n // future, so a December log parsed in early January is dated to the previous\n // year rather than the current one.\n const now = new Date();\n let d = new Date(`${s} ${now.getFullYear()}`);\n if (Number.isNaN(d.getTime())) return now;\n if (d.getTime() > now.getTime()) {\n const prev = new Date(`${s} ${now.getFullYear() - 1}`);\n if (!Number.isNaN(prev.getTime())) d = prev;\n }\n return d;\n}\n","import { spawn, type ChildProcess, spawnSync } from 'node:child_process';\nimport type { EventBus } from '../event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\n// Wraps `journalctl --user -o json -f` so threatcrushd can pick up user-session\n// events without needing to belong to the `adm` or `systemd-journal` group.\n// On systems without journalctl this watcher is a no-op.\nexport class JournalWatcher {\n private proc: ChildProcess | null = null;\n private buffer = '';\n private moduleName = 'user-journal';\n private active = false;\n\n constructor(private bus: EventBus) {}\n\n // When the daemon runs as root (system mode), tail the SYSTEM journal so\n // we pick up sshd / sudo / kernel / UFW events. Falling back to --user\n // would give us root's mostly-empty per-user journal. Otherwise we use\n // --user so the daemon can run unprivileged on a workstation.\n static scopeArgs(): string[] {\n const isRoot = process.platform === 'linux'\n && typeof process.getuid === 'function'\n && process.getuid() === 0;\n return isRoot ? [] : ['--user'];\n }\n\n static isAvailable(): boolean {\n const probe = spawnSync('journalctl', [...this.scopeArgs(), '-n', '0', '--no-pager'], {\n stdio: ['ignore', 'ignore', 'ignore'],\n });\n return probe.status === 0;\n }\n\n start(): boolean {\n if (!JournalWatcher.isAvailable()) return false;\n\n const child = spawn(\n 'journalctl',\n [...JournalWatcher.scopeArgs(), '-o', 'json', '-f', '--since', 'now'],\n { stdio: ['ignore', 'pipe', 'pipe'] },\n );\n if (!child.stdout) return false;\n child.stdout.setEncoding('utf-8');\n child.stdout.on('data', (chunk: string) => this.onData(chunk));\n child.on('exit', () => {\n this.proc = null;\n this.active = false;\n });\n this.proc = child;\n\n this.active = true;\n return true;\n }\n\n stop(): void {\n if (this.proc) {\n try { this.proc.kill('SIGTERM'); } catch {}\n this.proc = null;\n }\n this.active = false;\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n moduleNameValue(): string {\n return this.moduleName;\n }\n\n private onData(chunk: string): void {\n this.buffer += chunk;\n let idx;\n while ((idx = this.buffer.indexOf('\\n')) >= 0) {\n const line = this.buffer.slice(0, idx);\n this.buffer = this.buffer.slice(idx + 1);\n if (!line.trim()) continue;\n this.handleLine(line);\n }\n }\n\n private handleLine(line: string): void {\n let entry: Record<string, string>;\n try {\n entry = JSON.parse(line) as Record<string, string>;\n } catch {\n return;\n }\n\n const message = entry.MESSAGE;\n if (!message) return;\n\n const priority = parseInt(entry.PRIORITY ?? '6', 10);\n const severity = priorityToSeverity(priority);\n\n // Surface a couple of common suspicious-looking sources at a higher\n // severity even if the kernel disagrees with us.\n const ident = entry.SYSLOG_IDENTIFIER || entry._COMM || 'journal';\n const bumpedSeverity = bumpForIdent(ident, message, severity);\n\n const event: ThreatEvent = {\n timestamp: realtimeToDate(entry.__REALTIME_TIMESTAMP) || new Date(),\n module: this.moduleName,\n category: 'system',\n severity: bumpedSeverity,\n message: `[${ident}] ${message}`.slice(0, 500),\n };\n\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n\nfunction priorityToSeverity(priority: number): EventSeverity {\n // syslog priorities: 0 emerg, 1 alert, 2 crit, 3 err, 4 warning, 5 notice, 6 info, 7 debug\n if (priority <= 2) return 'critical';\n if (priority === 3) return 'high';\n if (priority === 4) return 'medium';\n if (priority === 5) return 'low';\n return 'info';\n}\n\nfunction bumpForIdent(ident: string, message: string, base: EventSeverity): EventSeverity {\n if (/sudo/i.test(ident) && /authentication failure|incorrect password|FAILED/i.test(message)) {\n return 'high';\n }\n if (/sshd/i.test(ident) && /failed|invalid user|break-in/i.test(message)) {\n return 'high';\n }\n return base;\n}\n\nfunction realtimeToDate(rt: string | undefined): Date | null {\n if (!rt) return null;\n const us = parseInt(rt, 10);\n if (!Number.isFinite(us)) return null;\n return new Date(Math.floor(us / 1000));\n}\n","/**\n * Network Monitor Module (PRD 04)\n *\n * Observes TCP/UDP connections via conntrack / ss / /proc/net.\n * Detects port scans and SYN-flood-style patterns.\n * Emits detections through the event bus for the rule engine.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport type { EventBus } from '../../daemon/event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\ninterface ConnectionRecord {\n source_ip: string;\n dest_port: number;\n timestamp: number;\n}\n\ninterface ScanTracker {\n ports: Set<number>;\n firstSeen: number;\n lastSeen: number;\n count: number;\n}\n\nexport class NetworkMonitor {\n private active = false;\n private pollTimer: NodeJS.Timeout | null = null;\n private scanTrackers = new Map<string, ScanTracker>();\n private halfOpenTrackers = new Map<string, { count: number; firstSeen: number }>();\n private lastConnections = new Set<string>();\n\n // Config\n private pollIntervalMs = 5000;\n private portScanThreshold = 10; // unique ports in window\n private portScanWindowMs = 30_000;\n private synFloodThreshold = 50; // half-open connections\n private synFloodWindowMs = 10_000;\n\n constructor(private bus: EventBus) {}\n\n start(): boolean {\n if (!this.hasConntrackOrSs()) {\n return false;\n }\n this.active = true;\n this.pollTimer = setInterval(() => this.poll(), this.pollIntervalMs);\n return true;\n }\n\n stop(): void {\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = null;\n this.active = false;\n }\n\n isActive(): boolean { return this.active; }\n\n private hasConntrackOrSs(): boolean {\n const ss = spawnSync('ss', ['--version'], { stdio: 'pipe' });\n if (ss.status === 0) return true;\n // Try /proc/net/tcp\n return existsSync('/proc/net/tcp');\n }\n\n private poll(): void {\n try {\n const connections = this.getConnections();\n this.analyzePortScans(connections);\n this.analyzeSynFlood(connections);\n this.cleanupTrackers();\n } catch {\n // Graceful degradation\n }\n }\n\n private getConnections(): ConnectionRecord[] {\n const records: ConnectionRecord[] = [];\n const now = Date.now();\n\n try {\n // Try conntrack first\n const ct = spawnSync('conntrack', ['-L', '-p', 'tcp', '-o', 'extended'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ct.status === 0 && ct.stdout) {\n for (const line of ct.stdout.split('\\n')) {\n const srcMatch = line.match(/src=(\\d+\\.\\d+\\.\\d+\\.\\d+)/);\n const dportMatch = line.match(/dport=(\\d+)/);\n if (srcMatch && dportMatch) {\n records.push({ source_ip: srcMatch[1], dest_port: parseInt(dportMatch[1]), timestamp: now });\n }\n }\n if (records.length > 0) return records;\n }\n } catch { /* fallthrough */ }\n\n try {\n // Fallback to ss\n const ss = spawnSync('ss', ['-tnp', '-H'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ss.status === 0 && ss.stdout) {\n for (const line of ss.stdout.split('\\n')) {\n // ss output: State Recv-Q Send-Q Local:Port Peer:Port Process\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 5) continue;\n const peerParts = parts[4].split(':');\n const localParts = parts[3].split(':');\n if (peerParts.length >= 2 && localParts.length >= 2) {\n const sourceIp = peerParts.slice(0, -1).join(':');\n const destPort = parseInt(localParts[localParts.length - 1]);\n if (sourceIp && !isNaN(destPort) && !this.isLocalIp(sourceIp)) {\n records.push({ source_ip: sourceIp, dest_port: destPort, timestamp: now });\n }\n }\n }\n }\n } catch { /* fallthrough */ }\n\n return records;\n }\n\n private analyzePortScans(connections: ConnectionRecord[]): void {\n const now = Date.now();\n\n for (const conn of connections) {\n const key = conn.source_ip;\n let tracker = this.scanTrackers.get(key);\n\n if (!tracker) {\n tracker = { ports: new Set(), firstSeen: now, lastSeen: now, count: 0 };\n this.scanTrackers.set(key, tracker);\n }\n\n tracker.ports.add(conn.dest_port);\n tracker.lastSeen = now;\n tracker.count++;\n\n // Check threshold within window\n if (tracker.ports.size >= this.portScanThreshold &&\n (now - tracker.firstSeen) <= this.portScanWindowMs) {\n this.emitEvent(\n 'high',\n `Port scan detected: ${conn.source_ip} probed ${tracker.ports.size} ports in ${Math.round((now - tracker.firstSeen) / 1000)}s`,\n conn.source_ip,\n { ports_scanned: tracker.ports.size, window_seconds: Math.round((now - tracker.firstSeen) / 1000) },\n );\n // Reset tracker after alert\n this.scanTrackers.delete(key);\n }\n }\n }\n\n private analyzeSynFlood(connections: ConnectionRecord[]): void {\n // Count SYN_RECV (half-open) states via ss\n try {\n const ss = spawnSync('ss', ['-tn', 'state', 'syn-recv', '-H'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ss.status !== 0 || !ss.stdout) return;\n\n const perSource = new Map<string, number>();\n\n for (const line of ss.stdout.split('\\n')) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 5) continue;\n const peer = parts[4].split(':');\n const ip = peer.slice(0, -1).join(':');\n if (ip) perSource.set(ip, (perSource.get(ip) || 0) + 1);\n }\n\n for (const [ip, count] of perSource) {\n if (count >= this.synFloodThreshold) {\n this.emitEvent(\n 'critical',\n `SYN flood indicators: ${count} half-open connections from ${ip}`,\n ip,\n { half_open_count: count },\n );\n }\n }\n } catch { /* graceful */ }\n }\n\n private emitEvent(severity: EventSeverity, message: string, sourceIp?: string, details?: Record<string, unknown>): void {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'network-monitor',\n category: 'network',\n severity,\n message,\n source_ip: sourceIp,\n details,\n };\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n\n private cleanupTrackers(): void {\n const now = Date.now();\n for (const [key, tracker] of this.scanTrackers) {\n if (now - tracker.lastSeen > this.portScanWindowMs * 2) {\n this.scanTrackers.delete(key);\n }\n }\n }\n\n private isLocalIp(ip: string): boolean {\n return ip === '127.0.0.1' || ip === '::1' || ip === '0.0.0.0' || ip.startsWith('::ffff:127.');\n }\n}\n","/**\n * DNS Monitor Module (PRD 05)\n *\n * Observes DNS query activity for tunneling and DGA indicators.\n * Sources: resolver logs, systemd-resolved, dnsmasq logs, passive :53 observation.\n */\n\nimport { existsSync, statSync, createReadStream, accessSync, constants } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { EventBus } from '../../daemon/event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\ninterface DnsQuery {\n domain: string;\n type: string;\n source_ip?: string;\n timestamp: number;\n}\n\nconst DNS_LOG_SOURCES = [\n '/var/log/syslog', // systemd-resolved logs here\n '/var/log/dnsmasq.log', // dnsmasq\n '/var/log/named/queries.log', // bind9\n '/var/log/pihole.log', // Pi-hole\n];\n\nexport class DnsMonitor {\n private active = false;\n private timers = new Map<string, NodeJS.Timeout>();\n private positions = new Map<string, number>();\n\n // Tracking windows\n private txtQueryCounts = new Map<string, { count: number; firstSeen: number }>();\n private domainBuffer: DnsQuery[] = [];\n\n // Config\n private txtRateThreshold = 20; // TXT queries per source per window\n private txtWindowMs = 60_000;\n private dgaBurstThreshold = 15; // unique high-entropy domains per window\n private dgaWindowMs = 60_000;\n private entropyThreshold = 3.5; // Shannon entropy threshold for DGA\n\n constructor(private bus: EventBus) {}\n\n start(): boolean {\n const sources = DNS_LOG_SOURCES.filter(p => {\n if (!existsSync(p)) return false;\n try { accessSync(p, constants.R_OK); return true; }\n catch { return false; }\n });\n\n if (sources.length === 0) return false;\n\n this.active = true;\n for (const src of sources) {\n this.tailLog(src);\n }\n\n // Periodic analysis\n setInterval(() => this.analyzeBuffer(), 10_000);\n return true;\n }\n\n stop(): void {\n for (const t of this.timers.values()) clearInterval(t);\n this.timers.clear();\n this.active = false;\n }\n\n isActive(): boolean { return this.active; }\n\n private tailLog(path: string): void {\n try {\n this.positions.set(path, statSync(path).size);\n } catch {\n this.positions.set(path, 0);\n }\n\n const timer = setInterval(() => this.pollLog(path), 2000);\n this.timers.set(path, timer);\n }\n\n private pollLog(path: string): void {\n let stat;\n try { stat = statSync(path); } catch { return; }\n const prev = this.positions.get(path) ?? 0;\n\n if (stat.size < prev) { this.positions.set(path, 0); return; }\n if (stat.size === prev) return;\n\n const stream = createReadStream(path, { start: prev, encoding: 'utf-8' });\n stream.on('error', () => this.positions.set(path, stat.size));\n const rl = createInterface({ input: stream });\n rl.on('line', (line) => this.parseDnsLine(line));\n rl.on('close', () => this.positions.set(path, stat.size));\n }\n\n private parseDnsLine(line: string): void {\n // systemd-resolved pattern: \"query[TXT] suspicious.domain.com from 192.168.1.1\"\n const resolvedMatch = line.match(/query\\[(\\w+)\\]\\s+(\\S+)\\s+from\\s+(\\S+)/i);\n if (resolvedMatch) {\n this.domainBuffer.push({\n type: resolvedMatch[1],\n domain: resolvedMatch[2],\n source_ip: resolvedMatch[3],\n timestamp: Date.now(),\n });\n return;\n }\n\n // dnsmasq pattern: \"query[TXT] suspicious.domain.com from 192.168.1.1\"\n const dnsmasqMatch = line.match(/query\\[(\\w+)\\]\\s+(\\S+)\\s+from\\s+(\\S+)/i);\n if (dnsmasqMatch) {\n this.domainBuffer.push({\n type: dnsmasqMatch[1],\n domain: dnsmasqMatch[2],\n source_ip: dnsmasqMatch[3],\n timestamp: Date.now(),\n });\n return;\n }\n\n // Generic DNS query log pattern\n const genericMatch = line.match(/(?:query|lookup|resolve)[:\\s]+(\\S+)/i);\n if (genericMatch) {\n const typeMatch = line.match(/type[:\\s]+(\\w+)/i);\n this.domainBuffer.push({\n type: typeMatch?.[1] || 'A',\n domain: genericMatch[1],\n timestamp: Date.now(),\n });\n }\n }\n\n private analyzeBuffer(): void {\n const now = Date.now();\n const cutoff = now - this.txtWindowMs;\n\n // Prune old entries\n this.domainBuffer = this.domainBuffer.filter(q => q.timestamp > cutoff);\n\n this.detectTunneling();\n this.detectDga();\n }\n\n private detectTunneling(): void {\n // Check for high TXT query volume from single source\n const txtBySource = new Map<string, number>();\n const longLabelDomains: string[] = [];\n\n for (const q of this.domainBuffer) {\n if (q.type === 'TXT') {\n const key = q.source_ip || 'unknown';\n txtBySource.set(key, (txtBySource.get(key) || 0) + 1);\n }\n\n // DNS tunneling uses abnormally long subdomain labels\n const labels = q.domain.split('.');\n const maxLabel = Math.max(...labels.map(l => l.length));\n if (maxLabel > 50) {\n longLabelDomains.push(q.domain);\n }\n }\n\n for (const [source, count] of txtBySource) {\n if (count >= this.txtRateThreshold) {\n this.emitEvent(\n 'high',\n `DNS tunneling indicators: ${count} TXT queries from ${source} in ${this.txtWindowMs / 1000}s`,\n source !== 'unknown' ? source : undefined,\n { txt_query_count: count, type: 'tunneling' },\n );\n }\n }\n\n if (longLabelDomains.length >= 5) {\n this.emitEvent(\n 'high',\n `DNS tunneling: ${longLabelDomains.length} queries with abnormally long labels detected`,\n undefined,\n { domains: longLabelDomains.slice(0, 5), type: 'tunneling-labels' },\n );\n }\n }\n\n private detectDga(): void {\n // Find domains with high entropy (DGA-like)\n const highEntropyDomains: string[] = [];\n\n for (const q of this.domainBuffer) {\n const domain = q.domain.toLowerCase();\n // Extract the second-level domain\n const parts = domain.split('.');\n if (parts.length < 2) continue;\n const sld = parts[parts.length - 2];\n\n if (sld.length >= 8 && this.shannonEntropy(sld) >= this.entropyThreshold) {\n highEntropyDomains.push(domain);\n }\n }\n\n // Deduplicate\n const unique = [...new Set(highEntropyDomains)];\n if (unique.length >= this.dgaBurstThreshold) {\n this.emitEvent(\n 'critical',\n `DGA-like domain burst: ${unique.length} unique high-entropy domains detected`,\n undefined,\n { sample_domains: unique.slice(0, 10), type: 'dga', unique_count: unique.length },\n );\n }\n }\n\n private shannonEntropy(str: string): number {\n const freq = new Map<string, number>();\n for (const ch of str) {\n freq.set(ch, (freq.get(ch) || 0) + 1);\n }\n let entropy = 0;\n for (const count of freq.values()) {\n const p = count / str.length;\n if (p > 0) entropy -= p * Math.log2(p);\n }\n return entropy;\n }\n\n private emitEvent(severity: EventSeverity, message: string, sourceIp?: string, details?: Record<string, unknown>): void {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'dns-monitor',\n category: 'network',\n severity,\n message,\n source_ip: sourceIp,\n details,\n };\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n","import { readFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport TOML from '@iarna/toml';\nimport type { ThreatCrushConfig, ModuleConfig } from '../types/config.js';\n\nconst DEFAULT_CONFIG_PATH = '/etc/threatcrush/threatcrushd.conf';\nconst DEFAULT_CONFDIR = '/etc/threatcrush/threatcrushd.conf.d';\n\nconst DEFAULT_CONFIG: ThreatCrushConfig = {\n daemon: {\n pid_file: '/var/run/threatcrush/threatcrushd.pid',\n log_level: 'info',\n log_file: '/var/log/threatcrush/threatcrushd.log',\n state_db: '/var/lib/threatcrush/state.db',\n },\n api: {\n enabled: true,\n bind: '127.0.0.1:9393',\n tls: false,\n },\n alerts: {},\n modules: {\n auto_update: true,\n update_interval: '24h',\n module_dir: '/etc/threatcrush/modules',\n config_dir: DEFAULT_CONFDIR,\n },\n};\n\nexport function loadConfig(configPath?: string): ThreatCrushConfig {\n const path = configPath || DEFAULT_CONFIG_PATH;\n if (!existsSync(path)) {\n return { ...DEFAULT_CONFIG };\n }\n\n try {\n const raw = readFileSync(path, 'utf-8');\n const parsed = TOML.parse(raw) as unknown as Partial<ThreatCrushConfig>;\n return {\n daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },\n api: { ...DEFAULT_CONFIG.api, ...parsed.api },\n alerts: parsed.alerts || {},\n modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },\n license: parsed.license,\n };\n } catch {\n return { ...DEFAULT_CONFIG };\n }\n}\n\nexport function loadModuleConfigs(confDir?: string): Map<string, ModuleConfig> {\n const dir = confDir || DEFAULT_CONFDIR;\n const configs = new Map<string, ModuleConfig>();\n\n if (!existsSync(dir)) {\n return configs;\n }\n\n const files = readdirSync(dir).filter((f) => f.endsWith('.conf'));\n for (const file of files) {\n try {\n const raw = readFileSync(join(dir, file), 'utf-8');\n const parsed = TOML.parse(raw) as Record<string, unknown>;\n for (const [name, config] of Object.entries(parsed)) {\n configs.set(name, config as ModuleConfig);\n }\n } catch {\n // skip bad configs\n }\n }\n\n return configs;\n}\n\nexport function generateDefaultConfig(detectedServices: string[]): string {\n const config: Record<string, unknown> = {\n daemon: DEFAULT_CONFIG.daemon,\n api: DEFAULT_CONFIG.api,\n modules: DEFAULT_CONFIG.modules,\n };\n\n return TOML.stringify(config as any);\n}\n\nexport function generateModuleConfig(\n moduleName: string,\n defaults: Record<string, unknown> = {},\n): string {\n const config: Record<string, unknown> = {\n [moduleName]: {\n enabled: true,\n ...defaults,\n },\n };\n return TOML.stringify(config as any);\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\ntype Mailer = {\n sendMail: (opts: Record<string, unknown>) => Promise<unknown>;\n};\n\nlet transporter: Mailer | null = null;\n// Lazy-load nodemailer so the CLI build doesn't pull it in when alerts are off.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet nodemailer: any = null;\n\nexport interface SmtpConfig {\n host?: string;\n port?: number;\n secure?: boolean;\n user?: string;\n pass?: string;\n from?: string;\n to?: string[] | string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nasync function ensureTransporter(config: SmtpConfig): Promise<Mailer | null> {\n if (!config.host || !config.from) return null;\n if (transporter) return transporter;\n\n if (!nodemailer) {\n try {\n nodemailer = await import('nodemailer');\n } catch {\n return null;\n }\n }\n\n transporter = nodemailer.createTransport({\n host: config.host,\n port: config.port ?? 587,\n secure: config.secure ?? false,\n auth: config.user && config.pass ? { user: config.user, pass: config.pass } : undefined,\n });\n return transporter;\n}\n\nfunction meetsSeverity(event: ThreatEvent, min?: SmtpConfig['min_severity']): boolean {\n if (!min) return true;\n return (SEVERITY_RANK[event.severity] ?? 0) >= (SEVERITY_RANK[min] ?? 0);\n}\n\nfunction renderBody(event: ThreatEvent): { text: string; html: string } {\n const ts = event.timestamp.toISOString();\n const ip = event.source_ip ? `\\nSource IP: ${event.source_ip}` : '';\n const text =\n `[${event.severity.toUpperCase()}] ${event.module}\\n\\n` +\n `${event.message}${ip}\\n\\n` +\n `When: ${ts}\\nCategory: ${event.category}`;\n const html =\n `<div style=\"font-family:system-ui,sans-serif;line-height:1.5\">` +\n `<h2 style=\"margin:0 0 8px\">⚠ ${event.severity.toUpperCase()} — ${event.module}</h2>` +\n `<p>${event.message}</p>` +\n (event.source_ip ? `<p><strong>Source IP:</strong> <code>${event.source_ip}</code></p>` : '') +\n `<p style=\"color:#888;margin-top:16px\"><small>${ts} · ${event.category}</small></p>` +\n `</div>`;\n return { text, html };\n}\n\nexport function smtpChannel(config: SmtpConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (!meetsSeverity(event, config.min_severity)) return;\n const t = await ensureTransporter(config);\n if (!t) return;\n\n const to = Array.isArray(config.to) ? config.to.join(', ') : config.to;\n if (!to) return;\n\n const { text, html } = renderBody(event);\n await t.sendMail({\n from: config.from,\n to,\n subject: `[ThreatCrush ${event.severity}] ${event.module} — ${event.message.slice(0, 60)}`,\n text,\n html,\n });\n };\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\nexport interface DiscordConfig {\n webhook_url: string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\nconst SEVERITY_COLORS: Record<string, number> = {\n info: 0x2ecc71, // green\n low: 0x3498db, // blue\n medium: 0xf39c12, // orange\n high: 0xe74c3c, // red\n critical: 0x9b59b6, // purple\n};\n\nexport function discordChannel(config: DiscordConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (config.min_severity) {\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[config.min_severity] ?? 0;\n if (eventRank < minRank) return;\n }\n\n const embed = {\n title: `${event.severity === 'critical' ? '🚨' : '⚠️'} [${event.severity.toUpperCase()}] ${event.module}`,\n description: event.message,\n color: SEVERITY_COLORS[event.severity] ?? 0xffffff,\n fields: [\n ...(event.source_ip ? [{ name: 'Source IP', value: `\\`${event.source_ip}\\``, inline: true }] : []),\n { name: 'Category', value: event.category, inline: true },\n { name: 'Time', value: event.timestamp.toISOString(), inline: true },\n ],\n footer: { text: 'ThreatCrush Security Alert' },\n };\n\n await fetch(config.webhook_url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ embeds: [embed] }),\n });\n };\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\nexport interface PagerDutyConfig {\n routing_key: string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\n// Map ThreatCrush severity to PagerDuty severity\nconst PD_SEVERITY: Record<string, string> = {\n info: 'info',\n low: 'info',\n medium: 'warning',\n high: 'error',\n critical: 'critical',\n};\n\nexport function pagerdutyChannel(config: PagerDutyConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (config.min_severity) {\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[config.min_severity] ?? 0;\n if (eventRank < minRank) return;\n }\n\n const payload = {\n routing_key: config.routing_key,\n event_action: 'trigger',\n payload: {\n summary: `[${event.severity.toUpperCase()}] ${event.module}: ${event.message}`,\n source: 'threatcrush',\n severity: PD_SEVERITY[event.severity] || 'warning',\n timestamp: event.timestamp.toISOString(),\n custom_details: {\n module: event.module,\n category: event.category,\n source_ip: event.source_ip,\n details: event.details,\n },\n },\n };\n\n await fetch('https://events.pagerduty.com/v2/enqueue', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n };\n}\n","import type { ThreatCrushConfig, AlertChannelConfig } from '../../types/config.js';\nimport type { ThreatEvent } from '../../types/events.js';\nimport type { EventBus } from '../event-bus.js';\nimport { smtpChannel, type SmtpConfig } from './smtp.js';\nimport { discordChannel, type DiscordConfig } from './discord.js';\nimport { pagerdutyChannel, type PagerDutyConfig } from './pagerduty.js';\n\ntype Channel = (event: ThreatEvent) => Promise<void>;\n\nexport class AlertDispatcher {\n private channels: Channel[] = [];\n private rateLimits = new Map<string, number[]>();\n\n constructor(private bus: EventBus, private config: ThreatCrushConfig) {\n this.bindChannels();\n bus.on('alert', (event) => { void this.dispatch(event); });\n }\n\n private bindChannels(): void {\n const alerts = this.config.alerts || {};\n for (const [name, raw] of Object.entries(alerts)) {\n const cfg = raw as AlertChannelConfig;\n if (!cfg.enabled) continue;\n if (name === 'webhook' && typeof cfg.url === 'string') {\n this.channels.push(webhookChannel(cfg.url, cfg.secret as string | undefined));\n }\n if (name === 'slack' && typeof cfg.webhook_url === 'string') {\n this.channels.push(slackChannel(cfg.webhook_url));\n }\n if (name === 'email' && typeof cfg.host === 'string' && typeof cfg.from === 'string') {\n this.channels.push(smtpChannel(cfg as unknown as SmtpConfig));\n }\n if (name === 'discord' && typeof cfg.webhook_url === 'string') {\n this.channels.push(discordChannel(cfg as unknown as DiscordConfig));\n }\n if (name === 'pagerduty' && typeof cfg.routing_key === 'string') {\n this.channels.push(pagerdutyChannel(cfg as unknown as PagerDutyConfig));\n }\n }\n }\n\n private checkRateLimit(channelIdx: number, maxPerHour: number = 60): boolean {\n const key = String(channelIdx);\n const now = Date.now();\n const hour = 3600_000;\n let timestamps = this.rateLimits.get(key) || [];\n timestamps = timestamps.filter(t => t > now - hour);\n if (timestamps.length >= maxPerHour) return false;\n timestamps.push(now);\n this.rateLimits.set(key, timestamps);\n return true;\n }\n\n private async dispatch(event: ThreatEvent): Promise<void> {\n await Promise.all(this.channels.map((ch, idx) => {\n if (!this.checkRateLimit(idx)) return Promise.resolve();\n return ch(event).catch(() => {});\n }));\n }\n}\n\nfunction webhookChannel(url: string, secret?: string): Channel {\n return async (event) => {\n const body = JSON.stringify({ event });\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (secret) headers['X-Threatcrush-Signature'] = secret;\n await fetch(url, { method: 'POST', headers, body });\n };\n}\n\nfunction slackChannel(webhookUrl: string): Channel {\n return async (event) => {\n const emoji = event.severity === 'critical' ? ':rotating_light:' : ':warning:';\n const text = `${emoji} *[${event.severity.toUpperCase()}]* \\`${event.module}\\` — ${event.message}${event.source_ip ? ` (from ${event.source_ip})` : ''}`;\n await fetch(webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text }),\n });\n };\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport const CLI_CONFIG_DIR = join(homedir(), '.threatcrush');\nexport const CLI_CONFIG_PATH = join(CLI_CONFIG_DIR, 'config.json');\n\nexport interface CliConfig {\n email?: string;\n user_id?: string;\n token?: string;\n refresh_token?: string;\n expires_at?: number;\n display_name?: string;\n current_org_id?: string;\n current_org_slug?: string;\n}\n\nexport function readCliConfig(): CliConfig {\n try {\n return JSON.parse(readFileSync(CLI_CONFIG_PATH, 'utf-8')) as CliConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeCliConfig(config: CliConfig): void {\n if (!existsSync(CLI_CONFIG_DIR)) mkdirSync(CLI_CONFIG_DIR, { recursive: true });\n writeFileSync(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8');\n try { chmodSync(CLI_CONFIG_PATH, 0o600); } catch { /* non-posix */ }\n}\n\nexport function updateCliConfig(patch: Partial<CliConfig>): CliConfig {\n const current = readCliConfig();\n const next = { ...current, ...patch };\n writeCliConfig(next);\n return next;\n}\n\nexport function clearCliConfig(keys?: Array<keyof CliConfig>): void {\n const current = readCliConfig();\n if (!keys) {\n writeCliConfig({});\n return;\n }\n for (const key of keys) delete current[key];\n writeCliConfig(current);\n}\n\nexport function isLoggedIn(): boolean {\n const cfg = readCliConfig();\n if (!cfg.token) return false;\n if (cfg.expires_at && cfg.expires_at * 1000 < Date.now()) return false;\n return true;\n}\n\nexport function authHeaders(): Record<string, string> {\n const cfg = readCliConfig();\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (cfg.token) headers['Authorization'] = `Bearer ${cfg.token}`;\n return headers;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { banner, logger } from '../core/logger.js';\nimport type { RunResult, StructuredFinding } from '../core/run-result.js';\nimport { summarize } from '../core/run-result.js';\nimport { meetsFailThreshold, SEVERITY_ORDER } from '@threatcrush/scan';\nimport type { ScanFinding, Severity } from '@threatcrush/scan';\nimport { buildSarif, scanDependencies, scanPath } from '@threatcrush/scan/node';\n\nexport type ScanFormat = 'text' | 'json' | 'sarif';\n\nexport interface ScanCommandOptions {\n /**\n * `text` for humans, `sarif` for the Security tab and coverage validators,\n * `json` for anything else. Non-text formats put the payload on stdout (or\n * `--output`) and every human line on stderr, so\n * `threatcrush scan --format sarif > out.sarif` produces a valid file.\n */\n format?: ScanFormat;\n /** Write the machine-readable payload here instead of stdout. */\n output?: string;\n /** Exit non-zero when a finding at or above one of these severities exists. */\n failOn?: readonly Severity[];\n /** Prefix prepended to SARIF URIs when the scan root is not the repo root. */\n pathPrefix?: string;\n /** Print the paths that could not be read, not just the count. */\n verbose?: boolean;\n /**\n * Query OSV.dev for advisories against the resolved lockfile versions.\n * Off by default in the CLI because it is the only part of a scan that\n * needs the network — a CI job should opt in deliberately rather than\n * discover the dependency mid-run.\n */\n dependencies?: boolean;\n}\n\ninterface ScanOutcome {\n result: RunResult;\n findings: ScanFinding[];\n filesScanned: number;\n unreadable: string[];\n suppressed: number;\n root: string;\n}\n\nfunction readVersion(): string {\n for (const candidate of [\n join(__dirname, '..', 'package.json'),\n join(__dirname, '..', '..', 'package.json'),\n ]) {\n try {\n return (\n (JSON.parse(readFileSync(candidate, 'utf-8')) as { version?: string }).version ?? '0.0.0'\n );\n } catch {\n /* try the next candidate */\n }\n }\n return '0.0.0';\n}\n\nconst PKG_VERSION = readVersion();\n\n/** Parse `--fail-on critical,high` into severities, rejecting unknown names. */\nexport function parseFailOn(raw: string | undefined): Severity[] {\n if (!raw) return [];\n const requested = raw\n .split(',')\n .map((part) => part.trim().toLowerCase())\n .filter(Boolean);\n\n const unknown = requested.filter((name) => !SEVERITY_ORDER.includes(name as Severity));\n if (unknown.length > 0) {\n throw new Error(\n `unknown severity in --fail-on: ${unknown.join(', ')} (expected ${SEVERITY_ORDER.join(', ')})`,\n );\n }\n return requested as Severity[];\n}\n\nfunction toRunResult(\n targetPath: string,\n findings: readonly ScanFinding[],\n filesScanned: number,\n): RunResult {\n const structured: StructuredFinding[] = findings.map((finding) => ({\n type: finding.title,\n severity: finding.severity,\n message: finding.message,\n location: `${finding.file}:${finding.line}`,\n details: {\n file: finding.file,\n line: finding.line,\n snippet: finding.excerpt,\n ruleId: finding.ruleId,\n confidence: finding.confidence,\n ...(finding.cwe ? { cwe: finding.cwe } : {}),\n },\n }));\n const counts = summarize(structured);\n\n return {\n type: 'scan',\n target: targetPath,\n findings: structured,\n severity_summary: counts,\n summary:\n findings.length === 0\n ? `No issues found across ${filesScanned} files`\n : `${findings.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`,\n };\n}\n\nfunction failedResult(targetPath: string, message: string): RunResult {\n return {\n type: 'scan',\n target: targetPath,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `Scan failed: ${message}`,\n error: message,\n };\n}\n\n/**\n * Non-interactive scan used by the daemon and the runs worker.\n *\n * Includes dependency advisories, as it always has — the daemon runs on a\n * schedule against a server it can reach the network from, and an advisory\n * published since the last run is the main thing that changed.\n */\nexport async function runScan(targetPath: string): Promise<RunResult> {\n try {\n const report = scanPath(targetPath);\n const findings = [...report.findings, ...(await scanDependencies(targetPath))];\n return toRunResult(targetPath, findings, report.filesScanned);\n } catch (err) {\n return failedResult(targetPath, (err as Error).message);\n }\n}\n\nexport async function scanCommand(\n targetPath: string,\n options: ScanCommandOptions = {},\n): Promise<RunResult> {\n const format = options.format ?? 'text';\n const machineReadable = format !== 'text';\n // Human output goes to stderr whenever stdout is carrying a payload. A\n // banner in the middle of a SARIF document is exactly how \"the scan worked\n // but the pipeline reports zero findings\" happens.\n const say = machineReadable\n ? (line: string) => process.stderr.write(`${line}\\n`)\n : (line: string) => process.stdout.write(`${line}\\n`);\n\n if (!existsSync(targetPath)) {\n say(chalk.red(`Scan target does not exist: ${targetPath}`));\n process.exitCode = 2;\n return failedResult(targetPath, `no such path: ${targetPath}`);\n }\n\n if (!machineReadable) {\n banner();\n logger.info(`Scanning ${chalk.white(targetPath)} for security issues...\\n`);\n }\n\n const spinner = machineReadable ? null : ora({ text: 'Scanning files...', color: 'green' }).start();\n\n let outcome: ScanOutcome;\n try {\n let seen = 0;\n const report = scanPath(targetPath, {\n onFile: () => {\n seen += 1;\n if (spinner) spinner.text = `Scanning files... (${seen} files)`;\n },\n });\n if (options.dependencies) {\n if (spinner) spinner.text = 'Querying OSV.dev for dependency advisories...';\n report.findings.push(...(await scanDependencies(targetPath)));\n }\n outcome = {\n result: toRunResult(targetPath, report.findings, report.filesScanned),\n findings: report.findings,\n filesScanned: report.filesScanned,\n unreadable: report.unreadable,\n suppressed: report.suppressed,\n root: report.root,\n };\n } catch (err) {\n spinner?.fail(`Scan failed: ${(err as Error).message}`);\n process.exitCode = 2;\n return failedResult(targetPath, (err as Error).message);\n }\n\n spinner?.succeed(`Scanned ${outcome.filesScanned} files\\n`);\n\n if (outcome.unreadable.length > 0) {\n // Surfaced, never swallowed. An unexamined file is not a clean one, and a\n // scanner that hides read failures reports silence as safety.\n say(\n chalk.yellow(\n ` ! ${outcome.unreadable.length} path(s) could not be read and were NOT scanned`,\n ),\n );\n if (options.verbose) {\n for (const path of outcome.unreadable) say(chalk.gray(` ${path}`));\n }\n }\n\n if (outcome.suppressed > 0) {\n say(\n chalk.gray(\n ` · ${outcome.suppressed} finding(s) suppressed by inline threatcrush-disable comments`,\n ),\n );\n }\n\n if (machineReadable) {\n emitMachineReadable(format, outcome, targetPath, options, say);\n } else {\n printHuman(outcome);\n }\n\n const failOn = options.failOn ?? [];\n if (meetsFailThreshold(outcome.findings, failOn)) {\n say(\n chalk.red(\n `\\n ✗ findings at or above ${[...failOn].join('/')} — failing as requested by --fail-on`,\n ),\n );\n process.exitCode = 1;\n }\n\n return outcome.result;\n}\n\nfunction emitMachineReadable(\n format: ScanFormat,\n outcome: ScanOutcome,\n targetPath: string,\n options: ScanCommandOptions,\n say: (line: string) => void,\n): void {\n const payload =\n format === 'sarif'\n ? buildSarif(outcome.findings, {\n toolVersion: PKG_VERSION,\n pathPrefix: options.pathPrefix,\n // Relative to the working directory, NOT the scan root. `threatcrush\n // scan vulns` from a repo root must emit `vulns/secrets/x.env`, not\n // `secrets/x.env` — the second form matches nothing in the\n // consumer's view of the repository, so every finding lands\n // \"outside\" whatever it scoped to and a working scan reads as 0%.\n // This is the single most expensive mistake in the whole pipeline\n // and it fails silently. `--path-prefix` covers the remaining case:\n // a scan run from inside the subdirectory it is scanning.\n base: process.cwd(),\n root: resolve(outcome.root),\n })\n : {\n tool: 'threatcrush',\n version: PKG_VERSION,\n target: targetPath,\n filesScanned: outcome.filesScanned,\n unreadable: outcome.unreadable,\n suppressed: outcome.suppressed,\n summary: outcome.result.severity_summary,\n findings: outcome.findings,\n };\n\n const serialized = `${JSON.stringify(payload, null, 2)}\\n`;\n\n if (options.output) {\n mkdirSync(dirname(resolve(options.output)), { recursive: true });\n writeFileSync(options.output, serialized, 'utf-8');\n say(\n chalk.gray(\n ` ${format.toUpperCase()} written to ${options.output} (${outcome.findings.length} finding(s))`,\n ),\n );\n return;\n }\n process.stdout.write(serialized);\n}\n\nfunction printHuman(outcome: ScanOutcome): void {\n const { findings, filesScanned } = outcome;\n\n if (findings.length === 0) {\n console.log(chalk.green.bold(' ✓ No security issues found!'));\n console.log();\n return;\n }\n\n const counts = outcome.result.severity_summary;\n console.log(chalk.white.bold(' Scan Results'));\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.red.bold(counts.critical + ' critical')} ` +\n `${chalk.red(counts.high + ' high')} ` +\n `${chalk.yellow(counts.medium + ' medium')} ` +\n `${chalk.gray(counts.low + ' low')}`,\n );\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log();\n\n for (const finding of findings) {\n const label = finding.severity.toUpperCase();\n const badge =\n finding.severity === 'critical'\n ? chalk.bgRed.white.bold(` ${label} `)\n : finding.severity === 'high'\n ? chalk.red(`[${label}]`)\n : finding.severity === 'medium'\n ? chalk.yellow(`[${label}]`)\n : chalk.gray(`[${label}]`);\n\n console.log(` ${badge} ${chalk.white.bold(finding.title)}`);\n console.log(\n ` ${chalk.gray('File:')} ${chalk.cyan(finding.file)}:${chalk.yellow(String(finding.line))}`,\n );\n console.log(` ${chalk.gray('Info:')} ${finding.message}`);\n if (finding.consequence) {\n console.log(` ${chalk.gray('Risk:')} ${chalk.dim(finding.consequence)}`);\n }\n if (finding.excerpt) {\n console.log(` ${chalk.gray('Code:')} ${finding.excerpt}`);\n }\n console.log(\n ` ${chalk.gray('Rule:')} ${chalk.dim(finding.ruleId)}` +\n (finding.cwe ? chalk.dim(` · ${finding.cwe}`) : '') +\n chalk.dim(` · confidence: ${finding.confidence}`),\n );\n console.log();\n }\n\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.white.bold(`${findings.length} issue(s) found`)} across ${filesScanned} files`,\n );\n console.log();\n}\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n","// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n","import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n","import chalk from 'chalk';\nimport type { EventSeverity } from '../types/events.js';\n\nconst SEVERITY_COLORS: Record<EventSeverity, (s: string) => string> = {\n info: chalk.green,\n low: chalk.cyan,\n medium: chalk.yellow,\n high: chalk.red,\n critical: chalk.bgRed.white.bold,\n};\n\nconst LEVEL_COLORS: Record<string, (s: string) => string> = {\n debug: chalk.gray,\n info: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n};\n\nexport function severityColor(severity: EventSeverity, text: string): string {\n return (SEVERITY_COLORS[severity] || chalk.white)(text);\n}\n\nexport function formatTimestamp(date: Date = new Date()): string {\n return chalk.gray(date.toISOString().replace('T', ' ').slice(0, 19));\n}\n\nexport function formatEvent(\n module: string,\n severity: EventSeverity,\n message: string,\n ip?: string,\n): string {\n const ts = formatTimestamp();\n const sev = severityColor(severity, `[${severity.toUpperCase()}]`.padEnd(10));\n const mod = chalk.cyan(`[${module}]`.padEnd(14));\n const src = ip ? chalk.magenta(` (${ip})`) : '';\n return `${ts} ${sev} ${mod} ${message}${src}`;\n}\n\nexport const logger = {\n debug: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.debug('[DEBUG]')} ${msg}`),\n info: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.info('[INFO]')} ${msg}`),\n warn: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.warn('[WARN]')} ${msg}`),\n error: (msg: string) => console.error(`${formatTimestamp()} ${LEVEL_COLORS.error('[ERROR]')} ${msg}`),\n success: (msg: string) => console.log(`${formatTimestamp()} ${chalk.green('[OK]')} ${msg}`),\n threat: (msg: string, ip?: string) => {\n const src = ip ? chalk.magenta(` from ${ip}`) : '';\n console.log(`${formatTimestamp()} ${chalk.red.bold('[THREAT]')} ${chalk.red(msg)}${src}`);\n },\n};\n\nexport function banner(): void {\n console.log(chalk.green.bold(`\n ████████╗██╗ ██╗██████╗ ███████╗ █████╗ ████████╗ ██████╗██████╗ ██╗ ██╗███████╗██╗ ██╗\n ╚══██╔══╝██║ ██║██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗██║ ██║██╔════╝██║ ██║\n ██║ ███████║██████╔╝█████╗ ███████║ ██║ ██║ ██████╔╝██║ ██║███████╗███████║\n ██║ ██╔══██║██╔══██╗██╔══╝ ██╔══██║ ██║ ██║ ██╔══██╗██║ ██║╚════██║██╔══██║\n ██║ ██║ ██║██║ ██║███████╗██║ ██║ ██║ ╚██████╗██║ ██║╚██████╔╝███████║██║ ██║\n ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝\n `));\n console.log(chalk.gray(' All-in-one security agent daemon — v0.1.0\\n'));\n}\n","import os from 'node:os';\n\nexport type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';\n\nexport interface StructuredFinding {\n type: string;\n severity: Severity;\n message: string;\n location?: string;\n details?: Record<string, unknown>;\n}\n\nexport interface RunResult {\n type: 'scan' | 'pentest';\n target: string;\n findings: StructuredFinding[];\n severity_summary: Record<Severity, number>;\n summary: string;\n error?: string;\n}\n\nexport function emptyCounts(): Record<Severity, number> {\n return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };\n}\n\nexport function summarize(findings: StructuredFinding[]): Record<Severity, number> {\n const counts = emptyCounts();\n for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;\n return counts;\n}\n\nexport function workerId(): string {\n return `${os.hostname()}/${process.pid}`;\n}\n","/**\n * Shared vocabulary for `threatcrush scan`.\n *\n * The scan pipeline is deliberately three separable pieces — rules produce\n * findings, the engine walks the tree, the reporters serialise. Keeping the\n * types here means a reporter never has to import a rule table to know what a\n * finding looks like.\n */\n\nexport type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';\n\n/**\n * How much the scanner is claiming.\n *\n * `pattern` the dangerous construct is present on the line. Nothing more.\n * `contextual` the construct sits alongside something that looks like\n * attacker-controlled input. Still not proof of exploitability,\n * but a materially stronger claim — and the only one allowed to\n * present at the rule's full severity.\n * `evidence` the match *is* the finding, not a proxy for it. A hardcoded\n * AWS key is a committed credential whether or not any request\n * ever reaches it, so the severity cap below does not apply.\n *\n * This mirrors the confidence model in `modules/code-scanner` (PRD 0004), for\n * the same reason: a regex is not data-flow analysis, and a scanner that blurs\n * the two produces confident-sounding findings that waste triage time.\n */\nexport type Confidence = 'pattern' | 'contextual' | 'evidence';\n\nexport type ScanLanguage =\n | 'javascript'\n | 'typescript'\n | 'python'\n | 'ruby'\n | 'go'\n | 'java'\n | 'php'\n | 'shell'\n | 'config'\n | 'other';\n\nexport interface ScanFinding {\n /** Stable rule identifier, e.g. `js-sql-string-building`. Used as the SARIF ruleId. */\n ruleId: string;\n /** Short human title for the construct, e.g. \"SQL assembled by concatenation\". */\n title: string;\n /** Path relative to the scan root, POSIX-separated. */\n file: string;\n /** 1-based. Whole-file findings report 1, never 0 — SARIF forbids 0. */\n line: number;\n severity: Severity;\n confidence: Confidence;\n /** What was found, in a sentence. Shown to the operator. */\n message: string;\n /** What happens if it is real. An operator triages on consequence. */\n consequence?: string;\n /** `CWE-89`. Absent for findings with no clean CWE mapping. */\n cwe?: string;\n /**\n * The matched source line, trimmed. Redacted by the reporters for secret\n * findings — see `redactSecret`.\n */\n excerpt: string;\n /** True when `excerpt` may contain credential material. */\n sensitive?: boolean;\n category: 'secret' | 'code' | 'manifest' | 'dependency' | 'file';\n}\n\nexport const SEVERITY_ORDER: readonly Severity[] = ['info', 'low', 'medium', 'high', 'critical'];\n\nexport function severityRank(severity: Severity): number {\n const index = SEVERITY_ORDER.indexOf(severity);\n return index === -1 ? 0 : index;\n}\n\n/**\n * Cap for a bare pattern match.\n *\n * A construct that merely *exists* never presents as high or critical. Enforced\n * centrally rather than per-rule so no future rule can opt out of it by\n * accident.\n */\nexport function severityFor(declared: Severity, confidence: Confidence): Severity {\n if (confidence !== 'pattern') return declared;\n return severityRank(declared) > severityRank('medium') ? 'medium' : declared;\n}\n","/**\n * Code-level vulnerability rules for `threatcrush scan`.\n *\n * Why this file exists\n * --------------------\n * Measured against the public testbed at `profullstack/malware-test-prs`, the\n * CLI scored 15.6% true-positive rate with a 0.0% false-positive rate: it found\n * every hardcoded credential and none of the code-level classes — no SQL\n * injection, XSS, SSRF, command injection, deserialisation or template\n * injection. ThreatCrush was a secrets scanner wearing a code scanner's name.\n *\n * These rules close that gap without giving up the number that was actually\n * worth having. The false-positive denominator in that testbed is a control\n * group of `SAFE:` lines — each one a *correct* implementation of the same\n * pattern the neighbouring vulnerable code gets wrong. A scanner that flags one\n * is pattern-matching on syntax instead of following the data. So every rule\n * here is built against both halves: it must fire on the vulnerable shape and\n * stay silent on the corrected shape standing next to it.\n *\n * Three mechanisms do that work:\n *\n * 1. **Shape, not keyword.** `db.query(\"SELECT … $1\", [id])` and\n * `db.query(\"SELECT … '\" + id + \"'\")` both contain `SELECT`. Only the\n * second concatenates, and only the second matches.\n * 2. **Guard windows.** A construct is exonerated by the code around it —\n * an allow-list two lines up, a `realpath` on the same line, an\n * `ObjectInputFilter` installed before the `readObject()`. Comment lines\n * are excluded from the window, because a comment saying \"no allow-list\n * here\" is not an allow-list.\n * 3. **Confidence.** A construct that merely exists is capped at medium.\n * Escalation requires visible untrusted input. See `types.ts`.\n *\n * What this is not: data-flow analysis. It is line-oriented matching with a\n * small amount of local context, and it says so. Classes that genuinely need\n * whole-function reasoning — missing CSRF tokens, check-then-use races,\n * integer overflow — are deliberately absent rather than approximated by a\n * rule that would flag every session read in the codebase. See KNOWN_GAPS.\n */\n\nimport type { Confidence, ScanLanguage, Severity } from './types';\nimport { severityFor } from './types';\n\nexport interface CodeRule {\n id: string;\n title: string;\n /** What happens if it is real. An operator triages on consequence. */\n consequence: string;\n cwe: string;\n severity: Severity;\n /** Languages the rule applies to. `undefined` means every language. */\n languages?: readonly ScanLanguage[];\n pattern: RegExp;\n /**\n * The rule describes a construct that is ordinary on its own — reading a\n * file from a computed path is just software. Only report it when untrusted\n * input is visible nearby.\n */\n needsContext?: boolean;\n /**\n * The construct *is* the defect, so its severity does not depend on context.\n *\n * The default model caps a finding at medium unless untrusted input is\n * visible nearby, which is right for injection: `exec(cmd)` is only a\n * vulnerability once `cmd` can be influenced. It is wrong for a whole class\n * of rules where nothing nearby changes the answer. `curl -k` against HTTPS\n * is a machine-in-the-middle hole whether or not a positional parameter\n * appears six lines above it; DES is broken in every file that uses it.\n *\n * Marking those rules `inherent` reports them at confidence `evidence` and\n * at their declared severity, the same treatment the credential rules get\n * for the same reason — a committed AWS key is a committed AWS key.\n *\n * Do not reach for this to make a rule look important. It is for rules whose\n * finding text would be identical no matter what surrounds the line.\n */\n inherent?: boolean;\n /**\n * Extra evidence that must appear in the guard window for the rule to fire.\n * Used where the dangerous part is the *combination* — a base64 blob is\n * harmless until something executes it.\n */\n requires?: RegExp;\n /**\n * Evidence that must appear somewhere in the file, not merely in the guard\n * window.\n *\n * For rules whose *applicability* is settled far from the match. Whether a\n * `.parse()` call is XML parsing is decided by an import at the top of the\n * file, which in a 1,600-line source is nowhere near the line that matched;\n * widening `guardBack` far enough to reach it would drag in unrelated\n * evidence for every other rule. Distinct from `requires`, which asks\n * whether the surrounding lines complete a dangerous combination.\n */\n fileRequires?: RegExp;\n /**\n * Evidence that the construct is already handled. `false` opts the rule out\n * of the generic guard entirely — the CWE-532 rules are *about* reading\n * `process.env`, so the generic guard would veto every true positive.\n */\n guard?: RegExp | false;\n /**\n * Evidence — on the matched line ONLY — that this occurrence is safe.\n *\n * Distinct from `guard`, which also searches the surrounding window. That\n * breadth is right for \"the value was sanitised three lines up\" but wrong\n * for properties of the line itself: a static `innerHTML` assignment says\n * nothing about a dynamic one two lines below it, and a context-scoped\n * guard would silently veto the dynamic one too.\n */\n lineGuard?: RegExp;\n /** Lines of context searched backwards for guards and required evidence. */\n guardBack?: number;\n /**\n * Lines searched *forwards*. Zero for almost everything: code that fixes a\n * problem generally runs before the problem. XML parser hardening is the\n * exception — the factory is constructed, then configured, so the evidence\n * is below the match.\n */\n guardForward?: number;\n}\n\n/**\n * Things that look like attacker-controlled input, per language family.\n *\n * Deliberately shallow. It is a heuristic for *ranking*, not a taint-source\n * model. A real source list would be framework-aware and interprocedural,\n * which is exactly what this subsystem promises not to pretend to be.\n */\n/**\n * `searchParams` is a read *and* a write API. `params.get('q')` is inbound\n * data; `url.searchParams.set('limit', 50)` is an outbound URL being built,\n * and treating the two alike marked every client of every third-party API as\n * taking untrusted input — which is what made the SSRF rule fire on requests\n * whose host is a compile-time constant. Only the reading half is evidence.\n */\nconst UNTRUSTED_JS =\n /\\b(?:req|request|ctx|context)\\s*\\.\\s*(?:body|query|params|param|headers|cookies|url|files)\\b|\\bprocess\\.argv\\b|\\bwindow\\.location\\b|\\bdocument\\.location\\b|\\blocation\\.(?:search|hash|href)\\b|\\bsearchParams\\s*\\.\\s*(?:get|getAll|has|entries|keys|values|forEach)\\b|\\bgetParameter\\s*\\(|\\bgetQueryString\\s*\\(|\\bgetInputStream\\s*\\(/;\n\nconst UNTRUSTED_PY = /\\brequest\\b|\\bparams\\b|\\bflask\\b|\\bsys\\.argv\\b|\\bos\\.environ\\b\\s*\\[/;\n\nconst UNTRUSTED_RB = /\\bparams\\s*\\[|\\brequest\\b|\\bcookies\\s*\\[/;\n\nconst UNTRUSTED_GO =\n /\\br\\s*\\.\\s*(?:URL|Form|Body|Header|PostForm)\\b|\\bFormValue\\s*\\(|\\bQuery\\s*\\(\\s*\\)\\s*\\.\\s*Get\\s*\\(|\\bmux\\.Vars\\s*\\(/;\n\nconst UNTRUSTED_JAVA =\n /\\bgetParameter\\s*\\(|\\bgetQueryString\\s*\\(|\\bgetHeader\\s*\\(|\\bgetInputStream\\s*\\(|\\bgetCookies\\s*\\(|\\b@RequestParam\\b|\\b@PathVariable\\b/;\n\n/**\n * Untrusted input to a shell script: what the caller controls.\n *\n * Positional parameters and `read` are the whole surface. Environment\n * variables are deliberately absent — a script's own configuration arrives\n * that way, so treating `$PREFIX` as attacker-controlled would mark every\n * line of every installer.\n */\nconst UNTRUSTED_SH =\n /\\$\\{?[1-9]\\d*\\b|\\$[@*]|\\$\\{@\\}|\\bread\\s+(?:-\\S+\\s+)*[A-Za-z_]\\w*|\\$\\{?REPLY\\b|\\$\\{?QUERY_STRING\\b/;\n\n/** PHP's superglobals are the request, verbatim. */\nconst UNTRUSTED_PHP =\n /\\$_(?:GET|POST|REQUEST|COOKIE|FILES|SERVER)\\b|\\bphp:\\/\\/input\\b|\\bgetallheaders\\s*\\(/;\n\nexport function untrustedPatternFor(language: ScanLanguage): RegExp {\n switch (language) {\n case 'php':\n return UNTRUSTED_PHP;\n case 'shell':\n return UNTRUSTED_SH;\n case 'python':\n return UNTRUSTED_PY;\n case 'ruby':\n return UNTRUSTED_RB;\n case 'go':\n return UNTRUSTED_GO;\n case 'java':\n return UNTRUSTED_JAVA;\n default:\n return UNTRUSTED_JS;\n }\n}\n\n/**\n * Evidence that the dangerous construct on this line is already handled.\n *\n * Every entry here was added because a *correct* implementation in the testbed\n * corpus was otherwise flagged. They are named after what the safe code does,\n * not after what the finding is:\n *\n * allow/whitelist an allow-list decides what reaches the sink\n * escape/sanitize the value is encoded for its output context\n * realpath/… the path is resolved and re-checked before use\n * process.env/… the value comes from the environment, not the request\n * ObjectInputFilter a class allow-list is installed on the stream\n *\n * A guard match suppresses the finding rather than downgrading it. Reporting\n * \"we saw an allow-list but flagged it anyway\" is the behaviour that makes\n * operators stop reading scanner output.\n */\nexport const GENERIC_GUARD =\n // `esc(`, `aEsc(`, `htmlEscape(`, `escapeHtml(` — the escaper is almost\n // never *named* `escapeHtml` in real code. It gets aliased to something\n // short because it is called on nearly every interpolation, so matching only\n // the long spellings reported the codebases that escape most rigorously.\n //\n // The identifier must END at the escaper (with at most a known output-context\n // suffix). An earlier, looser form also matched `describe(`, which would have\n // silenced findings across every test file in every repository.\n /\\ballow(?:ed|list|_list|ed_hosts)?\\b|\\bwhitelist\\b|\\b\\w{0,6}[Ee]sc(?:ape)?(?:[Hh]tml|HTML|[Xx]ml|XML|[Ss]ql|[Aa]ttr|[Jj]s|[Uu]ri|[Uu]rl)?\\s*\\(|\\bhtml_escape\\b|\\bhtmlspecialchars\\s*\\(|\\bsanitiz\\w*\\b|\\bencoded\\b|\\brealpath\\b|\\bcommonpath\\b|\\bresolve\\(\\)\\.startsWith\\b|\\bprocess\\.env\\b|\\bos\\.environ\\b|\\bgetenv\\b|\\bENV\\s*\\[|setObjectInputFilter|ObjectInputFilter/i;\n\n/** Evidence that an XML parser factory has been hardened against XXE. */\nconst XXE_GUARD =\n /FEATURE_SECURE_PROCESSING|setExpandEntityReferences|disallow-doctype-decl|external-general-entities|external-parameter-entities|setXIncludeAware\\s*\\(\\s*false/;\n\n/**\n * Evidence that a Java source parses XML at all.\n *\n * The package names are the reliable half: a file that reaches for\n * `javax.xml.parsers` or `org.xml.sax` has declared its intent at the top,\n * whatever the local variable ends up being called. The bare type names cover\n * sources that import by wildcard or sit in the same package.\n */\nconst XML_PARSING_FILE =\n /\\b(?:javax\\.xml|org\\.xml\\.sax|org\\.w3c\\.dom|org\\.jdom2?|org\\.dom4j|XmlPullParser|DocumentBuilderFactory|DocumentBuilder|SAXParserFactory|SAXParser|XMLInputFactory|XMLReaderFactory|XMLReader|SAXBuilder|SAXReader)\\b/;\n\n/** A sink that executes whatever string reaches it. */\nconst CODE_SINK =\n /\\bglobalThis\\s*\\[|\\bconstructor\\b|\\beval\\b|\\bFunction\\b|\\brun\\s*\\(|\\bvm\\s*\\.\\s*run/;\n\n/** A sink whose output is retained: a log, a console, an outbound request. */\nconst EXFIL_SINK = /\\bconsole\\s*\\.\\s*(?:log|debug|info|warn|error)\\s*\\(|\\bfetch\\s*\\(|\\baxios\\b|\\brequest\\s*\\(|\\.\\s*send\\s*\\(/;\n\n/**\n * SQL text that is being *assembled* rather than parameterised.\n *\n * The four tails are the four ways to build a string in the languages this\n * covers: `+` concatenation, `${}` template interpolation, `%`/`.format()`\n * substitution, and Ruby's `#{}`. A bound placeholder (`$1`, `?`, `%s` passed\n * as an argument) leaves a comma after the closing quote and matches none of\n * them — which is exactly how the safe counterparts stay unflagged.\n */\nconst SQL_KEYWORDS = 'SELECT|INSERT\\\\s+INTO|INSERT|UPDATE|DELETE\\\\s+FROM|DELETE|DROP|UNION\\\\s+SELECT';\n\n/**\n * A quoted string containing a SQL verb.\n *\n * Two variants, one per quote character, because the interesting strings\n * contain the *other* quote:\n *\n * \"SELECT id FROM users WHERE id = '\" + id + \"'\"\n *\n * A single `[\"'][^\"'\\n]*` class stops dead at that inner `'` and matches\n * nothing — which silently drops the most common SQL-injection shape in every\n * language at once. Match a double-quoted string with a class that excludes\n * only `\"`, and vice versa.\n */\nconst SQL_IN_DOUBLE = `\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*\"`;\nconst SQL_IN_SINGLE = `'[^'\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^'\\\\n]*'`;\nconst SQL_STRING = `(?:${SQL_IN_DOUBLE}|${SQL_IN_SINGLE})`;\n\nexport const CODE_RULES: readonly CodeRule[] = [\n // ── Injection: SQL ───────────────────────────────────────────────────────\n {\n id: 'sql-string-concatenation',\n title: 'SQL assembled by concatenation or interpolation',\n consequence:\n 'A quote in the interpolated value changes the query’s meaning — the query runs as the attacker wrote it, not as you wrote it.',\n cwe: 'CWE-89',\n severity: 'critical',\n // The tail is what distinguishes assembly from parameterisation. A bound\n // query leaves a comma after the closing quote (`\"… = $1\", [id]`) and\n // matches none of these.\n pattern: new RegExp(\n `${SQL_STRING}\\\\s*\\\\+|` +\n `${SQL_STRING}\\\\s*%\\\\s*[\\\\w(]|` +\n `${SQL_STRING}\\\\s*\\\\.\\\\s*format\\\\s*\\\\(|` +\n '\\\\+\\\\s*(?:\"[^\"\\\\n]*|\\'[^\\'\\\\n]*)(?:WHERE|ORDER\\\\s+BY|VALUES|SET)\\\\b',\n 'i',\n ),\n },\n {\n id: 'sql-template-interpolation',\n title: 'SQL built from a template literal or f-string',\n consequence:\n 'Template interpolation is string concatenation with nicer syntax — it binds nothing and escapes nothing.',\n cwe: 'CWE-89',\n severity: 'critical',\n pattern: new RegExp(\n `\\`[^\\`\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\\`\\\\n]*\\\\$\\\\{|` +\n `\\\\bf\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*\\\\{|` +\n `\\\\bf'[^'\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^'\\\\n]*\\\\{`,\n 'i',\n ),\n },\n {\n id: 'sql-format-call',\n title: 'SQL text produced by a format helper',\n consequence:\n '`Sprintf`/`String.format` substitute without quoting; the resulting string is concatenated SQL by another name.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['go', 'java'],\n pattern: new RegExp(\n `\\\\b(?:fmt\\\\.Sprintf|String\\\\.format)\\\\s*\\\\(\\\\s*\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b`,\n 'i',\n ),\n },\n {\n id: 'rb-sql-interpolation',\n title: 'ActiveRecord query built by string interpolation',\n consequence:\n '`where(\"… #{value}\")` interpolates before the adapter sees it, so no binding ever happens.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['ruby'],\n pattern:\n /\\b(?:where|find_by_sql|execute|select_all|select_values|order|group|pluck)\\s*[( ]\\s*(?:\"[^\"\\n]*|'[^'\\n]*)#\\{/,\n },\n\n // ── Injection: OS command ────────────────────────────────────────────────\n {\n id: 'js-shell-exec-interpolation',\n title: 'shell execution with an interpolated string',\n consequence: 'A `;` or `$(…)` in the interpolated value runs as the server user.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:exec|execSync|spawn|spawnSync)\\s*\\(\\s*(?:`[^`]*\\$\\{|['\"][^'\"]*['\"]\\s*\\+|[a-zA-Z_$][\\w$]*\\s*\\+)/,\n },\n {\n id: 'py-shell-command-string',\n title: 'shell command built from a string',\n consequence:\n '`os.system` and `shell=True` hand the string to `/bin/sh`, which happily interprets metacharacters.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['python'],\n pattern:\n /\\bos\\.(?:system|popen)\\s*\\(\\s*(?:f?['\"][^'\"]*['\"]\\s*(?:\\+|%|\\.\\s*format)|f['\"]|[a-zA-Z_]\\w*\\s*[,)])|\\bsubprocess\\.(?:run|call|check_call|check_output|Popen)\\s*\\([^)]*\\bshell\\s*=\\s*True/,\n },\n {\n id: 'go-shell-exec-command',\n title: 'exec.Command invoking a shell',\n consequence:\n 'Passing `sh -c` re-introduces the shell that `exec.Command`’s argv interface exists to avoid.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['go'],\n pattern: /\\bexec\\.Command(?:Context)?\\s*\\(\\s*(?:ctx\\s*,\\s*)?\"(?:\\/bin\\/)?(?:sh|bash|zsh|cmd|powershell)\"\\s*,\\s*\"(?:-c|\\/c)\"/,\n },\n {\n id: 'rb-backtick-interpolation',\n title: 'backtick command with interpolation',\n consequence: 'Ruby backticks are a shell invocation; `#{}` inside one is command injection.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['ruby'],\n pattern: /`[^`\\n]*#\\{|\\bsystem\\s*\\(\\s*[\"'][^\"'\\n]*#\\{|%x\\[[^\\]]*#\\{/,\n },\n\n // ── Injection: dynamic code ──────────────────────────────────────────────\n {\n id: 'js-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence: 'Any string reaching this call executes as code with the process’ privileges.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\beval\\s*\\(|\\bnew\\s+Function\\s*\\(|\\bvm\\s*\\.\\s*run(?:InThisContext|InNewContext|InContext)\\s*\\(|\\bset(?:Timeout|Interval)\\s*\\(\\s*(?:['\"`]|(?:req|request|ctx|params|query|body)\\b)/,\n },\n {\n id: 'js-indirect-code-sink',\n title: 'code sink reached indirectly',\n consequence:\n 'Resolving `eval`/`Function` through `globalThis[…]` or `.constructor` hides the sink from literal matching. Legitimate code has no reason to.',\n cwe: 'CWE-506',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bglobalThis\\s*\\[\\s*[a-zA-Z_$][\\w$]*\\s*\\]|\\(\\s*function\\s*\\(\\s*\\)\\s*\\{\\s*\\}\\s*\\)\\s*\\.\\s*constructor/,\n },\n {\n id: 'js-encoded-payload-execution',\n title: 'encoded blob decoded next to a code sink',\n consequence:\n 'A base64 literal that is decoded and executed is the standard shape of a planted backdoor; the encoding exists to defeat review.',\n cwe: 'CWE-506',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bBuffer\\.from\\s*\\(\\s*[\\w.$]+\\s*,\\s*['\"]base64['\"]\\s*\\)|\\batob\\s*\\(\\s*[\\w.$]+\\s*\\)/,\n requires: CODE_SINK,\n guardBack: 6,\n guardForward: 3,\n },\n {\n id: 'py-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence: 'Any string reaching this call executes as Python with the process’ privileges.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\b(?:eval|exec)\\s*\\(\\s*(?!['\"]\\s*\\))[a-zA-Z_(f'\"]/,\n needsContext: true,\n },\n {\n id: 'rb-dynamic-dispatch',\n title: 'dynamic code execution or unrestricted #send',\n consequence:\n '`eval` runs arbitrary Ruby; unrestricted `#send` lets the caller invoke any method on the receiver, including private ones.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['ruby'],\n pattern: /\\beval\\s*\\(|\\binstance_eval\\s*\\(|\\bclass_eval\\s*\\(|\\.\\s*send\\s*\\(\\s*(?:params|request|args)\\b/,\n },\n\n // ── Cross-site scripting ─────────────────────────────────────────────────\n {\n id: 'js-unescaped-html-sink',\n title: 'unescaped HTML rendering',\n consequence: 'A script tag in the value executes in the victim’s session — stored or reflected XSS.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bdangerouslySetInnerHTML\\s*=|\\.\\s*(?:innerHTML|outerHTML)\\s*=\\s*(?!\\s*['\"`]\\s*['\"`]\\s*;?\\s*$)|\\bdocument\\s*\\.\\s*write(?:ln)?\\s*\\(|\\.\\s*insertAdjacentHTML\\s*\\(/,\n /**\n * A whole-statement assignment of a string with no interpolation and no\n * concatenation carries no data, so it cannot carry attacker data. This\n * was the single largest source of noise: a codebase that builds its UI\n * with innerHTML reports every static heading and spinner as XSS, and a\n * rule that flags 40 safe lines to catch one real one gets switched off.\n *\n * Line-scoped on purpose — see `lineGuard`.\n */\n lineGuard:\n /(?:innerHTML|outerHTML)\\s*=\\s*(?:'[^'\\\\]*'|\"[^\"\\\\]*\"|`[^`$\\\\]*`)\\s*;?\\s*$/,\n },\n {\n id: 'java-html-writer-concatenation',\n title: 'HTML written to the response by concatenation',\n consequence:\n 'The servlet writer performs no encoding; a value concatenated into markup is rendered as markup.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['java'],\n pattern: /\\b(?:println|print|write)\\s*\\(\\s*\"[^\"\\n]*<[^\"\\n]*\"\\s*\\+/,\n },\n {\n id: 'rb-unescaped-output',\n title: 'Rails output escaping bypassed',\n consequence:\n '`html_safe` and `raw` tell Rails the string is already safe. If it came from a parameter, it is not.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['ruby'],\n pattern: /\\.\\s*html_safe\\b|\\braw\\s*\\(\\s*(?:params|request|@)|\\blink_to\\s+[^,\\n]+,\\s*params\\s*\\[/,\n },\n {\n id: 'py-template-autoescape-off',\n title: 'template rendering with escaping disabled',\n consequence:\n 'With autoescape off — or a `|safe` filter — every interpolated value is rendered as markup.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['python'],\n pattern: /\\bEnvironment\\s*\\([^)]*\\bautoescape\\s*=\\s*False|\\|\\s*safe\\b|\\bMarkup\\s*\\(\\s*(?!['\"])/,\n },\n {\n id: 'py-template-from-input',\n title: 'template compiled from a non-literal source',\n consequence:\n 'Server-side template injection. In Jinja2 the sandbox is escapable, so this escalates from XSS to remote code execution.',\n cwe: 'CWE-1336',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\bTemplate\\s*\\(\\s*(?!['\"])[a-zA-Z_]/,\n needsContext: true,\n },\n\n // ── Server-side request forgery ──────────────────────────────────────────\n {\n id: 'js-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bfetch\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]|\\bhttps?\\s*\\.\\s*(?:get|request)\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]|\\baxios\\s*\\.\\s*get\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]/,\n needsContext: true,\n },\n {\n id: 'py-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['python'],\n pattern:\n /\\brequests\\.(?:get|request|head)\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]|\\burlopen\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]|\\bhttpx\\.get\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]/,\n needsContext: true,\n },\n {\n id: 'go-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['go'],\n pattern: /\\bhttp\\.(?:Get|Post|Head)\\s*\\(\\s*(?:[a-zA-Z_]\\w*\\s*[,)]|\"[^\"]*\"\\s*\\+)/,\n needsContext: true,\n },\n\n // ── Open redirect ────────────────────────────────────────────────────────\n {\n id: 'js-open-redirect',\n title: 'redirect to a non-constant destination',\n consequence:\n 'Your domain becomes the credible first hop of a phishing chain; the victim sees your hostname in the link they clicked.',\n cwe: 'CWE-601',\n severity: 'medium',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:res|response)\\s*\\.\\s*redirect\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*\\)|\\bwindow\\s*\\.\\s*location(?:\\s*\\.\\s*(?:href|replace))?\\s*(?:=\\s*[a-zA-Z_$]|\\(\\s*[a-zA-Z_$][\\w$]*\\s*\\))/,\n needsContext: true,\n },\n\n // ── Deserialisation ──────────────────────────────────────────────────────\n {\n id: 'py-unsafe-deserialization',\n title: 'deserialisation of untrusted data',\n consequence:\n '`pickle` and `yaml.load` instantiate arbitrary types during parsing — a crafted payload is remote code execution, not a parse error.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\bpickle\\.loads?\\s*\\(|\\bcPickle\\.loads?\\s*\\(|\\bmarshal\\.loads\\s*\\(|\\byaml\\.load\\s*\\(|\\bjsonpickle\\.decode\\s*\\(/,\n },\n {\n id: 'java-unsafe-deserialization',\n title: 'Java deserialisation without a class filter',\n consequence:\n 'A gadget chain in the classpath turns `readObject()` on attacker bytes into remote code execution.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['java'],\n pattern: /\\breadObject\\s*\\(\\s*\\)|\\bnew\\s+ObjectInputStream\\s*\\(/,\n guardBack: 8,\n // The stream is constructed, *then* filtered. Without a forward window the\n // guarded case matches on its constructor line and reports a correct\n // implementation as a finding.\n guardForward: 6,\n },\n {\n id: 'js-unsafe-yaml-load',\n title: 'YAML parsed with type resolution enabled',\n consequence: 'A crafted document can instantiate arbitrary types during parsing.',\n cwe: 'CWE-502',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern: /\\byaml\\s*\\.\\s*load\\s*\\((?![^)]*safe)|\\bloadAll\\s*\\([^)]*unsafe/i,\n },\n\n // ── XML external entities ────────────────────────────────────────────────\n //\n // Evidence that a file parses XML at all. The XXE rules match on receiver\n // *names* — `builder.parse(is)` is the shape the vulnerability actually takes,\n // and the declared type is rarely on that line — so without this the pattern\n // reads any `.parse()` on anything suffixed Builder, Parser or Reader as XML.\n // In practice that meant a hostname-mask parser (`HostMask.Parser.parse(...)`)\n // was reported as CWE-611 at high severity.\n //\n // An import is the cheapest honest signal: a file that parses XML says so at\n // the top, and one that never mentions XML is not parsing it.\n {\n id: 'java-xxe-parser-defaults',\n title: 'XML parser left on its insecure defaults',\n consequence:\n 'External entity expansion reads local files and makes outbound requests on the parser’s behalf — file disclosure and SSRF from a document.',\n cwe: 'CWE-611',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\b(?:DocumentBuilderFactory|SAXParserFactory|XMLInputFactory|TransformerFactory|SchemaFactory)\\s*\\.\\s*newInstance\\s*\\(\\s*\\)/,\n guard: XXE_GUARD,\n guardBack: 4,\n guardForward: 8,\n },\n {\n id: 'java-xxe-parse-call',\n title: 'XML parsed by a builder that was never hardened',\n consequence:\n 'The expansion happens at `parse()`. Flagging only the factory misses the line where the document is actually read.',\n cwe: 'CWE-611',\n severity: 'high',\n languages: ['java'],\n // Receiver-qualified so `LocalDate.parse(s)` and friends stay out of it.\n // The suffix alone is not enough — plenty of parsers parse things that are\n // not XML — so `fileRequires` decides whether the file is in scope at all.\n pattern: /\\b\\w*(?:[Bb]uilder|[Pp]arser|[Rr]eader)\\s*\\.\\s*parse\\s*\\(/,\n fileRequires: XML_PARSING_FILE,\n guard: XXE_GUARD,\n guardBack: 6,\n guardForward: 4,\n },\n\n // ── Path traversal ───────────────────────────────────────────────────────\n {\n id: 'py-path-traversal',\n title: 'file opened at a path built from input',\n consequence: 'A `../` sequence — or an absolute path — reads or writes outside the intended directory.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['python'],\n pattern: /\\bopen\\s*\\(\\s*(?:os\\.path\\.join\\s*\\(|[a-zA-Z_]\\w*\\s*\\+|f['\"])/,\n needsContext: true,\n },\n {\n id: 'js-path-traversal',\n title: 'file path built from a variable',\n consequence: 'A `../` sequence in the value reads or writes outside the intended directory.',\n cwe: 'CWE-22',\n severity: 'medium',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:readFile|readFileSync|writeFile|writeFileSync|createReadStream|createWriteStream|unlink|unlinkSync|sendFile)\\s*\\(\\s*(?:`[^`]*\\$\\{|[a-zA-Z_$][\\w$]*\\s*\\+|path\\.join\\s*\\([^)]*(?:req|request)\\b)/,\n needsContext: true,\n },\n\n // ── Cryptography, tokens, randomness ─────────────────────────────────────\n {\n id: 'js-jwt-decode-without-verify',\n title: 'JWT decoded without verifying the signature',\n consequence:\n '`decode` parses the claims and checks nothing. Anyone can mint a token with any `sub` and any `role`.',\n cwe: 'CWE-347',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bjwt\\s*\\.\\s*decode\\s*\\(|\\bjsonwebtoken\\s*\\.\\s*decode\\s*\\(|\\bdecodeJwt\\s*\\(/,\n },\n {\n id: 'tls-verification-disabled',\n inherent: true,\n title: 'TLS certificate verification disabled',\n consequence:\n 'Every connection made this way is trivially interceptable; the encryption is decorative.',\n cwe: 'CWE-295',\n severity: 'high',\n pattern:\n /rejectUnauthorized\\s*:\\s*false|NODE_TLS_REJECT_UNAUTHORIZED\\s*[=:]\\s*['\"]?0|strictSSL\\s*:\\s*false|\\bverify\\s*=\\s*False\\b|InsecureSkipVerify\\s*:\\s*true/,\n },\n {\n id: 'weak-hash-on-credential',\n title: 'broken hash used on a credential',\n consequence: 'MD5 and SHA-1 are fast and collision-prone; hashed passwords are recoverable.',\n cwe: 'CWE-327',\n severity: 'high',\n pattern:\n /(?:createHash|hashlib|MessageDigest\\.getInstance|Digest::)\\s*[.(]?\\s*['\"]?(?:md5|MD5|sha1|SHA-?1)['\"]?\\s*\\)?[\\s\\S]{0,80}(?:password|passwd|secret|token|credential)/i,\n },\n {\n id: 'insecure-randomness-for-secret',\n title: 'predictable randomness used for a security value',\n consequence:\n '`Math.random`/`random.random` are predictable; tokens, session ids and reset codes built from them are guessable.',\n cwe: 'CWE-338',\n severity: 'high',\n pattern:\n /(?:token|secret|password|salt|nonce|session|otp|reset|apikey|api_key)[\\w]*\\s*[:=][^;\\n]{0,60}(?:Math\\s*\\.\\s*random\\s*\\(|\\brandom\\s*\\.\\s*(?:random|randint|choice)\\s*\\(|\\brand\\s*\\()/i,\n },\n {\n id: 'redos-nested-quantifier',\n title: 'regex with nested unbounded quantifiers',\n consequence:\n 'Catastrophic backtracking: a crafted input of a few dozen characters pins a CPU core for minutes.',\n cwe: 'CWE-1333',\n severity: 'medium',\n pattern: /\\([^)\\n]*[+*]\\s*\\)\\s*[+*]|\\([^)\\n]*\\{\\d+,\\}\\s*\\)\\s*[+*{]/,\n },\n\n // ── Temporary files ──────────────────────────────────────────────────────\n {\n id: 'insecure-temp-file',\n title: 'predictable temporary file path',\n consequence:\n 'A predictable name in a world-writable directory is a symlink attack: an attacker pre-creates the path and your process writes through it.',\n cwe: 'CWE-377',\n severity: 'medium',\n // A hardcoded path under /tmp is the finding whether or not it is\n // formatted: `\"/tmp/application.log.tmp\"` is worse than the PID-based one,\n // because every process on the host can predict it exactly.\n pattern:\n /\\btempfile\\.mktemp\\s*\\(|\\bos\\.tmpnam\\s*\\(|['\"]\\/tmp\\/[^'\"\\n]+['\"]|['\"]\\/tmp\\/[^'\"\\n]*\\{|\\bFile\\.createTempFile\\s*\\(/,\n },\n\n // ── Information exposure ─────────────────────────────────────────────────\n {\n id: 'py-stack-trace-returned',\n title: 'stack trace returned to the caller',\n consequence:\n 'Tracebacks leak absolute paths, dependency versions and source fragments — the reconnaissance an attacker would otherwise have to guess at.',\n cwe: 'CWE-209',\n severity: 'medium',\n languages: ['python'],\n pattern: /\\breturn\\b[^\\n]*\\btraceback\\.(?:format_exc|format_exception|print_exc)\\s*\\(|\\breturn\\b[^\\n]*\\bstr\\s*\\(\\s*e\\s*\\)/,\n },\n {\n id: 'js-environment-exfiltration',\n title: 'process environment serialised into a payload',\n consequence:\n 'The environment is where every secret lives. Serialising it whole into a request body is credential exfiltration regardless of the endpoint.',\n cwe: 'CWE-532',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bJSON\\.stringify\\s*\\(\\s*\\{?[^)]*\\bprocess\\.env\\b(?!\\s*\\.)/,\n guard: false,\n },\n {\n id: 'js-credential-logged',\n title: 'credential read from the environment into a log sink',\n consequence:\n 'CI retains job logs, and on public forks it publishes them. A token printed once is a token leaked permanently.',\n cwe: 'CWE-532',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern: /\\b(?:token|apiKey|api_key|secret|password|credential|auth)\\w*\\s*:\\s*process\\.env\\.\\w+/i,\n requires: EXFIL_SINK,\n guard: false,\n guardBack: 4,\n guardForward: 1,\n },\n\n // ── Prototype pollution ──────────────────────────────────────────────────\n {\n id: 'js-prototype-pollution',\n title: 'write to a prototype-reachable key',\n consequence:\n 'An attacker-supplied `__proto__` key changes behaviour for every object in the process, including ones it never touched.',\n cwe: 'CWE-1321',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\[\\s*['\"]__proto__['\"]\\s*\\]|\\bObject\\s*\\.\\s*assign\\s*\\(\\s*[\\w.$]*\\.prototype\\b|\\.\\s*__proto__\\s*=/,\n },\n\n // ── Shell ────────────────────────────────────────────────────────────────\n //\n // `shell` was a language the type system knew about and no rule targeted, so\n // a repository written entirely in bash got secret detection and nothing\n // else. Installers, CI helpers and packaging scripts are where a great deal\n // of privileged work actually happens, and they run as whoever invoked them.\n {\n id: 'sh-remote-script-execution',\n inherent: true,\n title: 'network output piped into a shell',\n consequence:\n 'Whatever that URL serves at the moment this runs is executed as the invoking user. There is no version, no signature, and no review — a compromise of the host, or anyone able to answer for it, is a compromise of every machine that runs the script.',\n cwe: 'CWE-494',\n severity: 'high',\n languages: ['shell'],\n // The pipe must be the *next* thing: `curl -o f url && sh f` is a different\n // (and checkable) shape, and `curl url | jq` is not an execution at all.\n pattern: /\\b(?:curl|wget)\\b[^|\\n]*\\|\\s*(?:sudo\\s+(?:-\\S+\\s+)*)?(?:\\/bin\\/|\\/usr\\/bin\\/)?(?:ba|da|k|z|a)?sh\\b/,\n // Nothing on this line can exonerate it. Integrity checking happens in a\n // separate step by construction, so a window guard would only mislead.\n guard: false,\n },\n {\n id: 'sh-eval-expansion',\n title: 'eval on an expanded string',\n consequence:\n 'The expansion is re-parsed as shell source, so a `;` or `$(…)` anywhere in the value runs as a command rather than arriving as data.',\n cwe: 'CWE-78',\n severity: 'high',\n languages: ['shell'],\n // Matched against eval's *argument*, not against the rest of the line.\n //\n // `\\beval\\b.*\\$` looks equivalent and is not: bash's ordinary dynamic-range\n // idiom, `eval echo {$((k + 1))..$((k + n))}`, contains `$k` inside the\n // arithmetic, so a line-wide search finds an expansion in a construct that\n // cannot carry a command — `$((…))` is parsed as an expression, where a `;`\n // is a syntax error rather than a second command. That spelling reported\n // 355 findings in one 3,500-line script, all of them the same safe loop.\n //\n // What is left is the form where eval is handed a value directly —\n // `eval \"$cmd\"`, `eval $cmd`, `eval \"$(…)\"` — which is the shape that\n // actually re-parses untrusted text as source. `eval echo $x` is not\n // covered; catching it without also catching the range idiom needs to know\n // which expansions are arithmetic, which is parsing, not matching.\n pattern: /\\beval\\s+(?:-\\S+\\s+)*(?:\"\\s*)?\\$(?:\\{?[A-Za-z_]\\w*|\\((?!\\())/,\n // The shell-init idiom `eval \"$(tool init -)\"` is the documented interface\n // of most version managers. It is still eval of program output, but the\n // program is a fixed local binary, and flagging it reports every developer\n // dotfile in existence.\n lineGuard:\n /\\beval\\s+\"?\\$\\(\\s*(?:ssh-agent|dircolors|direnv|rbenv|pyenv|nodenv|goenv|jenv|tfenv|opam|luarocks|conda|mamba|zoxide|starship|mise|asdf|fnm|nvm|brew|thefuck|register-python-argcomplete|_\\w+_completion)\\b/,\n },\n {\n id: 'sh-unquoted-expansion-destructive',\n title: 'unquoted expansion in a destructive command',\n consequence:\n 'An unquoted expansion is word-split and glob-expanded before the command sees it. A value with a space removes two paths instead of one; an empty value removes the argument entirely, which is how `rm -rf $DIR/` becomes `rm -rf /`.',\n cwe: 'CWE-78',\n severity: 'high',\n languages: ['shell'],\n // `[^\"'\\n]*?` cannot cross a quote, so `rm -rf \"$dir\"` — the correct form —\n // never reaches the `$` and never matches. Only a genuinely bare expansion\n // does. Restricted to recursive/forced removal: a bare `$f` in `rm $f` is\n // sloppy, but it is not the shape that erases a filesystem.\n pattern: /\\brm\\s+(?:-[a-zA-Z-]*[rRf][a-zA-Z-]*\\s+)+[^\"'\\n]*?\\$\\{?[A-Za-z_]/,\n },\n {\n id: 'sh-insecure-transport-flag',\n inherent: true,\n title: 'certificate verification disabled',\n consequence:\n 'Anyone positioned between this host and the server can substitute the response. When the response is a package, a key or a script, that is remote code execution with the transport doing nothing to stop it.',\n cwe: 'CWE-295',\n severity: 'high',\n languages: ['shell'],\n pattern:\n /\\b(?:curl|wget)\\b[^\\n|]*(?:\\s-k(?=\\s|$)|\\s--insecure\\b|\\s--no-check-certificate\\b)/,\n // Over plain HTTP there is no certificate to skip, so the flag is inert and\n // this rule has nothing to say — `sh-plaintext-download` is the finding\n // that fits. Reporting both put two entries on one line, one of which\n // recommended a fix that would change nothing.\n lineGuard: /^(?!.*https:\\/\\/).*\\bhttp:\\/\\//,\n },\n {\n id: 'sh-plaintext-download',\n inherent: true,\n title: 'download over plain HTTP',\n consequence:\n 'The response arrives unauthenticated over a channel any intermediary can rewrite. Where the payload is an archive, a package list or a key, substituting it is straightforward and leaves nothing for the script to notice.',\n cwe: 'CWE-319',\n severity: 'high',\n languages: ['shell'],\n pattern: /\\b(?:curl|wget)\\b[^\\n|]*\\bhttp:\\/\\//,\n // Loopback and link-local are not carried over a network anyone can sit on.\n lineGuard:\n /http:\\/\\/(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[::1\\]|169\\.254\\.|host\\.docker\\.internal)\\b/,\n },\n {\n id: 'sh-world-writable-permissions',\n inherent: true,\n title: 'world-writable permissions',\n consequence:\n 'Any local account can rewrite the file. If it is a script, a config or anything on a privileged path, the next process to read it runs someone else’s content.',\n cwe: 'CWE-732',\n severity: 'medium',\n languages: ['shell'],\n pattern: /\\bchmod\\s+(?:-[a-zA-Z-]+\\s+)*(?:0?777|a\\+rwx|ugo\\+rwx|a=rwx)\\b/,\n },\n {\n id: 'sh-predictable-temp-path',\n title: 'predictable temporary file',\n consequence:\n 'The name is guessable, so a local attacker can create it first — as a symlink to somewhere that matters — and the script writes through it with its own privileges.',\n cwe: 'CWE-377',\n severity: 'medium',\n languages: ['shell'],\n // Redirection or an explicit write into a literal `/tmp` path. A `$$` or\n // `$RANDOM` suffix is still predictable, so it is not treated as a fix;\n // `mktemp` is, and it is the guard below.\n pattern: /(?:>{1,2}\\s*|\\b(?:tee|touch|cp|mv|install)\\s+(?:-\\S+\\s+)*)\\/tmp\\/[\\w.$-]+/,\n guard: /\\bmktemp\\b/,\n guardBack: 6,\n guardForward: 2,\n },\n\n // ── PHP ──────────────────────────────────────────────────────────────────\n //\n // `php` was the second language in `ScanLanguage` that no rule targeted, for\n // the same reason `shell` was: nothing checks the two lists against each\n // other. `LANGUAGE_COVERAGE` in the tests does now.\n {\n id: 'php-sql-interpolation',\n title: 'SQL assembled by interpolation',\n consequence:\n 'PHP interpolates variables inside double-quoted strings, so the value is part of the statement before the driver ever sees it. A quote in the value ends the literal and the rest is parsed as SQL.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['php'],\n // Interpolation (`\"… $id …\"`, `\"… {$id} …\"`) or concatenation onto a SQL\n // string. A prepared statement passes placeholders and binds separately,\n // so its query string contains neither.\n pattern: new RegExp(\n `\\\\b(?:mysqli_query|mysql_query|pg_query|->\\\\s*(?:query|exec|unprepared))\\\\s*\\\\([^)]*(?:\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*(?:\\\\$\\\\w+|\\\\{\\\\$)|${SQL_STRING}\\\\s*\\\\.)`,\n 'i',\n ),\n },\n {\n id: 'php-shell-exec-interpolation',\n title: 'shell command built from a variable',\n consequence:\n 'The string is handed to `/bin/sh`, which interprets `;`, `|` and `$(…)` in whatever the variable held.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['php'],\n pattern:\n /\\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec)\\s*\\(\\s*(?:\"[^\"\\n]*(?:\\$\\w+|\\{\\$)|'[^'\\n]*'\\s*\\.|\\$\\w+\\s*\\.)/,\n // `escapeshellarg`/`escapeshellcmd` are the correct answer and are usually\n // applied inline, so a line-scoped guard is the right shape.\n lineGuard: /\\bescapeshell(?:arg|cmd)\\s*\\(/,\n },\n {\n id: 'php-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence:\n 'Whatever reaches this call is executed as PHP source with the privileges of the web process.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['php'],\n pattern: /\\b(?:eval|assert|create_function)\\s*\\(\\s*(?:\\$\\w+|\"[^\"\\n]*(?:\\$\\w+|\\{\\$))/,\n guard: false,\n },\n {\n id: 'php-dynamic-file-inclusion',\n title: 'include path built from a variable',\n consequence:\n 'The included file is executed, not read. A traversal sequence reaches any file the process can open, and with a remote wrapper enabled the path need not be local at all.',\n cwe: 'CWE-98',\n severity: 'critical',\n languages: ['php'],\n pattern:\n /\\b(?:include|include_once|require|require_once)\\s*(?:\\(\\s*)?(?:\\$\\w+|\"[^\"\\n]*(?:\\$\\w+|\\{\\$)|'[^'\\n]*'\\s*\\.)/,\n // A basename-and-allow-list is the standard fix; `basename` alone still\n // leaves the extension open, but it defeats traversal, which is the part\n // this rule is about.\n lineGuard: /\\bbasename\\s*\\(/,\n },\n {\n id: 'php-unserialize-untrusted',\n title: 'unserialize on request data',\n consequence:\n 'PHP object deserialisation instantiates classes and runs their magic methods. With a suitable class in scope this is remote code execution, and no `unserialize` option short of `allowed_classes => false` prevents it.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['php'],\n pattern: /\\bunserialize\\s*\\(\\s*(?:\\$_(?:GET|POST|REQUEST|COOKIE)\\b|\\$\\w+)/,\n // The key is an array key and is normally quoted: `['allowed_classes' => false]`.\n lineGuard: /[\"']?allowed_classes[\"']?\\s*=>\\s*(?:false|\\[)/,\n needsContext: true,\n },\n {\n id: 'php-unescaped-output',\n title: 'request data echoed without escaping',\n consequence:\n 'The value is written into the response verbatim, so markup in it becomes markup in the page — script that runs with the victim’s session.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['php'],\n pattern:\n /\\b(?:echo|print)\\s+[^;\\n]*\\$_(?:GET|POST|REQUEST|COOKIE|SERVER)\\b|<\\?=\\s*\\$_(?:GET|POST|REQUEST|COOKIE)\\b/,\n },\n {\n id: 'php-request-path-traversal',\n title: 'file path taken from the request',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory, and the process reads or writes wherever it lands.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['php'],\n pattern:\n /\\b(?:file_get_contents|file_put_contents|fopen|readfile|unlink|copy|rename|opendir|scandir)\\s*\\(\\s*[^)\\n]*\\$_(?:GET|POST|REQUEST|COOKIE)\\b/,\n lineGuard: /\\bbasename\\s*\\(|\\brealpath\\s*\\(/,\n },\n {\n id: 'php-variable-injection',\n title: 'request data expanded into local variables',\n consequence:\n '`extract` creates a variable per key, so a request can overwrite any local already in scope — including the one a subsequent authorisation check reads.',\n cwe: 'CWE-621',\n severity: 'high',\n languages: ['php'],\n pattern: /\\bextract\\s*\\(\\s*\\$_(?:GET|POST|REQUEST|COOKIE)\\b|\\bimport_request_variables\\s*\\(/,\n guard: false,\n },\n\n // ── Java and Go: classes the other languages already had ─────────────────\n //\n // Command injection, SSRF and path traversal were implemented for JavaScript\n // and, in part, for Go, and never for Java — so the same defect in the same\n // codebase was reported or not depending on which file it lived in. TLS\n // verification, weak hashing and insecure randomness are deliberately absent\n // here: `tls-verification-disabled`, `weak-hash-on-credential` and\n // `insecure-randomness-for-secret` are language-agnostic and already cover\n // both, including Go's `InsecureSkipVerify` and Java's `MessageDigest`.\n {\n id: 'java-runtime-exec-concatenation',\n title: 'Runtime.exec with a concatenated command',\n consequence:\n 'The single-string form of `exec` is split on whitespace and handed to the OS. A value carrying a space becomes extra arguments, and where a shell is invoked, `;` and `$(…)` become extra commands.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['java'],\n // The array form — `exec(new String[]{\"git\", arg})` — passes argv and is\n // the fix, so it is not matched: the `+` has to be inside the string\n // argument for this to fire.\n pattern:\n /\\b(?:Runtime\\s*\\.\\s*getRuntime\\s*\\(\\s*\\)\\s*\\.\\s*exec|ProcessBuilder)\\s*\\(\\s*(?:\"[^\"\\n]*\"\\s*\\+|\\w+\\s*\\+\\s*\")/,\n },\n {\n id: 'java-ssrf-outbound-request',\n title: 'outbound request to a computed URL',\n consequence:\n 'The destination is chosen by the caller, so the request can be aimed at internal services and cloud metadata endpoints that are reachable from this host and from nowhere else.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\bnew\\s+URL\\s*\\(\\s*(?!\\s*\"[a-z]+:\\/\\/[^\"\\n]*\"\\s*\\))[^)\\n]*\\w|\\bHttpRequest\\s*\\.\\s*newBuilder\\s*\\(\\s*\\)\\s*\\.\\s*uri\\s*\\(\\s*URI\\s*\\.\\s*create\\s*\\(\\s*[^\"\\n)]/,\n needsContext: true,\n },\n {\n id: 'java-request-path-traversal',\n title: 'file path built from request data',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory. The process then reads or writes wherever it lands, with its own privileges.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\b(?:new\\s+File|new\\s+FileInputStream|new\\s+FileOutputStream|Paths\\s*\\.\\s*get|Files\\s*\\.\\s*(?:readAllBytes|newInputStream|newOutputStream|copy|delete))\\s*\\([^)\\n]*\\+/,\n // `getCanonicalPath().startsWith(base)` is the check that makes this safe,\n // and it is normally a line or two below the construction.\n guard: /getCanonicalPath|toRealPath|normalize\\s*\\(\\s*\\)|\\bstartsWith\\s*\\(/,\n guardForward: 4,\n needsContext: true,\n },\n {\n id: 'java-broken-cipher',\n inherent: true,\n title: 'broken cipher or ECB mode',\n consequence:\n 'DES, RC2, RC4 and Blowfish are broken or too small to rely on. ECB encrypts identical plaintext blocks to identical ciphertext blocks, so structure in the data survives encryption and is readable straight off the ciphertext.',\n cwe: 'CWE-327',\n severity: 'high',\n languages: ['java'],\n // Bare `\"AES\"` is included: the JCE resolves it to `AES/ECB/PKCS5Padding`,\n // so the default is the mode this rule exists to catch.\n pattern:\n /\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"(?:DES|DESede|RC2|RC4|ARCFOUR|Blowfish)(?:\\/|\")|\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"[^\"\\n]*\\/ECB\\/|\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"AES\"\\s*\\)/,\n guard: false,\n },\n {\n id: 'go-request-path-traversal',\n title: 'file path built from request data',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory, and the handler serves or writes whatever it reaches.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['go'],\n pattern:\n /\\b(?:os\\s*\\.\\s*(?:Open|OpenFile|ReadFile|Create|Remove|WriteFile)|ioutil\\s*\\.\\s*(?:ReadFile|WriteFile)|http\\s*\\.\\s*ServeFile)\\s*\\([^)\\n]*(?:r\\s*\\.\\s*URL|FormValue|Query\\s*\\(\\s*\\)\\s*\\.\\s*Get|mux\\s*\\.\\s*Vars|\\bfilepath\\s*\\.\\s*Join\\s*\\([^)\\n]*\\w)/,\n // `filepath.Clean` alone does not bound the result to a directory, so it is\n // not a guard here — the containment check is.\n guard: /\\bstrings\\s*\\.\\s*HasPrefix\\s*\\(|\\bfilepath\\s*\\.\\s*Rel\\s*\\(|\\bfs\\s*\\.\\s*ValidPath\\s*\\(|\\bhttp\\s*\\.\\s*Dir\\b/,\n guardBack: 5,\n guardForward: 3,\n needsContext: true,\n },\n {\n id: 'go-template-escaping-bypass',\n title: 'value marked as pre-escaped HTML',\n consequence:\n '`template.HTML` tells `html/template` the value is already safe, which switches off the contextual escaping that makes the package worth using. Markup in the value reaches the page intact.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['go'],\n // A conversion of a *variable*. `template.HTML(\"<br>\")` on a literal is a\n // constant the author wrote and is not a finding.\n pattern: /\\btemplate\\s*\\.\\s*(?:HTML|JS|CSS|HTMLAttr|URL|Srcset)\\s*\\(\\s*(?!\\s*[`\"])/,\n needsContext: true,\n },\n];\n\n/**\n * Classes deliberately not implemented, and why.\n *\n * Recorded in code rather than in a document because the reason is a design\n * constraint, not a backlog item: each of these needs reasoning this scanner\n * does not do, and the line-oriented approximation of each one flags ordinary\n * software. A missing detection is a known number. A rule that fires on every\n * session read is a scanner nobody runs twice.\n */\nexport const KNOWN_GAPS: readonly { cwe: string; name: string; why: string }[] = [\n {\n cwe: 'CWE-352',\n name: 'Missing CSRF token',\n why: 'Requires knowing that a handler is state-changing and that no token check dominates the mutation. Line-locally, the vulnerable and the guarded handler are the same code.',\n },\n {\n cwe: 'CWE-362',\n name: 'Check-then-use race (TOCTOU)',\n why: 'Requires pairing a check with a later use of the same path across statements. A rule matching either half alone flags every `os.path.exists`.',\n },\n {\n cwe: 'CWE-190',\n name: 'Integer overflow / unchecked narrowing',\n why: 'Requires range reasoning about the operands. Flagging arithmetic on a request value would flag arithmetic.',\n },\n {\n cwe: 'CWE-1321',\n name: 'Prototype pollution via generic dynamic assignment',\n why: '`target[key] = source[key]` is both the vulnerable merge and the guarded one; only a denylist several lines away distinguishes them. The explicit `__proto__` shapes are covered.',\n },\n];\n\nexport interface MatchContext {\n /** All lines of the file, 0-indexed. */\n lines: readonly string[];\n /** 0-indexed position of the line being tested. */\n index: number;\n language: ScanLanguage;\n /**\n * Indexes inside a multi-line string or block comment, from `proseLines`.\n * Treated exactly like comment lines: not scanned, not guard evidence.\n */\n prose?: ReadonlySet<number>;\n}\n\nconst COMMENT_PREFIX = /^\\s*(?:\\/\\/|\\/\\*|\\*|#|--|<!--)/;\n\n/**\n * A line that introduces a name rather than doing something with it.\n *\n * Excluded from guard windows because a *name* is not evidence. The corpus\n * contains `def sanitize_path_vulnerable(path):` directly above three\n * catastrophic-backtracking regexes: reading that signature as proof of\n * sanitisation suppressed all three. Naming a function `sanitize` does not\n * sanitise anything, and neither does calling one `validate` or `escape`.\n */\nconst DEFINITION_PREFIX =\n /^\\s*(?:(?:export|public|private|protected|static|final|async|abstract)\\s+)*(?:def|function|func|class|module|interface|struct|impl|fn|sub)\\b/;\n\n/**\n * Comment lines are documentation, not code.\n *\n * Excluded from guard windows for a reason found the hard way: the testbed's\n * vulnerable cases carry comments like \"No `__proto__` guard\" and \"without\n * allow-list validation\". Reading those as evidence of a guard suppresses\n * exactly the findings the corpus exists to measure.\n */\nexport function isComment(line: string): boolean {\n return COMMENT_PREFIX.test(line);\n}\n\n/**\n * Line indexes belonging to multi-line strings and block comments.\n *\n * Python module docstrings are the case that forced this. Every file in the\n * testbed opens with a `\"\"\"…\"\"\"` header describing the vulnerability it\n * contains — `pickle.loads`, `(a+)+`, `autoescape=False` — and scanning that\n * prose produces findings *about the documentation*, reported at line 9 of a\n * file whose code starts at line 18. They are unattributable by construction,\n * and they are the scanner reading its own description back to itself.\n */\nexport function proseLines(lines: readonly string[]): Set<number> {\n const inside = new Set<number>();\n let delimiter: string | null = null;\n\n lines.forEach((line, index) => {\n if (delimiter) {\n inside.add(index);\n if (line.includes(delimiter)) delimiter = null;\n return;\n }\n for (const candidate of ['\"\"\"', \"'''\"]) {\n const start = line.indexOf(candidate);\n if (start === -1) continue;\n // A docstring opened and closed on one line encloses nothing.\n if (line.indexOf(candidate, start + candidate.length) !== -1) return;\n delimiter = candidate;\n inside.add(index);\n return;\n }\n });\n\n return inside;\n}\n\nfunction skippable(line: string, index: number, prose?: ReadonlySet<number>): boolean {\n return isComment(line) || DEFINITION_PREFIX.test(line) || (prose?.has(index) ?? false);\n}\n\nfunction windowText(\n lines: readonly string[],\n index: number,\n back: number,\n forward: number,\n prose?: ReadonlySet<number>,\n): string {\n const from = Math.max(0, index - back);\n const to = Math.min(lines.length - 1, index + forward);\n const collected: string[] = [];\n for (let i = from; i <= to; i += 1) {\n const line = lines[i] ?? '';\n if (i !== index && skippable(line, i, prose)) continue;\n collected.push(line);\n }\n return collected.join('\\n');\n}\n\n/**\n * Whole-file text, memoised on the `lines` array it came from.\n *\n * `fileRequires` asks a question no window can answer, but joining the file on\n * every line of every rule would make scanning quadratic in file length. The\n * caller already reuses one `lines` array for the whole file, so keying on its\n * identity gives one join per file. A `WeakMap` keeps nothing alive after the\n * file is done with.\n */\nconst FILE_TEXT = new WeakMap<readonly string[], string>();\n\nfunction fileTextOf(lines: readonly string[]): string {\n let text = FILE_TEXT.get(lines);\n if (text === undefined) {\n text = lines.join('\\n');\n FILE_TEXT.set(lines, text);\n }\n return text;\n}\n\nexport interface RuleMatch {\n rule: CodeRule;\n confidence: Confidence;\n severity: Severity;\n}\n\n/**\n * Test one rule against one line.\n *\n * Returns `null` when the rule does not apply, does not match, is guarded, or\n * needs context it cannot see.\n */\n/**\n * Blank out single-quoted spans before looking for untrusted input.\n *\n * The shell performs no expansion inside single quotes, so a `$1` there is the\n * two characters `$1` and never a positional parameter. Without this, an awk\n * or sed program written inline — `gawk -F '=' '{print $2}'` — reads as\n * attacker-controlled input.\n *\n * That was not theoretical. In `ralyodio/debtap` it escalated one `curl -k`\n * line to `contextual`, and the ±6-line window carried the escalation to four\n * neighbouring findings, so the same defect reported `high` on lines 103–111\n * and `medium` on 113, 120 and 128 — decided entirely by distance from an awk\n * one-liner. A `--fail-on high` gate would have caught five of eight identical\n * problems.\n */\nfunction withoutSingleQuoted(text: string): string {\n return text.replace(/'[^'\\n]*'/g, \"''\");\n}\n\nexport function evaluateRule(rule: CodeRule, ctx: MatchContext): RuleMatch | null {\n if (rule.languages && !rule.languages.includes(ctx.language)) return null;\n\n const line = ctx.lines[ctx.index] ?? '';\n if (isComment(line) || ctx.prose?.has(ctx.index)) return null;\n if (!rule.pattern.test(line)) return null;\n\n // Before any window work: a rule whose file-level precondition fails does not\n // apply to this file at all.\n if (rule.fileRequires && !rule.fileRequires.test(fileTextOf(ctx.lines))) return null;\n\n const back = rule.guardBack ?? 8;\n const forward = rule.guardForward ?? 0;\n const context = windowText(ctx.lines, ctx.index, back, forward, ctx.prose);\n\n if (rule.requires && !rule.requires.test(context)) return null;\n\n if (rule.lineGuard?.test(line)) return null;\n\n const guard = rule.guard === undefined ? GENERIC_GUARD : rule.guard;\n if (guard && (guard.test(line) || guard.test(context))) return null;\n\n const untrusted = untrustedPatternFor(ctx.language);\n const probeLine = ctx.language === 'shell' ? withoutSingleQuoted(line) : line;\n const probeContext = ctx.language === 'shell' ? withoutSingleQuoted(context) : context;\n const contextual = untrusted.test(probeLine) || untrusted.test(probeContext);\n if (rule.needsContext && !contextual) return null;\n\n // `inherent` short-circuits the whole context question. See the field's\n // documentation: for these rules the construct is the defect, so nearby\n // input cannot make it worse and its absence cannot make it better.\n const confidence: Confidence = rule.inherent\n ? 'evidence'\n : contextual\n ? 'contextual'\n : 'pattern';\n return { rule, confidence, severity: severityFor(rule.severity, confidence) };\n}\n","/**\n * Dependency-manifest rules — typosquats, dependency confusion, and\n * install-time lifecycle scripts.\n *\n * This is the one detector here that does not need a vulnerability to exist\n * yet. `event-stream` (2018), `ua-parser-js` (2021) and `node-ipc` (2022) were\n * all advisory-clean at the moment they were installed; the advisory gets\n * written *after* somebody notices. What they shared was a name you would\n * misread and a lifecycle script that ran with the installing user's\n * privileges. Both are visible in the manifest, before anything is fetched.\n */\n\nimport type { Severity } from './types';\n\nexport interface ManifestFinding {\n ruleId: string;\n title: string;\n line: number;\n severity: Severity;\n cwe: string;\n message: string;\n consequence: string;\n excerpt: string;\n}\n\n/**\n * Popular package names, by ecosystem.\n *\n * Not a registry mirror and not trying to be. It is the set of names worth\n * *impersonating* — a typosquat only pays off against a package people install\n * without looking. A longer list would not find more attacks; it would find\n * more legitimate packages that happen to sit one edit from something famous.\n */\nconst POPULAR_NPM = [\n 'react', 'react-dom', 'lodash', 'express', 'axios', 'chalk', 'commander', 'debug',\n 'moment', 'dayjs', 'uuid', 'dotenv', 'typescript', 'webpack', 'vite', 'rollup',\n 'eslint', 'prettier', 'jest', 'vitest', 'mocha', 'chai', 'sinon', 'request',\n 'node-fetch', 'cross-env', 'rimraf', 'glob', 'minimist', 'yargs', 'inquirer',\n 'colors', 'ora', 'semver', 'ws', 'socket.io', 'mongoose', 'sequelize', 'knex',\n 'pg', 'mysql', 'mysql2', 'redis', 'ioredis', 'jsonwebtoken', 'bcrypt', 'passport',\n 'cors', 'helmet', 'morgan', 'body-parser', 'multer', 'nodemailer', 'puppeteer',\n 'playwright', 'cheerio', 'sharp', 'canvas', 'esbuild', 'babel', 'postcss',\n 'tailwindcss', 'next', 'nuxt', 'vue', 'svelte', 'angular', 'rxjs', 'zod',\n];\n\nconst POPULAR_PYPI = [\n 'requests', 'urllib3', 'numpy', 'pandas', 'scipy', 'flask', 'django', 'fastapi',\n 'sqlalchemy', 'pydantic', 'click', 'jinja2', 'pyyaml', 'boto3', 'botocore',\n 'setuptools', 'wheel', 'pip', 'six', 'certifi', 'idna', 'chardet', 'attrs',\n 'python-dateutil', 'pytz', 'pytest', 'tox', 'black', 'flake8', 'mypy', 'isort',\n 'beautifulsoup4', 'lxml', 'pillow', 'matplotlib', 'seaborn', 'scikit-learn',\n 'tensorflow', 'torch', 'transformers', 'openai', 'anthropic', 'httpx', 'aiohttp',\n 'celery', 'redis', 'psycopg2', 'pymongo', 'cryptography', 'paramiko', 'colorama',\n];\n\n/**\n * Names that read as belonging to a private registry.\n *\n * A manifest that asks a public index for a package whose name announces it is\n * internal is the dependency-confusion setup: whoever registers the name\n * publicly first wins, and the build takes their copy.\n */\nconst INTERNAL_MARKER = /(?:^|[-_/@])(?:internal|private|corp|intranet|inhouse|confidential)(?:$|[-_/])/i;\n\n/** Strip the separators a squatter varies but a reader does not notice. */\nfunction normalizeName(name: string): string {\n return name.toLowerCase().replace(/^@/, '').replace(/[-_.\\s]/g, '');\n}\n\n/**\n * Damerau-Levenshtein distance, capped.\n *\n * Damerau rather than plain Levenshtein because the single most common\n * typosquat is a transposition — `lodahs` for `lodash`, `reqeust` for\n * `request`. Levenshtein scores those as 2, the same as two unrelated edits,\n * which puts them below any threshold tight enough to be useful.\n */\nexport function editDistance(a: string, b: string, cap = 3): number {\n if (a === b) return 0;\n if (Math.abs(a.length - b.length) > cap) return cap + 1;\n\n const rows: number[][] = [];\n for (let i = 0; i <= a.length; i += 1) {\n rows.push(new Array<number>(b.length + 1).fill(0));\n rows[i]![0] = i;\n }\n for (let j = 0; j <= b.length; j += 1) rows[0]![j] = j;\n\n for (let i = 1; i <= a.length; i += 1) {\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let best = Math.min(\n rows[i - 1]![j]! + 1,\n rows[i]![j - 1]! + 1,\n rows[i - 1]![j - 1]! + cost,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, rows[i - 2]![j - 2]! + 1);\n }\n rows[i]![j] = best;\n }\n }\n return rows[a.length]![b.length]!;\n}\n\nexport interface SquatVerdict {\n impersonates: string;\n /** `separator` when only punctuation differs, `edit` when a character does. */\n kind: 'separator' | 'edit';\n}\n\n/**\n * Whether `name` looks like an attempt to be mistaken for a popular package.\n *\n * Exact matches return null first, always. The check that follows is\n * deliberately asymmetric: a name is suspicious for being *close to* a popular\n * package, never for being popular itself.\n */\nexport function detectTyposquat(name: string, ecosystem: 'npm' | 'pypi'): SquatVerdict | null {\n const popular = ecosystem === 'npm' ? POPULAR_NPM : POPULAR_PYPI;\n const lower = name.toLowerCase();\n\n // A scoped name is left alone, scope and all.\n //\n // Discarding the scope before comparing was this rule's largest source of\n // false positives, and it fired on some of the most widely installed packages\n // there are: `@babel/core`, `@angular/core`, `@nestjs/core` and\n // `@capacitor/core` all reduce to `core`, which sits one edit from `cors`.\n //\n // Scopes are owned. Publishing `@babel/anything` requires control of the\n // `@babel` scope, so a squat cannot be planted inside a legitimate one, and\n // nobody typing `npm i cors` arrives at `@capacitor/core` by accident. The\n // misreading this rule exists to catch does not cross the scope boundary, so\n // a name that has one is not a candidate.\n //\n // The scoped attack that *is* real is a lookalike scope — `@babeljs/core` for\n // `@babel/core`. Catching it means comparing scopes against a list of popular\n // scopes, which is a different check than this one rather than a variation on\n // it. Stripping the scope never performed that check; it only compared the\n // part after the slash, so nothing is lost here.\n if (/^@[^/]+\\//.test(lower)) return null;\n\n if (popular.includes(lower)) return null;\n if (lower.length < 4) return null;\n\n const normalized = normalizeName(lower);\n for (const candidate of popular) {\n const candidateNormalized = normalizeName(candidate);\n // `urllib-3` and `pythondateutil` normalise onto their targets exactly.\n // Nothing legitimate reaches a popular package's spelling by deleting or\n // inserting punctuation.\n if (normalized === candidateNormalized) return { impersonates: candidate, kind: 'separator' };\n if (editDistance(normalized, candidateNormalized, 1) === 1) {\n return { impersonates: candidate, kind: 'edit' };\n }\n }\n return null;\n}\n\nconst LIFECYCLE_SCRIPTS = ['preinstall', 'install', 'postinstall', 'prepare', 'prepublish'];\n\n/**\n * Scan a `package.json`.\n *\n * Text-oriented rather than object-oriented so every finding can carry the\n * line it came from. A finding an operator cannot navigate to is a finding\n * they will not act on.\n */\nexport function scanPackageJson(text: string): ManifestFinding[] {\n const findings: ManifestFinding[] = [];\n const lines = text.split('\\n');\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return findings;\n }\n\n const lineOf = (needle: string): number => {\n const index = lines.findIndex((line) => line.includes(`\"${needle}\"`));\n return index === -1 ? 1 : index + 1;\n };\n\n const depBuckets = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];\n for (const bucket of depBuckets) {\n const deps = parsed[bucket];\n if (!deps || typeof deps !== 'object') continue;\n for (const name of Object.keys(deps as Record<string, unknown>)) {\n const line = lineOf(name);\n\n if (INTERNAL_MARKER.test(name)) {\n findings.push({\n ruleId: 'manifest-dependency-confusion',\n title: 'internal-looking package resolved from a public registry',\n line,\n severity: 'critical',\n cwe: 'CWE-1357',\n message: `\"${name}\" names itself as internal but carries no registry pin`,\n consequence:\n 'Whoever registers this name publicly first wins the resolution, and their code runs in your build.',\n excerpt: (lines[line - 1] ?? '').trim(),\n });\n continue;\n }\n\n const squat = detectTyposquat(name, 'npm');\n if (squat) {\n findings.push({\n ruleId: 'manifest-typosquat',\n title: 'dependency name close to a popular package',\n line,\n severity: 'high',\n cwe: 'CWE-1357',\n message:\n squat.kind === 'separator'\n ? `\"${name}\" differs from \"${squat.impersonates}\" only in punctuation`\n : `\"${name}\" is one edit from \"${squat.impersonates}\"`,\n consequence:\n 'A reviewer scanning a diff reads the name they expected. The package that installs is the one that was written.',\n excerpt: (lines[line - 1] ?? '').trim(),\n });\n }\n }\n }\n\n const scripts = parsed.scripts;\n if (scripts && typeof scripts === 'object') {\n for (const [name, body] of Object.entries(scripts as Record<string, unknown>)) {\n if (!LIFECYCLE_SCRIPTS.includes(name)) continue;\n findings.push({\n ruleId: 'manifest-install-lifecycle-script',\n title: 'install-time lifecycle script',\n line: lineOf(name),\n severity: 'medium',\n cwe: 'CWE-506',\n message: `\"${name}\" runs automatically on install: ${String(body).slice(0, 120)}`,\n consequence:\n 'Lifecycle scripts run with the installing user’s privileges and network access, before any code is reviewed. It is the execution vector every notable npm compromise has used.',\n excerpt: (lines[lineOf(name) - 1] ?? '').trim(),\n });\n }\n }\n\n return findings;\n}\n\n/** Scan a `requirements.txt`. Same checks, different grammar. */\nexport function scanRequirementsTxt(text: string): ManifestFinding[] {\n const findings: ManifestFinding[] = [];\n const lines = text.split('\\n');\n\n lines.forEach((raw, index) => {\n const line = raw.trim();\n if (!line || line.startsWith('#') || line.startsWith('-')) return;\n\n const match = /^([A-Za-z0-9_.-]+)\\s*(?:[=<>!~]=|@|$)/.exec(line);\n const name = match?.[1];\n if (!name) return;\n\n if (INTERNAL_MARKER.test(name)) {\n findings.push({\n ruleId: 'manifest-dependency-confusion',\n title: 'internal-looking package resolved from a public index',\n line: index + 1,\n severity: 'critical',\n cwe: 'CWE-1357',\n message: `\"${name}\" names itself as internal but carries no index pin`,\n consequence:\n 'pip resolves the highest version across every configured index, so a public package of the same name shadows the private one.',\n excerpt: line,\n });\n return;\n }\n\n const squat = detectTyposquat(name, 'pypi');\n if (squat) {\n findings.push({\n ruleId: 'manifest-typosquat',\n title: 'dependency name close to a popular package',\n line: index + 1,\n severity: 'high',\n cwe: 'CWE-1357',\n message:\n squat.kind === 'separator'\n ? `\"${name}\" differs from \"${squat.impersonates}\" only in punctuation`\n : `\"${name}\" is one edit from \"${squat.impersonates}\"`,\n consequence:\n 'A reviewer scanning a diff reads the name they expected. The package that installs is the one that was written.',\n excerpt: line,\n });\n }\n });\n\n return findings;\n}\n","/**\n * Credential-shape rules for `threatcrush scan`.\n *\n * These are the rules ThreatCrush already scored 0.0% false positives on\n * against the public testbed's control group, so the bar for changing one is\n * high: a secret rule earns its place by matching material that is a\n * credential, not by matching material that looks vaguely random.\n *\n * The distinction that keeps the false-positive rate at zero is *shape with a\n * vendor prefix*. `AKIA…`, `ghp_…`, `xoxb-…`, `sk_live_…` are issued formats —\n * nothing else produces them. Entropy alone is not a rule here, because\n * entropy alone flags every UUID, hash and minified bundle in the tree.\n *\n * Two lines in the testbed corpus are the reason for that discipline. Both\n * live in the same `.env` file as five real credentials:\n *\n * AWS_ROLE_ARN=arn:aws:iam::123456789012:role/app-runtime\n * DATABASE_URL_SSM_PARAMETER=/prod/app/database-url\n *\n * An identifier and a lookup path. Both sit under secret-shaped variable\n * names, and neither is a credential. A rule keyed on the variable name would\n * flag both.\n */\n\nimport type { Severity } from './types';\n\nexport interface SecretRule {\n id: string;\n /** Vendor-facing name, e.g. \"AWS Access Key\". */\n name: string;\n pattern: RegExp;\n severity: Severity;\n cwe: string;\n /** What an attacker does with it. */\n consequence: string;\n}\n\nexport const SECRET_RULES: readonly SecretRule[] = [\n {\n id: 'secret-aws-access-key',\n name: 'AWS Access Key',\n pattern: /\\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Paired with a secret key, grants the API access of whatever IAM principal issued it.',\n },\n {\n id: 'secret-aws-secret-key',\n name: 'AWS Secret Access Key',\n pattern:\n /(?:aws_secret_access_key|AWS_SECRET(?:_ACCESS_KEY)?)\\s*[=:]\\s*['\"]?([A-Za-z0-9/+=]{40})['\"]?/i,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'The other half of an AWS credential pair; on its own it is still the hard half to guess.',\n },\n {\n id: 'secret-github-token',\n name: 'GitHub Token',\n pattern: /\\b(?:ghp_[A-Za-z0-9]{36}|gho_[A-Za-z0-9]{36}|ghu_[A-Za-z0-9]{36}|ghs_[A-Za-z0-9]{36}|ghr_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,})\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Repository read or write as the issuing account, including the ability to push workflow changes.',\n },\n {\n id: 'secret-npm-token',\n name: 'npm Token',\n pattern: /\\bnpm_[A-Za-z0-9]{36}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Publish rights to every package the account owns — a supply-chain compromise in one command.',\n },\n {\n id: 'secret-private-key',\n name: 'Private Key',\n pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Key material, committed. Rotation is the only remediation.',\n },\n {\n id: 'secret-slack-token',\n name: 'Slack Token',\n pattern: /\\bxox[bpoasr]-[A-Za-z0-9-]{10,}/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Read and post access to the workspace as the installing app.',\n },\n {\n id: 'secret-slack-webhook',\n name: 'Slack Webhook URL',\n pattern: /https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9_+\\/-]{6,}/,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'The URL *is* the credential — anyone holding it can post to that channel.',\n },\n {\n id: 'secret-stripe-key',\n name: 'Stripe Key',\n pattern: /\\b(?:sk_live_|rk_live_|sk_test_|rk_test_)[A-Za-z0-9]{20,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Charge, refund and customer-data access against the account.',\n },\n {\n id: 'secret-sendgrid-key',\n name: 'SendGrid API Key',\n pattern: /\\bSG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Send mail as the domain — the credential behind most convincing phishing from a real sender.',\n },\n {\n id: 'secret-google-api-key',\n name: 'Google API Key',\n pattern: /\\bAIza[0-9A-Za-z_-]{35}\\b/,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Quota theft at minimum; API access to whatever the key was scoped to at worst.',\n },\n {\n id: 'secret-openai-key',\n name: 'OpenAI API Key',\n pattern: /\\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Billed inference against the owner’s account, with no per-key spend limit by default.',\n },\n {\n id: 'secret-anthropic-key',\n name: 'Anthropic API Key',\n pattern: /\\bsk-ant-(?:api\\d{2}-)?[A-Za-z0-9_-]{32,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Billed inference against the owner’s account.',\n },\n {\n id: 'secret-database-url',\n name: 'Database URL with credentials',\n // Requires a credential segment before the `@` — `postgres://localhost/db`\n // is a hostname, not a secret.\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|amqp|clickhouse):\\/\\/[^\\s'\"@\\/]*:[^\\s'\"@\\/]*@[^\\s'\"]+/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Direct database access, usually bypassing every application-level authorisation check.',\n },\n {\n id: 'secret-jwt',\n name: 'JSON Web Token',\n pattern: /\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_.+/=-]*/,\n severity: 'medium',\n cwe: 'CWE-798',\n consequence: 'Session or service identity until it expires — and committed tokens are usually long-lived.',\n },\n {\n id: 'secret-generic-api-key',\n name: 'Generic API Key',\n // Quoted assignment only. An unquoted value in a `.env` is covered by the\n // vendor-prefixed rules above; matching it here is what starts flagging\n // ARNs and parameter-store paths.\n pattern: /(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token)\\s*[=:]\\s*['\"]([A-Za-z0-9\\-_.]{20,})['\"]/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Whatever the third-party service lets the key do, for as long as it stays valid.',\n },\n {\n id: 'secret-generic-credential',\n name: 'Hardcoded Credential',\n pattern: /(?:secret|password|passwd|pwd|token)\\s*[=:]\\s*['\"]([^'\"\\s]{8,})['\"]/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'A password in source is a password in every clone, fork and CI cache of that source.',\n },\n {\n id: 'secret-hex-token',\n name: 'High-entropy Hex Token',\n pattern: /(?:token|key|secret|auth|signing)\\w*\\s*[=:]\\s*['\"]?([0-9a-f]{32,})['\"]?/i,\n severity: 'medium',\n cwe: 'CWE-798',\n consequence: 'Signing secrets and session keys are usually hex; a leaked one forges anything they sign.',\n },\n];\n\n/**\n * Values that satisfy a credential shape but are not credentials.\n *\n * Kept deliberately short. Every entry is a documented, publicly-published\n * placeholder — not a guess that something \"looks like a test value\". A\n * generous allow-list here is how a scanner talks itself out of a real finding.\n */\nconst KNOWN_PLACEHOLDERS = [\n // Deliberately NOT here: AWS's published documentation key/secret pair\n // (`AKIAIOSFODNN7EXAMPLE`, `wJalrXUtnFEMI/…`). GitHub allow-lists them, and\n // the argument for following suit is that they authenticate nothing. The\n // argument against is stronger: they appear in a repository because someone\n // pasted a credentials template and left it there, and the remediation —\n // move this to the secret manager — is identical to the one for a live key.\n // Exempting them means the scanner goes quiet on the file most likely to\n // acquire a real key next.\n /\\bEXAMPLE_?KEY\\b/i,\n /\\bYOUR_[A-Z_]*(?:KEY|TOKEN|SECRET|PASSWORD)\\b/,\n /\\b(?:xxx+|X{4,}|\\*{4,}|<[a-z-]+>)\\b/,\n /\\bchangeme\\b/i,\n];\n\n/**\n * Whether the matched text is a documented placeholder rather than material.\n *\n * Note what this does *not* do: it does not exempt a value for being all\n * zeros, all A's, or otherwise \"obviously fake\". Those shapes are exactly what\n * the testbed's fixtures use, deliberately, and a scanner that skips them\n * scores zero on a corpus of real credential formats. Only values a vendor has\n * published as examples are exempt.\n */\nexport function isKnownPlaceholder(text: string): boolean {\n return KNOWN_PLACEHOLDERS.some((pattern) => pattern.test(text));\n}\n\n/**\n * Replace anything that looks like credential material with asterisks.\n *\n * Applied to every excerpt on a secret finding before it reaches a terminal, a\n * SARIF file, a CI log or a PR comment. A scanner that prints the secret it\n * found has moved the secret somewhere new, and CI logs are retained and, on\n * public forks, published.\n */\nexport function redactSecret(line: string): string {\n return line.replace(/([A-Za-z0-9+/=_.-]{12,})/g, (match) => {\n if (match.length <= 12) return match;\n return `${match.slice(0, 3)}${'*'.repeat(Math.min(16, match.length - 3))}`;\n });\n}\n\n/** Files whose mere presence is worth reporting, independent of content. */\nexport const SENSITIVE_FILES: readonly { pattern: string; message: string; severity: Severity }[] = [\n { pattern: '.env', message: 'Environment file committed — the usual home of every runtime credential', severity: 'high' },\n { pattern: '.env.local', message: 'Local environment file committed', severity: 'high' },\n { pattern: '.env.production', message: 'Production environment file committed', severity: 'critical' },\n { pattern: 'id_rsa', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: 'id_ed25519', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: 'id_ecdsa', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: '.pem', message: 'PEM certificate or key file committed', severity: 'high' },\n { pattern: '.p12', message: 'PKCS#12 keystore committed', severity: 'high' },\n { pattern: '.pfx', message: 'PKCS#12 keystore committed', severity: 'high' },\n { pattern: '.keystore', message: 'Java keystore committed', severity: 'high' },\n // Deliberately not `.npmrc`. Its presence is normal; only an `_authToken`\n // line in it is a credential, and that is a content match, not a filename\n // match. Reporting the file itself trades a real finding for a chore.\n];\n","/**\n * The scan engine, minus the filesystem: run every rule set over text.\n *\n * Kept free of I/O entirely — no reading, no printing, no exit codes, no\n * SARIF. The command layer decides how to present what this returns, which is\n * what lets the same scan feed a terminal, a SARIF file and a daemon run\n * without three implementations drifting apart.\n *\n * The absence of `node:` imports here is load-bearing, not incidental. This\n * module is the package's default entry point, and the browser surfaces —\n * web, extension, desktop renderer — import it directly. A single\n * `import … from 'node:fs'` anywhere in this file's dependency graph breaks\n * every one of their bundles, so the tree walker lives in `./node/walk.ts`\n * and everything here works on strings that somebody else read.\n */\n\nimport { CODE_RULES, evaluateRule, proseLines } from './code-rules';\nimport { scanPackageJson, scanRequirementsTxt } from './manifest-rules';\nimport { isKnownPlaceholder, redactSecret, SECRET_RULES, SENSITIVE_FILES } from './secret-rules';\nimport type { ScanFinding, ScanLanguage, Severity } from './types';\nimport { severityRank } from './types';\n\n/**\n * `extname` and `basename`, reimplemented in three lines each.\n *\n * Importing them from `node:path` is what would otherwise put this module —\n * and therefore the package's whole default entry point — out of reach of a\n * browser bundle, for two functions that are pure string arithmetic.\n *\n * Semantics match the originals on the inputs that reach them: a leading dot\n * is not an extension, so `.env` has none, and a name with no dot has none\n * either. Only `/` is treated as a separator, which is what the callers pass —\n * repository-relative paths and shebang interpreter paths.\n */\nfunction baseNameOf(path: string): string {\n return path.slice(path.lastIndexOf('/') + 1);\n}\n\nfunction extensionOf(path: string): string {\n const base = baseNameOf(path);\n const dot = base.lastIndexOf('.');\n return dot <= 0 ? '' : base.slice(dot);\n}\n\nexport const SKIP_DIRS = new Set([\n 'node_modules', '.git', '.next', '.nuxt', 'dist', 'build', 'out', '__pycache__',\n '.venv', 'venv', 'vendor', '.terraform', 'coverage', '.cache', '.pnpm-store',\n 'target', '.gradle', '.idea', '.vscode', 'bower_components', '.svelte-kit',\n]);\n\nexport const SCAN_EXTENSIONS = new Set([\n '.ts', '.js', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts',\n '.py', '.rb', '.go', '.java', '.kt', '.scala', '.php', '.rs',\n '.c', '.cc', '.cpp', '.h', '.hpp', '.cs', '.swift',\n '.yml', '.yaml', '.json', '.toml', '.ini', '.cfg', '.conf', '.env',\n '.sh', '.bash', '.zsh', '.tf', '.hcl', '.xml', '.properties', '.gradle',\n '.txt', '.md', '.sql', '.erb', '.ejs', '.vue', '.svelte',\n]);\n\nconst LANGUAGE_BY_EXTENSION: Record<string, ScanLanguage> = {\n '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',\n '.ts': 'typescript', '.tsx': 'typescript', '.mts': 'typescript', '.cts': 'typescript',\n '.vue': 'javascript', '.svelte': 'javascript', '.ejs': 'javascript',\n '.py': 'python',\n '.rb': 'ruby', '.erb': 'ruby',\n '.go': 'go',\n '.java': 'java', '.kt': 'java', '.scala': 'java',\n '.php': 'php',\n '.sh': 'shell', '.bash': 'shell', '.zsh': 'shell',\n '.yml': 'config', '.yaml': 'config', '.json': 'config', '.toml': 'config',\n '.ini': 'config', '.cfg': 'config', '.conf': 'config', '.env': 'config',\n '.tf': 'config', '.hcl': 'config', '.properties': 'config',\n};\n\nexport function languageOf(filename: string): ScanLanguage {\n if (filename.startsWith('.env') || filename.endsWith('.env')) return 'config';\n return LANGUAGE_BY_EXTENSION[extensionOf(filename).toLowerCase()] ?? 'other';\n}\n\n/** Interpreters worth recognising, by the language their scripts are written in. */\nconst LANGUAGE_BY_INTERPRETER: Record<string, ScanLanguage> = {\n sh: 'shell', bash: 'shell', zsh: 'shell', dash: 'shell', ksh: 'shell', ash: 'shell',\n python: 'python', python2: 'python', python3: 'python',\n ruby: 'ruby',\n node: 'javascript', nodejs: 'javascript', deno: 'javascript', bun: 'javascript',\n php: 'php',\n};\n\n/**\n * The language a `#!` line declares, or `null` if the line is not a shebang.\n *\n * An executable in a repository root is routinely named for the command it\n * provides rather than the language it is written in — `debtap`, `configure`,\n * `gradlew`. Extension-based detection skips every one of them, which is worst\n * exactly where it matters: a project whose entire source is one extensionless\n * script gets a clean scan because nothing was read.\n *\n * The shebang is the authoritative answer to a question the filename cannot\n * answer, and the kernel already treats it that way.\n */\nexport function languageOfShebang(firstLine: string): ScanLanguage | null {\n const match = /^#!\\s*(\\S+)(?:\\s+(.+?))?\\s*$/.exec(firstLine);\n if (!match) return null;\n\n // `#!/usr/bin/env bash` names the interpreter in the argument, not the path.\n const command = baseNameOf(match[1]!);\n const args = match[2]?.trim().split(/\\s+/) ?? [];\n const splitString = args[0] === '-S' || args[0] === '--split-string';\n const name = command === 'env' ? baseNameOf(args[splitString ? 1 : 0] ?? '') : command;\n\n const exact = LANGUAGE_BY_INTERPRETER[name];\n if (exact) return exact;\n\n // `python3.11` and `bash5` are the same interpreters with a version glued on.\n const stripped = name.replace(/[\\d.]+$/, '');\n return (stripped ? LANGUAGE_BY_INTERPRETER[stripped] : undefined) ?? null;\n}\n\n\n/**\n * Inline suppression, matching the convention `modules/code-scanner` already\n * uses so a repository does not learn two syntaxes for the same idea.\n *\n * // threatcrush-disable-next-line secret-aws-access-key fixture, not a key\n * // threatcrush-disable-line\n *\n * The rule id is optional; without one the whole line is suppressed. This\n * exists because the highest-volume false positive in practice is a scanner's\n * own test fixtures — a file of deliberately-malformed credentials is\n * indistinguishable from a file of leaked ones, and only the author knows\n * which. Suppressions are counted and reported: a quiet scan full of\n * suppressions is not a clean one.\n */\nconst SUPPRESS_NEXT = /threatcrush-disable-next-line(?:\\s+([\\w-]+))?/;\nconst SUPPRESS_LINE = /threatcrush-disable-line(?:\\s+([\\w-]+))?/;\n\nexport interface Suppressions {\n /** line index → set of rule ids, or `*` for every rule. */\n byLine: Map<number, Set<string>>;\n count: number;\n}\n\nexport function collectSuppressions(lines: readonly string[]): Suppressions {\n const byLine = new Map<number, Set<string>>();\n let count = 0;\n\n const add = (index: number, ruleId: string | undefined): void => {\n const existing = byLine.get(index) ?? new Set<string>();\n existing.add(ruleId ?? '*');\n byLine.set(index, existing);\n count += 1;\n };\n\n lines.forEach((line, index) => {\n const next = SUPPRESS_NEXT.exec(line);\n if (next) add(index + 1, next[1]);\n const same = SUPPRESS_LINE.exec(line);\n // `disable-next-line` also matches the `disable-line` substring, so only\n // treat it as a same-line directive when the longer form did not match.\n if (same && !next) add(index, same[1]);\n });\n\n return { byLine, count };\n}\n\nfunction isSuppressed(suppressions: Suppressions, index: number, ruleId: string): boolean {\n const rules = suppressions.byLine.get(index);\n if (!rules) return false;\n return rules.has('*') || rules.has(ruleId);\n}\n\n/**\n * Does this path hold tests or fixtures?\n *\n * Used to soften credential findings, never to hide them. A secret in a test\n * is nearly always a fixture — often a deliberately real-looking one, because\n * the test exists to prove the real path is guarded — but \"nearly always\" is\n * not \"always\", and a genuine key does get pasted into a test. So these are\n * still reported, at a severity that does not block a merge, rather than\n * dropped where nobody would ever see them.\n */\nexport function isTestPath(relativePath: string): boolean {\n const p = relativePath.replace(/\\\\/g, '/');\n return (\n /(?:^|\\/)(?:tests?|__tests__|__mocks__|spec|specs|fixtures?|mocks?|e2e|testdata)\\//i.test(p) ||\n /(?:^|\\/)(?:test|conftest)_[^/]+$/i.test(p) ||\n /[._-](?:test|spec)\\.[a-z]+$/i.test(p) ||\n /_test\\.[a-z]+$/i.test(p)\n );\n}\n\n/** Scan a single file's text. Exposed for tests and for single-file callers. */\nexport function scanText(\n relativePath: string,\n text: string,\n language: ScanLanguage = languageOf(relativePath),\n): ScanFinding[] {\n const findings: ScanFinding[] = [];\n const lines = text.split('\\n');\n const suppressions = collectSuppressions(lines);\n const inTests = isTestPath(relativePath);\n\n // ── Credentials ────────────────────────────────────────────────────────\n lines.forEach((line, index) => {\n for (const rule of SECRET_RULES) {\n const match = rule.pattern.exec(line);\n if (!match) continue;\n if (isKnownPlaceholder(match[0])) continue;\n if (isSuppressed(suppressions, index, rule.id)) continue;\n\n findings.push({\n ruleId: rule.id,\n title: rule.name,\n file: relativePath,\n line: index + 1,\n // Reported but not blocking in tests — see isTestPath.\n severity: inTests ? 'low' : rule.severity,\n // A matched credential format is the finding, not a proxy for one.\n confidence: 'evidence',\n message: inTests\n ? `Possible ${rule.name} detected in a test file — usually a fixture, still worth confirming it is not a live credential`\n : `Possible ${rule.name} detected`,\n consequence: rule.consequence,\n cwe: rule.cwe,\n excerpt: redactSecret(line.trim()).slice(0, 200),\n sensitive: true,\n category: 'secret',\n });\n }\n });\n\n // ── Code-level constructs ──────────────────────────────────────────────\n const prose = proseLines(lines);\n lines.forEach((_line, index) => {\n for (const rule of CODE_RULES) {\n if (isSuppressed(suppressions, index, rule.id)) continue;\n const match = evaluateRule(rule, { lines, index, language, prose });\n if (!match) continue;\n\n findings.push({\n ruleId: rule.id,\n title: rule.title,\n file: relativePath,\n line: index + 1,\n severity: match.severity,\n confidence: match.confidence,\n message: `${rule.title} (${rule.cwe})`,\n consequence: rule.consequence,\n cwe: rule.cwe,\n excerpt: (lines[index] ?? '').trim().slice(0, 200),\n category: 'code',\n });\n }\n });\n\n return findings;\n}\n\nexport function scanManifest(relativePath: string, filename: string, text: string): ScanFinding[] {\n const manifestFindings =\n filename === 'package.json'\n ? scanPackageJson(text)\n : filename === 'requirements.txt'\n ? scanRequirementsTxt(text)\n : [];\n\n return manifestFindings.map((finding) => ({\n ruleId: finding.ruleId,\n title: finding.title,\n file: relativePath,\n line: finding.line,\n severity: finding.severity,\n confidence: 'evidence' as const,\n message: finding.message,\n consequence: finding.consequence,\n cwe: finding.cwe,\n excerpt: finding.excerpt.slice(0, 200),\n category: 'manifest' as const,\n }));\n}\n\n\n\n/** Highest severity present, or null for a clean scan. */\nexport function peakSeverity(findings: readonly ScanFinding[]): Severity | null {\n let peak: Severity | null = null;\n for (const finding of findings) {\n if (!peak || severityRank(finding.severity) > severityRank(peak)) peak = finding.severity;\n }\n return peak;\n}\n\n/** True when any finding is at or above `threshold`. Drives `--fail-on`. */\nexport function meetsFailThreshold(\n findings: readonly ScanFinding[],\n threshold: readonly Severity[],\n): boolean {\n if (threshold.length === 0) return false;\n const floor = Math.min(...threshold.map(severityRank));\n return findings.some((finding) => severityRank(finding.severity) >= floor);\n}\n","/**\n * The filesystem half of the scan engine: walk a tree, read what is scannable,\n * hand the text to the rules.\n *\n * Split from `../text.ts` because this file imports `node:fs` and that one must\n * not. The package's default entry point is consumed by browser bundles, and a\n * single filesystem import anywhere in its graph breaks all of them. Everything\n * that needs a disk lives behind the `./node` entry point instead.\n */\n\nimport {\n closeSync, fstatSync, openSync, readdirSync, readFileSync, readSync, statSync,\n} from 'node:fs';\nimport { basename, dirname, extname, join, relative, sep } from 'node:path';\nimport { SENSITIVE_FILES } from '../secret-rules';\nimport {\n collectSuppressions,\n languageOf,\n languageOfShebang,\n SCAN_EXTENSIONS,\n scanManifest,\n scanText,\n SKIP_DIRS,\n} from '../text';\nimport type { ScanFinding, ScanLanguage } from '../types';\nimport { severityRank } from '../types';\n\nexport interface ScanOptions {\n /** Skip files larger than this. Defaults to 1 MiB. */\n maxFileBytes?: number;\n /** Called once per file actually read, for progress reporting. */\n onFile?: (path: string) => void;\n /** Restrict to these rule categories. Defaults to all. */\n categories?: readonly ScanFinding['category'][];\n}\n\nexport interface ScanReport {\n findings: ScanFinding[];\n filesScanned: number;\n /**\n * How many inline suppressions were honoured. Reported, never hidden: a\n * scan that came back quiet because someone silenced forty rules is a\n * different result from a scan that came back quiet.\n */\n suppressed: number;\n /**\n * Directory that finding paths are relative to. Equal to the target for a\n * directory scan, its parent for a single-file scan. SARIF URI resolution\n * needs this — guessing it from the target is what produces file URIs that\n * resolve to nothing.\n */\n root: string;\n /**\n * Files matched by extension but unreadable. Reported rather than swallowed:\n * a scan that could not read a file has not cleared it, and \"0 findings\"\n * over an unread tree is the failure this scanner exists to avoid.\n */\n unreadable: string[];\n}\n\nexport function scanPath(targetPath: string, options: ScanOptions = {}): ScanReport {\n const maxFileBytes = options.maxFileBytes ?? 1024 * 1024;\n const allowed = options.categories ? new Set(options.categories) : null;\n const findings: ScanFinding[] = [];\n const unreadable: string[] = [];\n let filesScanned = 0;\n let suppressed = 0;\n\n // A file target is not a degenerate directory target. `readdirSync` on a\n // file throws ENOTDIR, which the walker below treats as an unreadable\n // directory — so `threatcrush scan app.js` reported a clean scan of a file\n // it never opened. Resolve the shape first, and walk only what is walkable.\n const rootIsDirectory = (() => {\n try {\n return statSync(targetPath).isDirectory();\n } catch {\n return true;\n }\n })();\n const walkRoot = rootIsDirectory ? targetPath : dirname(targetPath);\n\n const scanFile = (fullPath: string, filename: string): void => {\n const relativePath = toRelative(walkRoot, fullPath);\n const extension = extname(filename).toLowerCase();\n const isManifest = filename === 'package.json' || filename === 'requirements.txt';\n const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith('.env');\n\n // A file with no extension gets one question asked of it before being\n // dismissed: does it start with a shebang? Executables are habitually named\n // for what they do rather than what they are written in, and skipping them\n // silently is how a repository whose only source file is `debtap` scans\n // clean. Files that carry an unrecognised extension are still skipped —\n // `.png` is not a script, and sniffing every one of them would mean reading\n // the whole tree.\n const mayDeclareInterpreter = !scannable && !isManifest && extension === '';\n\n if (!scannable && !isManifest && !mayDeclareInterpreter) {\n recordSensitiveFile(filename, relativePath, findings, []);\n return;\n }\n\n // Size-check and read through one descriptor.\n //\n // `statSync(path)` followed by `readFileSync(path)` is check-then-use: the\n // path can be replaced between the two calls, so the size that was checked\n // is not necessarily the size that gets read. Opening once and calling\n // `fstatSync` on the descriptor removes the window — the descriptor refers\n // to the same inode for both operations, whatever happens to the name.\n //\n // A scanner walking directories it does not control is exactly where this\n // matters, and CWE-362 is a class this tool reports on. Worth getting\n // right in its own walker.\n let text: string;\n let handle: number;\n let declared: ScanLanguage | null = null;\n try {\n handle = openSync(fullPath, 'r');\n } catch {\n unreadable.push(relativePath);\n return;\n }\n\n try {\n if (fstatSync(handle).size > maxFileBytes) return;\n\n // Sniff the shebang from a short prefix rather than the whole file, so an\n // extensionless blob — a checked-in binary, a data file — costs one small\n // read instead of a megabyte decoded as UTF-8 and thrown away.\n if (mayDeclareInterpreter) {\n const prefix = Buffer.alloc(128);\n const read = readSync(handle, prefix, 0, prefix.length, 0);\n declared = languageOfShebang(prefix.subarray(0, read).toString('utf-8').split('\\n', 1)[0] ?? '');\n if (!declared) return;\n }\n\n text = readFileSync(handle, 'utf-8');\n } catch {\n unreadable.push(relativePath);\n return;\n } finally {\n try {\n closeSync(handle);\n } catch {\n /* the descriptor is going away regardless */\n }\n }\n\n filesScanned += 1;\n options.onFile?.(relativePath);\n suppressed += collectSuppressions(text.split('\\n')).count;\n\n const fileFindings = [\n ...scanText(relativePath, text, declared ?? languageOf(filename)),\n ...(isManifest ? scanManifest(relativePath, filename, text) : []),\n ];\n\n findings.push(...fileFindings);\n recordSensitiveFile(filename, relativePath, findings, fileFindings);\n };\n\n const walk = (currentPath: string): void => {\n let entries;\n try {\n entries = readdirSync(currentPath, { withFileTypes: true });\n } catch {\n unreadable.push(toRelative(walkRoot, currentPath));\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue;\n walk(fullPath);\n continue;\n }\n if (!entry.isFile()) continue;\n\n scanFile(fullPath, entry.name);\n }\n };\n\n if (rootIsDirectory) {\n walk(targetPath);\n } else {\n scanFile(targetPath, basename(targetPath));\n }\n\n const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;\n filtered.sort(\n (a, b) =>\n severityRank(b.severity) - severityRank(a.severity) ||\n a.file.localeCompare(b.file) ||\n a.line - b.line,\n );\n\n return { findings: filtered, filesScanned, unreadable, suppressed, root: walkRoot };\n}\n\n/**\n * Report a file whose *name* is the finding — but only when its contents\n * produced nothing.\n *\n * A `.env` full of detected credentials does not also need \"this is a .env\n * file\" stapled to line 1. The filename finding exists for the case the\n * content rules cannot cover: an env file whose values are shapes no vendor\n * rule matches, which is still an env file that should not be committed.\n */\nfunction recordSensitiveFile(\n filename: string,\n relativePath: string,\n sink: ScanFinding[],\n fileFindings: readonly ScanFinding[],\n): void {\n if (fileFindings.length > 0) return;\n\n for (const sensitive of SENSITIVE_FILES) {\n const matches = filename === sensitive.pattern || filename.endsWith(sensitive.pattern);\n if (!matches) continue;\n sink.push({\n ruleId: 'sensitive-file-committed',\n title: 'Sensitive file',\n file: relativePath,\n line: 1,\n severity: sensitive.severity,\n confidence: 'evidence',\n message: sensitive.message,\n consequence: 'Anything in this file is in every clone, fork and CI cache of the repository.',\n cwe: 'CWE-538',\n excerpt: '',\n sensitive: true,\n category: 'file',\n });\n return;\n }\n}\n\nfunction toRelative(base: string, target: string): string {\n const rel = relative(base, target);\n return (rel === '' ? target : rel).split(sep).join('/');\n}\n","/**\n * Dependency advisory lookup against OSV.dev (PRD 06).\n *\n * Split out of `commands/scan.ts` unchanged in behaviour. It is the only part\n * of a scan that makes network calls, and that difference is worth a module\n * boundary: the pattern rules are deterministic and fast, this is neither, and\n * CI wants to choose. `runScan` keeps calling it (the daemon has always\n * included advisories); the CLI asks for it with `--deps`.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { ScanFinding, Severity } from '../types';\n\ninterface OsvVulnerability {\n id: string;\n summary?: string;\n details?: string;\n severity?: Array<{ type: string; score: string }>;\n}\n\nconst LOCKFILES: readonly { file: string; ecosystem: string }[] = [\n { file: 'package-lock.json', ecosystem: 'npm' },\n { file: 'pnpm-lock.yaml', ecosystem: 'npm' },\n { file: 'yarn.lock', ecosystem: 'npm' },\n { file: 'requirements.txt', ecosystem: 'PyPI' },\n { file: 'Pipfile.lock', ecosystem: 'PyPI' },\n];\n\n/** Cap per lockfile, so a first run on a neglected tree summarises rather than floods OSV. */\nconst MAX_DEPS_PER_LOCKFILE = 50;\n\nexport async function scanDependencies(targetPath: string): Promise<ScanFinding[]> {\n const findings: ScanFinding[] = [];\n\n for (const { file, ecosystem } of LOCKFILES) {\n const lockPath = join(targetPath, file);\n if (!existsSync(lockPath)) continue;\n\n let deps: Array<{ name: string; version: string }>;\n try {\n deps = parseDependencies(lockPath, file);\n } catch {\n continue;\n }\n\n for (const dep of deps.slice(0, MAX_DEPS_PER_LOCKFILE)) {\n let vulns: OsvVulnerability[];\n try {\n vulns = await queryOsv(dep.name, dep.version, ecosystem);\n } catch {\n continue;\n }\n\n for (const vuln of vulns) {\n const cvss = vuln.severity?.find((entry) => entry.type === 'CVSS_V3')?.score;\n findings.push({\n ruleId: 'dependency-known-vulnerability',\n title: 'Dependency CVE',\n file,\n line: 1,\n severity: severityFromCvss(cvss),\n confidence: 'evidence',\n message: `${dep.name}@${dep.version}: ${vuln.summary ?? vuln.id}`,\n consequence: 'A published advisory exists for the exact version resolved in this lockfile.',\n excerpt: `${vuln.id}${cvss ? ` (CVSS: ${cvss})` : ''}`,\n category: 'dependency',\n });\n }\n }\n }\n\n return findings;\n}\n\nfunction severityFromCvss(score: string | undefined): Severity {\n if (!score) return 'medium';\n const value = Number.parseFloat(score);\n if (Number.isNaN(value)) return 'medium';\n if (value >= 9) return 'critical';\n if (value >= 7) return 'high';\n if (value >= 4) return 'medium';\n return 'low';\n}\n\nfunction parseDependencies(lockPath: string, filename: string): Array<{ name: string; version: string }> {\n const deps: Array<{ name: string; version: string }> = [];\n\n if (filename === 'package-lock.json') {\n const lock = JSON.parse(readFileSync(lockPath, 'utf-8')) as {\n packages?: Record<string, { version?: string }>;\n dependencies?: Record<string, { version?: string }>;\n };\n const packages = lock.packages ?? lock.dependencies ?? {};\n for (const [key, value] of Object.entries(packages)) {\n const name = key.replace(/^node_modules\\//, '');\n const version = value?.version;\n if (name && version && !name.startsWith('.')) deps.push({ name, version });\n }\n return deps;\n }\n\n if (filename === 'requirements.txt') {\n for (const line of readFileSync(lockPath, 'utf-8').split('\\n')) {\n const match = /^([a-zA-Z0-9_.-]+)==([0-9.]+)/.exec(line);\n if (match?.[1] && match[2]) deps.push({ name: match[1], version: match[2] });\n }\n }\n\n return deps;\n}\n\n/** Package names and versions are validated before they reach the query body. */\nfunction isValidPackageName(name: string): boolean {\n return /^[@a-zA-Z0-9_.\\-/]{1,214}$/.test(name);\n}\n\nfunction isValidVersion(version: string): boolean {\n return /^[0-9a-zA-Z._\\-+]{1,50}$/.test(version);\n}\n\nasync function queryOsv(name: string, version: string, ecosystem: string): Promise<OsvVulnerability[]> {\n if (!isValidPackageName(name) || !isValidVersion(version)) return [];\n\n try {\n const response = await fetch('https://api.osv.dev/v1/query', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ package: { name, ecosystem }, version }),\n signal: AbortSignal.timeout(5000),\n });\n if (!response.ok) return [];\n const data = (await response.json()) as { vulns?: OsvVulnerability[] };\n return data.vulns ?? [];\n } catch {\n return [];\n }\n}\n","/**\n * SARIF 2.1.0 output.\n *\n * Why native, rather than converting the CLI's terminal output: a text parser\n * sitting between a scanner and its consumer fails in the one way that matters\n * — silently. `profullstack/malware-test-prs` documents three separate bugs its\n * `threatcrush-to-sarif.py` hit, and one of them (paths relative to the scan\n * root, unprefixed) made a working scan report a 0% true-positive rate. The\n * scan was fine. The pipe was lying.\n *\n * Emitting SARIF from the process that found the finding removes that class of\n * failure. It also makes the output portable: GitHub's Security tab, the\n * testbed's coverage validator, and any other SARIF consumer read the same\n * bytes, and none of them has to know what a ThreatCrush terminal line looks\n * like.\n *\n * Two details the spec is strict about and consumers are not forgiving about:\n *\n * - `startLine` must be >= 1. Whole-file findings carry no line, so they are\n * clamped rather than emitted as 0, which fails schema validation.\n * - `artifactLocation.uri` must be relative to something the consumer can\n * resolve. Absolute paths from a CI runner (`/home/runner/work/…`) match\n * nothing in the repository view, so every finding lands \"outside\" whatever\n * the consumer was scoping to.\n */\n\nimport { createHash } from 'node:crypto';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport type { ScanFinding, Severity } from '../types';\n\n/**\n * The key our fingerprint is published under.\n *\n * Deliberately *not* `primaryLocationLineHash`. That name is reserved: the\n * CodeQL upload action computes its own value for it and logs\n *\n * Calculated fingerprint of 13bfd14c5cc763c:1 for file debtap line 104,\n * but found existing inconsistent fingerprint value <ours>\n *\n * for every finding whose value differs from what it derived — which is any\n * value we supply, whatever it contains. The first attempt at this replaced\n * the old `ruleId:file:line` with a content hash and still logged the warning,\n * because the collision is over the *key*, not the format.\n *\n * Namespacing it leaves GitHub to compute the fingerprint it wants while other\n * SARIF consumers keep a stable identity from us. The version suffix is there\n * so the hash input can change later without silently redefining what an\n * existing value meant.\n */\nconst FINGERPRINT_KEY = 'threatcrush/contentHash/v1';\n\n/**\n * A stable identity for a finding, for `partialFingerprints`.\n *\n * The line number is deliberately not part of it. It used to be — the value\n * was `ruleId:file:line` — which meant adding an import at the top of a file\n * re-fingerprinted every finding below it. A consumer that tracks findings by\n * fingerprint then treats them as new: previously dismissed ones come back,\n * and review comments detach from the code they were written about. Hashing\n * the rule, the file and the matched text instead keeps one finding identified\n * as one finding while it moves around the file.\n *\n * Whitespace is normalised so reindentation does not count as a new finding.\n * Two identical lines in one file collide onto one fingerprint, which is the\n * right trade: they are the same defect, and SARIF locations still tell them\n * apart.\n */\nexport function fingerprintOf(finding: ScanFinding): string {\n const content = finding.excerpt.replace(/\\s+/g, ' ').trim();\n return createHash('sha256')\n .update(`${finding.ruleId}\\n${finding.file}\\n${content}`)\n .digest('hex')\n .slice(0, 32);\n}\n\nexport const SARIF_VERSION = '2.1.0';\nexport const SARIF_SCHEMA =\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json';\n\nexport type SarifLevel = 'error' | 'warning' | 'note' | 'none';\n\n/**\n * SARIF has three levels; ThreatCrush has five severities. The mapping is\n * lossy in the direction that matters least — the exact severity survives in\n * `properties.severity` and in `security-severity`, which is what GitHub's\n * Security tab actually sorts on.\n */\nexport function sarifLevel(severity: Severity): SarifLevel {\n switch (severity) {\n case 'critical':\n case 'high':\n return 'error';\n case 'medium':\n return 'warning';\n case 'low':\n return 'note';\n default:\n return 'none';\n }\n}\n\n/** GitHub reads this to place a finding on its own severity scale. */\nexport function securitySeverity(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return '9.0';\n case 'high':\n return '7.0';\n case 'medium':\n return '5.0';\n case 'low':\n return '3.0';\n default:\n return '1.0';\n }\n}\n\n/**\n * Turn a finding's path into a SARIF artifact URI.\n *\n * Findings carry paths relative to the *scan root*; consumers resolve URIs\n * against the *repository root*. Those are the same directory only when the\n * scan target is `.`, and the difference is silent — `secrets/x.env` matches\n * nothing in a repository that holds `vulns/secrets/x.env`, so a working scan\n * reports every finding as out-of-scope. `root` closes that gap by\n * reconstructing the absolute path before making it relative to `base`.\n *\n * Files outside `base` keep an absolute POSIX path rather than acquiring a run\n * of `../` segments no consumer resolves usefully.\n */\nexport function toArtifactUri(\n filePath: string,\n base: string,\n prefix = '',\n root = base,\n): string {\n const absolute = isAbsolute(filePath) ? filePath : resolve(root, filePath);\n const relativePath = relative(base, absolute);\n const escapedOut = relativePath.startsWith('..') || relativePath === '';\n const chosen = escapedOut ? absolute : relativePath;\n const posix = chosen.split(sep).join('/').replace(/^\\.\\//, '');\n if (!prefix || escapedOut) return posix;\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '');\n return trimmed ? `${trimmed}/${posix}` : posix;\n}\n\nexport interface SarifOptions {\n /** Version string reported as the tool's. */\n toolVersion: string;\n /**\n * Prepended to every relative URI. Covers the one case `root` cannot: a\n * scan run from *inside* the directory it is scanning, where the repository\n * root is not an ancestor of the working directory in any way the process\n * can observe.\n */\n pathPrefix?: string;\n /** Absolute path the URIs are made relative to. Defaults to `process.cwd()`. */\n base?: string;\n /** Absolute scan root that finding paths are relative to. Defaults to `base`. */\n root?: string;\n}\n\ninterface SarifRule {\n id: string;\n name: string;\n shortDescription: { text: string };\n fullDescription: { text: string };\n help: { text: string; markdown: string };\n defaultConfiguration: { level: SarifLevel };\n properties: {\n tags: string[];\n 'security-severity': string;\n precision: string;\n };\n}\n\n/**\n * Build a complete SARIF log.\n *\n * Always returns a valid run, including for zero findings — an empty `results`\n * array is a meaningful statement (\"looked, found nothing\") and consumers\n * distinguish it from a missing file.\n */\nexport function buildSarif(findings: readonly ScanFinding[], options: SarifOptions): unknown {\n const rules = new Map<string, SarifRule>();\n\n for (const finding of findings) {\n if (rules.has(finding.ruleId)) continue;\n const tags = ['security'];\n if (finding.cwe) tags.push(`external/cwe/${finding.cwe.toLowerCase()}`);\n tags.push(`threatcrush/${finding.category}`);\n\n const description = finding.consequence\n ? `${finding.title}. ${finding.consequence}`\n : finding.title;\n\n rules.set(finding.ruleId, {\n id: finding.ruleId,\n name: finding.ruleId,\n shortDescription: { text: finding.title },\n fullDescription: { text: description },\n help: {\n text: description,\n markdown: finding.consequence\n ? `**${finding.title}**\\n\\n${finding.consequence}`\n : `**${finding.title}**`,\n },\n defaultConfiguration: { level: sarifLevel(finding.severity) },\n properties: {\n tags,\n 'security-severity': securitySeverity(finding.severity),\n // SARIF's vocabulary for how much the rule is claiming. It lines up\n // with the confidence model: a bare construct match is `medium`, a\n // match with visible untrusted input is `high`.\n precision: finding.confidence === 'pattern' ? 'medium' : 'high',\n },\n });\n }\n\n const base = options.base ?? process.cwd();\n const root = options.root ?? base;\n\n const results = findings.map((finding) => ({\n ruleId: finding.ruleId,\n level: sarifLevel(finding.severity),\n message: { text: finding.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: toArtifactUri(finding.file, base, options.pathPrefix, root),\n uriBaseId: '%SRCROOT%',\n },\n region: {\n // Clamped, never 0. A whole-file finding has no line; SARIF has no\n // way to say that, and 0 fails validation outright.\n startLine: Math.max(1, finding.line),\n snippet: { text: finding.excerpt },\n },\n },\n },\n ],\n partialFingerprints: {\n [FINGERPRINT_KEY]: fingerprintOf(finding),\n },\n properties: {\n severity: finding.severity,\n confidence: finding.confidence,\n category: finding.category,\n ...(finding.cwe ? { cwe: finding.cwe } : {}),\n },\n }));\n\n return {\n $schema: SARIF_SCHEMA,\n version: SARIF_VERSION,\n runs: [\n {\n tool: {\n driver: {\n name: 'ThreatCrush',\n version: options.toolVersion,\n informationUri: 'https://threatcrush.com',\n rules: [...rules.values()],\n },\n },\n results,\n columnKind: 'utf16CodeUnits',\n },\n ],\n };\n}\n","import { execSync } from 'node:child_process';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { banner, logger } from '../core/logger.js';\nimport type { RunResult, StructuredFinding } from '../core/run-result.js';\nimport { summarize } from '../core/run-result.js';\n\ninterface PentestResult {\n url: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n message: string;\n details?: string;\n}\n\n// Basic vulnerability tests\nconst PENTEST_CHECKS = [\n {\n name: 'XSS Reflected',\n test: (html: string) => /<script>alert\\(1\\)<\\/script>|<img\\s+src=x\\s+onerror=alert/i.test(html),\n severity: 'critical' as const,\n message: 'Reflected XSS payload rendered in response',\n },\n {\n name: 'Open Redirect',\n test: (url: string, body: string) => body.includes('location.href') || body.includes('window.location'),\n severity: 'medium' as const,\n message: 'Potential open redirect detected',\n },\n {\n name: 'Missing Security Headers',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const required = ['x-content-type-options', 'x-frame-options', 'strict-transport-security'];\n const missing = required.filter(h => !headers[h.toLowerCase()]);\n return missing.length > 2;\n },\n severity: 'low' as const,\n message: 'Missing critical security headers (X-Content-Type-Options, X-Frame-Options, HSTS)',\n },\n {\n name: 'Server Version Disclosure',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n return !!(headers['server'] && /apache|nginx|iis|tomcat/i.test(headers['server']));\n },\n severity: 'low' as const,\n message: 'Server version disclosed in response header',\n },\n {\n name: 'Directory Listing',\n test: (html: string) => /Index of\\s*\\/|<title>Directory Listing/i.test(html),\n severity: 'medium' as const,\n message: 'Directory listing enabled',\n },\n {\n name: 'Error Page Information Disclosure',\n test: (html: string) => /stack trace|traceback|exception|at\\s+\\w+\\.\\w+\\(/i.test(html),\n severity: 'medium' as const,\n message: 'Error page reveals internal information',\n },\n // PRD 07: Additional checks\n {\n name: 'CORS Misconfiguration',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const acao = headers['access-control-allow-origin'];\n return acao === '*' || acao === 'null';\n },\n severity: 'medium' as const,\n message: 'CORS allows any origin (Access-Control-Allow-Origin: *)',\n },\n {\n name: 'Cookie Security',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const setCookie = headers['set-cookie'] || '';\n return setCookie.length > 0 && (!setCookie.includes('HttpOnly') || !setCookie.includes('Secure'));\n },\n severity: 'medium' as const,\n message: 'Cookies missing HttpOnly or Secure flags',\n },\n {\n name: 'Content Security Policy',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n return !headers['content-security-policy'];\n },\n severity: 'low' as const,\n message: 'No Content-Security-Policy header set',\n },\n {\n name: 'Sensitive Path Exposure',\n test: (html: string) => /\\.env|wp-admin|phpinfo|\\.git\\/config|server-status/i.test(html),\n severity: 'high' as const,\n message: 'Response references sensitive paths or admin endpoints',\n },\n];\n\nexport async function runPentest(rawUrl: string): Promise<RunResult> {\n const targetUrl = rawUrl.startsWith('http') ? rawUrl : `https://${rawUrl}`;\n const results = await collectPentestResults(targetUrl);\n const structured: StructuredFinding[] = results.map((r) => ({\n type: r.type,\n severity: r.severity === 'low' ? 'low' : (r.severity as StructuredFinding['severity']),\n message: r.message,\n location: r.url,\n details: r.details ? { detail: r.details } : undefined,\n }));\n const counts = summarize(structured);\n return {\n type: 'pentest',\n target: targetUrl,\n findings: structured,\n severity_summary: counts,\n summary: structured.length === 0\n ? 'No vulnerabilities detected'\n : `${structured.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`,\n };\n}\n\nasync function collectPentestResults(targetUrl: string): Promise<PentestResult[]> {\n const results: PentestResult[] = [];\n try {\n const resp = await fetch(targetUrl, { redirect: 'manual' });\n const headers: Record<string, string> = {};\n resp.headers.forEach((v, k) => { headers[k] = v; });\n const body = await resp.text();\n for (const check of PENTEST_CHECKS) {\n try {\n if (check.test(body, body, headers)) {\n results.push({ url: targetUrl, type: check.name, severity: check.severity, message: check.message });\n }\n } catch { /* skip */ }\n }\n } catch {\n return results;\n }\n\n const sqliPayloads = [\"' OR 1=1--\", \"1' UNION SELECT NULL--\", \"' AND '1'='1\"];\n for (const payload of sqliPayloads) {\n try {\n const testUrl = `${targetUrl}?id=${encodeURIComponent(payload)}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/sql\\s+(syntax|error|exception)|mysql|postgres|ORA-\\d+/i.test(body)) {\n results.push({ url: testUrl, type: 'SQL Injection', severity: 'critical', message: `SQL error with payload: ${payload}` });\n }\n } catch { /* skip */ }\n }\n\n const traversalPaths = ['../../etc/passwd', '..%2F..%2Fetc%2Fpasswd', '....//....//etc/passwd'];\n for (const path of traversalPaths) {\n try {\n const testUrl = `${targetUrl}/${path}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/root:.*:0:0:|daemon:.*:1:1:|nobody:.*:65534/i.test(body)) {\n results.push({ url: testUrl, type: 'Path Traversal', severity: 'critical', message: `Possible /etc/passwd disclosure: ${path}` });\n }\n } catch { /* skip */ }\n }\n\n const methods = ['OPTIONS', 'TRACE', 'DELETE', 'PUT'];\n for (const method of methods) {\n try {\n const resp = await fetch(targetUrl, { method, signal: AbortSignal.timeout(5000) });\n if (resp.status < 400 && method !== 'OPTIONS') {\n results.push({ url: targetUrl, type: `Unsafe HTTP Method: ${method}`, severity: 'medium', message: `${method} allowed (status ${resp.status})` });\n }\n if (method === 'OPTIONS') {\n const allow = resp.headers.get('allow');\n if (allow && /DELETE|PUT|TRACE/i.test(allow)) {\n results.push({ url: targetUrl, type: 'HTTP Methods', severity: 'low', message: `Allowed methods: ${allow}` });\n }\n }\n } catch { /* skip */ }\n }\n\n return results;\n}\n\nexport async function pentestCommand(targetUrl: string): Promise<RunResult> {\n banner();\n\n // Ensure URL has protocol\n if (!targetUrl.startsWith('http')) {\n targetUrl = `https://${targetUrl}`;\n }\n\n logger.info(`Penetration testing ${chalk.white(targetUrl)}...\\n`);\n\n const results: PentestResult[] = [];\n\n // Test 1: Basic response analysis\n const spinner = ora({ text: 'Fetching target...', color: 'green' }).start();\n try {\n const resp = await fetch(targetUrl, { redirect: 'manual' });\n const headers: Record<string, string> = {};\n resp.headers.forEach((v, k) => { headers[k] = v; });\n const body = await resp.text();\n\n spinner.succeed(`Got ${resp.status} response\\n`);\n\n // Run all checks\n for (const check of PENTEST_CHECKS) {\n try {\n if (check.test(body, body, headers)) {\n results.push({\n url: targetUrl,\n type: check.name,\n severity: check.severity,\n message: check.message,\n });\n }\n } catch {\n // Skip check on error\n }\n }\n } catch (err) {\n spinner.fail(`Failed to reach target: ${(err as Error).message}`);\n console.log(chalk.gray(' Check the URL and try again.\\n'));\n return {\n type: 'pentest',\n target: targetUrl,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `Failed to reach target: ${(err as Error).message}`,\n error: (err as Error).message,\n };\n }\n\n // Test 2: SQL injection probe\n const sqliSpinner = ora({ text: 'Testing SQL injection vectors...', color: 'green' }).start();\n const sqliPayloads = [\"' OR 1=1--\", \"1' UNION SELECT NULL--\", \"' AND '1'='1\"];\n for (const payload of sqliPayloads) {\n try {\n const testUrl = `${targetUrl}?id=${encodeURIComponent(payload)}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/sql\\s+(syntax|error|exception)|mysql|postgres|ORA-\\d+/i.test(body)) {\n results.push({\n url: testUrl,\n type: 'SQL Injection',\n severity: 'critical',\n message: `SQL error response detected with payload: ${payload}`,\n });\n }\n } catch {\n // Skip on timeout/network error\n }\n }\n sqliSpinner.succeed('SQL injection tests complete\\n');\n\n // Test 3: Path traversal probe\n const pathSpinner = ora({ text: 'Testing path traversal...', color: 'green' }).start();\n const traversalPaths = ['../../etc/passwd', '..%2F..%2Fetc%2Fpasswd', '....//....//etc/passwd'];\n for (const path of traversalPaths) {\n try {\n const testUrl = `${targetUrl}/${path}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/root:.*:0:0:|daemon:.*:1:1:|nobody:.*:65534/i.test(body)) {\n results.push({\n url: testUrl,\n type: 'Path Traversal',\n severity: 'critical',\n message: `Possible /etc/passwd disclosure via: ${path}`,\n });\n }\n } catch {\n // Skip on timeout/network error\n }\n }\n pathSpinner.succeed('Path traversal tests complete\\n');\n\n // Test 4: HTTP methods\n const methodSpinner = ora({ text: 'Testing HTTP methods...', color: 'green' }).start();\n const methods = ['OPTIONS', 'TRACE', 'DELETE', 'PUT'];\n for (const method of methods) {\n try {\n const resp = await fetch(targetUrl, { method, signal: AbortSignal.timeout(5000) });\n if (resp.status < 400 && method !== 'OPTIONS') {\n results.push({\n url: targetUrl,\n type: `Unsafe HTTP Method: ${method}`,\n severity: 'medium',\n message: `${method} method is allowed (status ${resp.status})`,\n });\n }\n if (method === 'OPTIONS') {\n const allow = resp.headers.get('allow');\n if (allow && /DELETE|PUT|TRACE/i.test(allow)) {\n results.push({\n url: targetUrl,\n type: 'HTTP Methods',\n severity: 'low',\n message: `Allowed methods: ${allow}`,\n });\n }\n }\n } catch {\n // Skip on error\n }\n }\n methodSpinner.succeed('HTTP method tests complete\\n');\n\n const structured: StructuredFinding[] = results.map((r) => ({\n type: r.type,\n severity: r.severity as StructuredFinding['severity'],\n message: r.message,\n location: r.url,\n details: r.details ? { detail: r.details } : undefined,\n }));\n const sevCounts = summarize(structured);\n\n // Print results\n if (results.length === 0) {\n console.log(chalk.green.bold(' ✓ No vulnerabilities detected in basic scan!'));\n console.log(chalk.dim(' Note: This is a basic scan. Full pentest requires manual review.\\n'));\n return {\n type: 'pentest',\n target: targetUrl,\n findings: [],\n severity_summary: sevCounts,\n summary: 'No vulnerabilities detected',\n };\n }\n\n const critical = results.filter(r => r.severity === 'critical');\n const high = results.filter(r => r.severity === 'high');\n const medium = results.filter(r => r.severity === 'medium');\n const low = results.filter(r => r.severity === 'low');\n\n console.log(chalk.white.bold(' Penetration Test Results'));\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.red.bold(critical.length + ' critical')} ` +\n `${chalk.red(high.length + ' high')} ` +\n `${chalk.yellow(medium.length + ' medium')} ` +\n `${chalk.gray(low.length + ' low')}`,\n );\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log();\n\n const sorted = [...critical, ...high, ...medium, ...low];\n for (const r of sorted) {\n const sev =\n r.severity === 'critical' ? chalk.bgRed.white.bold(` ${r.severity.toUpperCase()} `) :\n r.severity === 'high' ? chalk.red(`[${r.severity.toUpperCase()}]`) :\n r.severity === 'medium' ? chalk.yellow(`[${r.severity.toUpperCase()}]`) :\n chalk.gray(`[${r.severity.toUpperCase()}]`);\n\n console.log(` ${sev} ${chalk.white.bold(r.type)}`);\n console.log(` ${chalk.gray('URL:')} ${chalk.cyan(r.url)}`);\n console.log(` ${chalk.gray('Info:')} ${r.message}`);\n if (r.details) console.log(` ${chalk.gray('Details:')} ${r.details}`);\n console.log();\n }\n\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(` ${chalk.white.bold(`${results.length} issue(s) found`)}`);\n console.log(chalk.dim(' Note: This is an automated basic scan. Manual review recommended.\\n'));\n\n return {\n type: 'pentest',\n target: targetUrl,\n findings: structured,\n severity_summary: sevCounts,\n summary: `${results.length} issue(s): ${sevCounts.critical}C ${sevCounts.high}H ${sevCounts.medium}M ${sevCounts.low}L`,\n };\n}\n","import type { EventBus } from '../event-bus.js';\nimport { readCliConfig, authHeaders, isLoggedIn } from '../../core/cli-config.js';\nimport { runScan } from '../../commands/scan.js';\nimport { runPentest } from '../../commands/pentest.js';\nimport { workerId, type RunResult } from '../../core/run-result.js';\n\nconst API_URL = process.env.THREATCRUSH_API_URL || 'https://threatcrush.com';\nconst POLL_INTERVAL_MS = 30_000;\nconst SCHEDULE_INTERVAL_MS = 120_000;\n\ninterface ClaimedRun {\n id: string;\n org_id: string;\n property_id: string;\n type: 'scan' | 'pentest';\n property: { id: string; name: string; kind: string; target: string } | null;\n}\n\n/**\n * Polls the server for queued property runs belonging to orgs the logged-in\n * user is a member of, claims them atomically, executes them locally, and\n * posts the result back.\n *\n * No-op unless `~/.threatcrush/config.json` contains a valid bearer token.\n */\nexport class RunsWorker {\n private pollTimer: NodeJS.Timeout | null = null;\n private scheduleTimer: NodeJS.Timeout | null = null;\n private running = false;\n private orgIds: string[] = [];\n\n constructor(private bus: EventBus) {}\n\n async start(): Promise<void> {\n if (!isLoggedIn()) return;\n\n try {\n await this.refreshOrgs();\n } catch {\n // First fetch may fail if the network is down; the tick loop will retry.\n }\n\n this.bus.announceModule('runs-worker', 'running', `poll ${POLL_INTERVAL_MS / 1000}s`);\n this.tick();\n this.scheduleTick();\n this.pollTimer = setInterval(() => this.tick(), POLL_INTERVAL_MS);\n this.scheduleTimer = setInterval(() => this.scheduleTick(), SCHEDULE_INTERVAL_MS);\n }\n\n stop(): void {\n if (this.pollTimer) clearInterval(this.pollTimer);\n if (this.scheduleTimer) clearInterval(this.scheduleTimer);\n this.pollTimer = null;\n this.scheduleTimer = null;\n this.bus.announceModule('runs-worker', 'stopped');\n }\n\n private async scheduleTick(): Promise<void> {\n if (!isLoggedIn()) return;\n try {\n if (this.orgIds.length === 0) await this.refreshOrgs();\n for (const orgId of this.orgIds) {\n try {\n await fetch(`${API_URL}/api/orgs/${orgId}/schedules/tick`, {\n method: 'POST',\n headers: authHeaders(),\n });\n } catch {\n // ignore transient network errors\n }\n }\n } catch {\n // swallow — retry next interval\n }\n }\n\n private async tick(): Promise<void> {\n if (this.running) return;\n if (!isLoggedIn()) return;\n\n this.running = true;\n try {\n if (this.orgIds.length === 0) await this.refreshOrgs();\n for (const orgId of this.orgIds) {\n const claimed = await this.claimOne(orgId);\n if (!claimed) continue;\n\n const result = await this.execute(claimed);\n await this.finalize(orgId, claimed, result);\n }\n } catch {\n // swallow — we'll try again on the next tick\n } finally {\n this.running = false;\n }\n }\n\n private async refreshOrgs(): Promise<void> {\n const res = await fetch(`${API_URL}/api/orgs`, { headers: authHeaders() });\n if (!res.ok) return;\n const data = await res.json() as { organizations?: Array<{ id: string }> };\n this.orgIds = (data.organizations || []).map((o) => o.id);\n }\n\n private async claimOne(orgId: string): Promise<ClaimedRun | null> {\n try {\n const res = await fetch(`${API_URL}/api/orgs/${orgId}/runs/pending`, {\n method: 'POST',\n headers: authHeaders(),\n body: JSON.stringify({ worker_id: workerId() }),\n });\n if (!res.ok) return null;\n const data = await res.json() as { run?: ClaimedRun | null };\n return data.run ?? null;\n } catch {\n return null;\n }\n }\n\n private async execute(run: ClaimedRun): Promise<RunResult> {\n const target = run.property?.target;\n if (!target) {\n return {\n type: run.type,\n target: '',\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: 'property target missing',\n error: 'property target missing',\n };\n }\n\n this.bus.announceModule('runs-worker', 'running', `${run.type} ${run.property?.name || target}`);\n\n try {\n if (run.type === 'scan') return await runScan(target);\n return await runPentest(target);\n } catch (err) {\n return {\n type: run.type,\n target,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `failed: ${(err as Error).message}`,\n error: (err as Error).message,\n };\n }\n }\n\n private async finalize(orgId: string, claimed: ClaimedRun, result: RunResult): Promise<void> {\n try {\n await fetch(\n `${API_URL}/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,\n {\n method: 'PATCH',\n headers: authHeaders(),\n body: JSON.stringify({\n status: result.error ? 'failed' : 'succeeded',\n findings_count: result.findings.length,\n severity_summary: result.severity_summary,\n summary: result.summary,\n findings: result.findings,\n error: result.error,\n source: 'daemon',\n worker_id: workerId(),\n }),\n },\n );\n } catch {\n // best-effort\n } finally {\n this.bus.announceModule('runs-worker', 'idle');\n }\n }\n}\n","import type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\nexport interface DetectionRule {\n id: string;\n title: string;\n description: string;\n version: string;\n category: string;\n severity: EventSeverity;\n source_types: string[];\n match: RuleMatch;\n threshold: number;\n window_seconds: number;\n cooldown_seconds: number;\n tags: string[];\n remediation?: {\n action?: string;\n ttl_seconds?: number;\n description?: string;\n };\n enabled: boolean;\n}\n\nexport interface RuleMatch {\n field: string;\n operator: 'contains' | 'regex' | 'equals' | 'starts_with' | 'ends_with';\n value: string;\n and?: RuleMatch[];\n or?: RuleMatch[];\n}\n\ninterface EventWindow {\n events: Array<{ timestamp: number; event: ThreatEvent }>;\n lastAlert: number;\n}\n\nexport class RuleEngine {\n private rules: DetectionRule[] = [];\n private windows = new Map<string, EventWindow>();\n\n constructor(private onDetection: (detection: {\n rule_id: string;\n severity: EventSeverity;\n title: string;\n description: string;\n source_ip?: string;\n username?: string;\n raw_metadata?: Record<string, unknown>;\n }) => void) {}\n\n loadRules(rules: DetectionRule[]): void {\n this.rules = rules.filter(r => r.enabled !== false);\n }\n\n getRules(): DetectionRule[] {\n return [...this.rules];\n }\n\n evaluate(event: ThreatEvent): void {\n const now = Date.now();\n\n for (const rule of this.rules) {\n // Check source type match\n if (rule.source_types.length > 0 && !rule.source_types.includes(event.module) && !rule.source_types.includes(event.category)) {\n continue;\n }\n\n // Check match conditions\n if (!this.matchesCondition(event, rule.match)) continue;\n\n // Window key: rule_id + source_ip (or 'global')\n const windowKey = `${rule.id}:${event.source_ip || 'global'}`;\n let window = this.windows.get(windowKey);\n if (!window) {\n window = { events: [], lastAlert: 0 };\n this.windows.set(windowKey, window);\n }\n\n // Add event to window\n window.events.push({ timestamp: now, event });\n\n // Prune old events outside window\n const cutoff = now - (rule.window_seconds * 1000);\n window.events = window.events.filter(e => e.timestamp >= cutoff);\n\n // Check threshold\n if (window.events.length < rule.threshold) continue;\n\n // Check cooldown\n if (window.lastAlert > 0 && (now - window.lastAlert) < (rule.cooldown_seconds * 1000)) continue;\n\n // Fire detection\n window.lastAlert = now;\n window.events = []; // Reset window after detection\n\n this.onDetection({\n rule_id: rule.id,\n severity: rule.severity,\n title: rule.title,\n description: `${rule.description} (${rule.threshold} events in ${rule.window_seconds}s)`,\n source_ip: event.source_ip,\n username: event.details?.user as string || undefined,\n raw_metadata: {\n rule_version: rule.version,\n tags: rule.tags,\n category: rule.category,\n remediation: rule.remediation,\n },\n });\n }\n }\n\n private matchesCondition(event: ThreatEvent, match: RuleMatch): boolean {\n const fieldValue = this.getFieldValue(event, match.field);\n if (fieldValue === undefined) return false;\n\n const strValue = String(fieldValue);\n let result = false;\n\n switch (match.operator) {\n case 'contains':\n result = strValue.toLowerCase().includes(String(match.value).toLowerCase());\n break;\n case 'regex':\n try { result = new RegExp(String(match.value), 'i').test(strValue); } catch { result = false; }\n break;\n case 'equals':\n result = strValue === String(match.value);\n break;\n case 'starts_with':\n result = strValue.startsWith(String(match.value));\n break;\n case 'ends_with':\n result = strValue.endsWith(String(match.value));\n break;\n }\n\n // AND conditions\n if (result && match.and) {\n result = match.and.every(m => this.matchesCondition(event, m));\n }\n\n // OR conditions\n if (!result && match.or) {\n result = match.or.some(m => this.matchesCondition(event, m));\n }\n\n return result;\n }\n\n private getFieldValue(event: ThreatEvent, field: string): unknown {\n switch (field) {\n case 'message': return event.message;\n case 'severity': return event.severity;\n case 'module': return event.module;\n case 'category': return event.category;\n case 'source_ip': return event.source_ip;\n default:\n return event.details?.[field];\n }\n }\n\n // Periodic cleanup of stale windows\n cleanup(): void {\n const now = Date.now();\n for (const [key, window] of this.windows.entries()) {\n if (window.events.length === 0 && (now - window.lastAlert) > 3600_000) {\n this.windows.delete(key);\n }\n }\n }\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { DetectionRule } from './engine.js';\nimport { DEFAULT_RULES } from './default-rules.js';\n\nconst RULES_DIR = '/etc/threatcrush/rules.d';\n\nexport function loadAllRules(customDir?: string): DetectionRule[] {\n const rules = [...DEFAULT_RULES];\n const dir = customDir || RULES_DIR;\n\n if (existsSync(dir)) {\n const files = readdirSync(dir).filter(f => f.endsWith('.json'));\n for (const file of files) {\n try {\n const raw = readFileSync(join(dir, file), 'utf-8');\n const parsed = JSON.parse(raw);\n const customRules: DetectionRule[] = Array.isArray(parsed) ? parsed : [parsed];\n for (const rule of customRules) {\n if (!rule.id || !rule.title || !rule.match) {\n console.warn(`[rules] skipping invalid rule in ${file}: missing required fields`);\n continue;\n }\n const existingIdx = rules.findIndex(r => r.id === rule.id);\n if (existingIdx >= 0) {\n rules[existingIdx] = { ...rules[existingIdx], ...rule };\n } else {\n rules.push(rule);\n }\n }\n } catch (err) {\n console.warn(`[rules] failed to load ${file}: ${(err as Error).message}`);\n }\n }\n }\n\n return rules;\n}\n","import type { DetectionRule } from './engine.js';\n\nexport const DEFAULT_RULES: DetectionRule[] = [\n {\n id: 'ssh-brute-force',\n title: 'SSH Brute Force Detected',\n description: 'Multiple failed SSH login attempts from the same source',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'failed ssh login|invalid ssh user',\n },\n threshold: 5,\n window_seconds: 300,\n cooldown_seconds: 600,\n tags: ['ssh', 'brute-force', 'credential-stuffing'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP for 1 hour',\n },\n enabled: true,\n },\n {\n id: 'ssh-success-after-failures',\n title: 'SSH Login After Failed Attempts',\n description: 'Successful SSH login from an IP that had recent failures',\n version: '1.0.0',\n category: 'auth',\n severity: 'critical',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'SSH login accepted',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['ssh', 'compromise-indicator'],\n enabled: true,\n },\n {\n id: 'ssh-root-login',\n title: 'Root SSH Login Attempt',\n description: 'Direct root login via SSH detected',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'regex',\n value: '(failed|accepted).*\\\\broot\\\\b',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['ssh', 'root-access'],\n remediation: {\n action: 'block',\n ttl_seconds: 7200,\n description: 'Block source IP attempting root login',\n },\n enabled: true,\n },\n {\n id: 'ssh-user-enumeration',\n title: 'SSH User Enumeration',\n description: 'Multiple SSH attempts with different usernames from same source',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Invalid SSH user',\n },\n threshold: 3,\n window_seconds: 120,\n cooldown_seconds: 600,\n tags: ['ssh', 'enumeration', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing user enumeration',\n },\n enabled: true,\n },\n {\n id: 'sudo-abuse',\n title: 'Sudo Authentication Failure',\n description: 'Repeated sudo authentication failures',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['user-journal', 'system'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'sudo.*authentication failure|sudo.*incorrect password|sudo.*FAILED',\n },\n threshold: 3,\n window_seconds: 300,\n cooldown_seconds: 600,\n tags: ['sudo', 'privilege-escalation'],\n enabled: true,\n },\n {\n id: 'web-sqli-attack',\n title: 'SQL Injection Attack Detected',\n description: 'HTTP request with SQL injection patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'critical',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Attack detected [SQLI]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'sqli', 'injection'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing SQL injection',\n },\n enabled: true,\n },\n {\n id: 'web-path-traversal',\n title: 'Path Traversal Attack Detected',\n description: 'HTTP request with path traversal patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'critical',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Attack detected [PATH_TRAVERSAL]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'path-traversal', 'lfi'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing path traversal',\n },\n enabled: true,\n },\n {\n id: 'web-xss-attack',\n title: 'XSS Attack Detected',\n description: 'HTTP request with cross-site scripting patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'high',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Attack detected \\\\[XSS\\\\]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'xss', 'injection'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing XSS attack',\n },\n enabled: true,\n },\n {\n id: 'web-scanner-detection',\n title: 'Web Vulnerability Scanner Detected',\n description: 'High volume of 4xx errors suggesting automated scanning',\n version: '1.0.0',\n category: 'web',\n severity: 'medium',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Client error 4\\\\d{2}:',\n },\n threshold: 20,\n window_seconds: 60,\n cooldown_seconds: 600,\n tags: ['web', 'scanner', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 1800,\n description: 'Block automated scanner',\n },\n enabled: true,\n },\n {\n id: 'port-scan-indicator',\n title: 'Port Scan Indicators',\n description: 'Connection attempts to many ports from a single source',\n version: '1.0.0',\n category: 'network',\n severity: 'medium',\n source_types: ['network-monitor', 'network'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'port scan',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['network', 'port-scan', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block port scanner',\n },\n enabled: true,\n },\n {\n id: 'system-critical-error',\n title: 'Critical System Error',\n description: 'Critical or emergency level system log message',\n version: '1.0.0',\n category: 'system',\n severity: 'critical',\n source_types: ['user-journal', 'system'],\n match: {\n field: 'severity',\n operator: 'equals',\n value: 'critical',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['system', 'critical'],\n enabled: true,\n },\n {\n id: 'exploit-probe-pattern',\n title: 'Exploit Probe Pattern',\n description: 'HTTP requests matching common exploit probe patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'high',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Attack detected \\\\[(CMD_INJECTION|RCE|SSRF|XXE)\\\\]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'exploit', 'probe'],\n remediation: {\n action: 'block',\n ttl_seconds: 7200,\n description: 'Block source IP performing exploit probes',\n },\n enabled: true,\n },\n];\n","import { execSync, spawnSync } from 'node:child_process';\nimport { isIP } from 'node:net';\n\nexport interface FirewallAdapter {\n name: string;\n isAvailable(): boolean;\n block(ip: string): Promise<void>;\n unblock(ip: string): Promise<void>;\n isBlocked(ip: string): Promise<boolean>;\n listBlocked(): Promise<string[]>;\n}\n\nfunction assertValidFirewallIp(ip: string): void {\n if (isIP(ip) !== 4) {\n throw new Error(`Invalid IPv4 address: ${ip}`);\n }\n}\n\nexport class NftablesAdapter implements FirewallAdapter {\n name = 'nftables';\n private table = 'threatcrush';\n private set = 'blocklist';\n\n isAvailable(): boolean {\n const result = spawnSync('nft', ['--version'], { stdio: 'pipe' });\n return result.status === 0;\n }\n\n private ensureSetup(): void {\n try {\n execSync(`nft list table inet ${this.table} 2>/dev/null`, { stdio: 'pipe' });\n } catch {\n execSync(`nft add table inet ${this.table}`);\n execSync(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);\n execSync(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);\n execSync(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);\n }\n }\n\n async block(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n this.ensureSetup();\n execSync(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);\n }\n\n async unblock(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n try {\n execSync(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);\n } catch { /* element may not exist */ }\n }\n\n async isBlocked(ip: string): Promise<boolean> {\n assertValidFirewallIp(ip);\n try {\n const output = execSync(`nft list set inet ${this.table} ${this.set}`, { encoding: 'utf-8' });\n return output.includes(ip);\n } catch { return false; }\n }\n\n async listBlocked(): Promise<string[]> {\n try {\n const output = execSync(`nft list set inet ${this.table} ${this.set}`, { encoding: 'utf-8' });\n const match = output.match(/elements\\s*=\\s*\\{([^}]*)\\}/);\n if (!match) return [];\n return match[1].split(',').map(s => s.trim().split(/\\s/)[0]).filter(Boolean);\n } catch { return []; }\n }\n}\n\nexport class IptablesAdapter implements FirewallAdapter {\n name = 'iptables';\n private chain = 'THREATCRUSH';\n\n isAvailable(): boolean {\n const result = spawnSync('iptables', ['--version'], { stdio: 'pipe' });\n return result.status === 0;\n }\n\n private ensureChain(): void {\n try {\n execSync(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: 'pipe' });\n } catch {\n execSync(`iptables -N ${this.chain}`);\n execSync(`iptables -I INPUT 1 -j ${this.chain}`);\n }\n }\n\n async block(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n this.ensureChain();\n if (await this.isBlocked(ip)) return;\n execSync(`iptables -A ${this.chain} -s ${ip} -j DROP`);\n }\n\n async unblock(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n try { execSync(`iptables -D ${this.chain} -s ${ip} -j DROP`); }\n catch { /* rule may not exist */ }\n }\n\n async isBlocked(ip: string): Promise<boolean> {\n assertValidFirewallIp(ip);\n try {\n const output = execSync(`iptables -n -L ${this.chain}`, { encoding: 'utf-8' });\n return output.includes(ip);\n } catch { return false; }\n }\n\n async listBlocked(): Promise<string[]> {\n try {\n const output = execSync(`iptables -n -L ${this.chain}`, { encoding: 'utf-8' });\n const ips: string[] = [];\n for (const line of output.split('\\n')) {\n const match = line.match(/DROP\\s+all\\s+--\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)/);\n if (match) ips.push(match[1]);\n }\n return ips;\n } catch { return []; }\n }\n}\n\nexport class DryRunAdapter implements FirewallAdapter {\n name = 'dry-run';\n private blocked = new Set<string>();\n\n isAvailable(): boolean { return true; }\n async block(ip: string): Promise<void> { assertValidFirewallIp(ip); this.blocked.add(ip); }\n async unblock(ip: string): Promise<void> { assertValidFirewallIp(ip); this.blocked.delete(ip); }\n async isBlocked(ip: string): Promise<boolean> { assertValidFirewallIp(ip); return this.blocked.has(ip); }\n async listBlocked(): Promise<string[]> { return [...this.blocked]; }\n}\n\nexport function detectFirewallAdapter(): FirewallAdapter {\n const nft = new NftablesAdapter();\n if (nft.isAvailable()) return nft;\n const ipt = new IptablesAdapter();\n if (ipt.isAvailable()) return ipt;\n return new DryRunAdapter();\n}\n","import { appendFileSync } from 'node:fs';\nimport type { FirewallAdapter } from './adapters.js';\nimport type { EventBus } from '../event-bus.js';\nimport { getModuleState, setModuleState } from '../../core/state.js';\nimport { PATHS } from '../paths.js';\nimport type { ThreatEvent } from '../../types/events.js';\n\ninterface BlockEntry {\n ip: string;\n reason: string;\n rule_id?: string;\n blocked_at: number;\n expires_at?: number;\n dry_run: boolean;\n}\n\ninterface RemediationConfig {\n enabled: boolean;\n dry_run: boolean;\n default_ttl_seconds: number;\n min_severity: string;\n allowlist: string[];\n}\n\nconst DEFAULT_CONFIG: RemediationConfig = {\n enabled: true,\n dry_run: true,\n default_ttl_seconds: 3600,\n min_severity: 'high',\n allowlist: ['127.0.0.1', '::1'],\n};\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\nexport class RemediationManager {\n private config: RemediationConfig;\n private blocklist: BlockEntry[] = [];\n private expiryTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private adapter: FirewallAdapter,\n private bus: EventBus,\n config?: Partial<RemediationConfig>,\n ) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.loadState();\n this.startExpiryWorker();\n }\n\n async handleDetection(event: ThreatEvent): Promise<void> {\n if (!this.config.enabled) return;\n\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[this.config.min_severity] ?? 3;\n if (eventRank < minRank) return;\n\n const ip = event.source_ip;\n if (!ip) return;\n if (this.isAllowlisted(ip)) return;\n if (this.blocklist.some(b => b.ip === ip)) return;\n\n const ruleRemediation = event.details?.remediation as Record<string, unknown> | undefined;\n const ttl = (ruleRemediation?.ttl_seconds as number) || this.config.default_ttl_seconds;\n const ruleId = event.details?.rule_id as string | undefined;\n\n await this.blockIp(ip, event.message, ruleId, ttl);\n }\n\n async blockIp(ip: string, reason: string, ruleId?: string, ttlSeconds?: number): Promise<boolean> {\n if (this.isAllowlisted(ip)) return false;\n\n const entry: BlockEntry = {\n ip,\n reason,\n rule_id: ruleId,\n blocked_at: Date.now(),\n expires_at: ttlSeconds ? Date.now() + (ttlSeconds * 1000) : undefined,\n dry_run: this.config.dry_run,\n };\n\n if (!this.config.dry_run) {\n try {\n await this.adapter.block(ip);\n } catch (err) {\n this.logLine(`[firewall] EACCES or error blocking ${ip}: ${(err as Error).message}`);\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'medium',\n message: `Failed to block ${ip}: ${(err as Error).message}. Ensure daemon has CAP_NET_ADMIN.`,\n });\n return false;\n }\n }\n\n this.blocklist.push(entry);\n this.saveState();\n\n const mode = this.config.dry_run ? '[DRY-RUN] ' : '';\n const expiryMsg = ttlSeconds ? ` (expires in ${ttlSeconds}s)` : ' (permanent)';\n this.logLine(`[firewall] ${mode}Blocked ${ip}: ${reason}${expiryMsg}`);\n\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'info',\n message: `${mode}Blocked ${ip}: ${reason}${expiryMsg}`,\n source_ip: ip,\n details: { action: 'block', rule_id: ruleId, dry_run: this.config.dry_run, ttl_seconds: ttlSeconds },\n });\n\n return true;\n }\n\n async unblockIp(ip: string): Promise<boolean> {\n const idx = this.blocklist.findIndex(b => b.ip === ip);\n if (idx < 0) return false;\n\n const entry = this.blocklist[idx];\n if (!entry.dry_run) {\n try {\n await this.adapter.unblock(ip);\n } catch (err) {\n this.logLine(`[firewall] Error unblocking ${ip}: ${(err as Error).message}`);\n return false;\n }\n }\n\n this.blocklist.splice(idx, 1);\n this.saveState();\n\n this.logLine(`[firewall] Unblocked ${ip}`);\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'info',\n message: `Unblocked ${ip}`,\n source_ip: ip,\n details: { action: 'unblock' },\n });\n\n return true;\n }\n\n isAllowlisted(ip: string): boolean {\n return this.config.allowlist.includes(ip);\n }\n\n addToAllowlist(ip: string): void {\n if (!this.config.allowlist.includes(ip)) {\n this.config.allowlist.push(ip);\n }\n }\n\n removeFromAllowlist(ip: string): void {\n this.config.allowlist = this.config.allowlist.filter(a => a !== ip);\n }\n\n getBlocklist(): BlockEntry[] { return [...this.blocklist]; }\n getAllowlist(): string[] { return [...this.config.allowlist]; }\n\n stop(): void {\n if (this.expiryTimer) clearInterval(this.expiryTimer);\n this.expiryTimer = null;\n }\n\n private startExpiryWorker(): void {\n this.expiryTimer = setInterval(() => void this.processExpiries(), 30_000);\n }\n\n private async processExpiries(): Promise<void> {\n const now = Date.now();\n const expired = this.blocklist.filter(b => b.expires_at && b.expires_at <= now);\n for (const entry of expired) {\n await this.unblockIp(entry.ip);\n }\n }\n\n private loadState(): void {\n try {\n const saved = getModuleState('firewall-rules', 'blocklist') as BlockEntry[] | undefined;\n if (Array.isArray(saved)) this.blocklist = saved;\n } catch { /* State DB may not be available */ }\n }\n\n private saveState(): void {\n try { setModuleState('firewall-rules', 'blocklist', this.blocklist); }\n catch { /* State DB may not be available */ }\n }\n\n private logLine(line: string): void {\n try { appendFileSync(PATHS.logFile, `${new Date().toISOString()} ${line}\\n`); }\n catch { /* best-effort */ }\n }\n}\n","/**\n * Opt-in error reporting for the CLI + daemon.\n *\n * Enabled only when `SENTRY_DSN` is set in the environment. Safe to call\n * from both short-lived CLI invocations and the long-running daemon.\n */\n\nlet ready = false;\n// Keep the import lazy so the CLI doesn't pay the Sentry bundle cost when\n// reporting is disabled.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet sentry: any = null;\n\nasync function loadSentry(): Promise<void> {\n if (sentry) return;\n try {\n sentry = await import('@sentry/node');\n } catch {\n sentry = null;\n }\n}\n\nexport async function initTelemetry(context: 'cli' | 'daemon'): Promise<void> {\n if (ready) return;\n const dsn = process.env.SENTRY_DSN;\n if (!dsn) return;\n\n await loadSentry();\n if (!sentry) return;\n\n sentry.init({\n dsn,\n environment: process.env.NODE_ENV || 'production',\n release: process.env.SENTRY_RELEASE,\n serverName: context,\n tracesSampleRate: 0,\n beforeSend(event: Record<string, unknown>) {\n const req = (event as { request?: { headers?: Record<string, string> } }).request;\n if (req?.headers) {\n delete req.headers.authorization;\n delete req.headers.cookie;\n }\n return event;\n },\n });\n\n ready = true;\n}\n\nexport function captureException(err: unknown): void {\n if (!ready || !sentry) return;\n sentry.captureException(err);\n}\n\nexport async function flushTelemetry(timeoutMs = 2000): Promise<void> {\n if (!ready || !sentry) return;\n try { await sentry.flush(timeoutMs); } catch { /* ignore */ }\n}\n","#!/usr/bin/env node\nimport { runDaemon } from './daemon/index.js';\n\nrunDaemon().catch((err) => {\n console.error('threatcrushd failed to start:', err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,sFAAAA,UAAAC,SAAA;AAAA;AACA,QAAM,YAAY;AAClB,QAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA,MAE9B,YAAa,KAAK,UAAU,YAAY;AACtC,cAAM,mBAAmB,KAAK,UAAU,UAAU;AAClD,aAAK,OAAO;AACZ,aAAK,OAAO;AACZ,YAAI,MAAM,kBAAmB,OAAM,kBAAkB,MAAM,YAAW;AAAA,MACxE;AAAA,IACF;AACA,QAAM,QAAN,MAAY;AAAA,MACV,YAAa,QAAQ;AACnB,aAAK,SAAS;AACd,aAAK,MAAM;AACX,aAAK,WAAW;AAChB,aAAK,SAAS;AACd,aAAK,cAAc;AACnB,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AACA,QAAM,SAAN,MAAa;AAAA,MACX,cAAe;AACb,aAAK,MAAM;AACX,aAAK,MAAM;AACX,aAAK,OAAO;AACZ,aAAK,MAAM,CAAC;AACZ,aAAK,MAAM,KAAK;AAChB,aAAK,QAAQ,CAAC;AACd,aAAK,OAAO;AACZ,aAAK,OAAO;AACZ,aAAK,KAAK;AACV,aAAK,QAAQ,IAAI,MAAM,KAAK,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K,SAAS,QAAQ;AAAA,EAAG,CAAC;AACvD,UAAQ,GAAG,WAAW,MAAM;AAAE,SAAK,SAAS,SAAS;AAAA,EAAG,CAAC;AACzD,UAAQ,GAAG,UAAU,MAAM;AAAE,SAAK,SAAS,QAAQ;AAAA,EAAG,CAAC;AAGvD,cAAY,MAAM;AAAA,EAAC,GAAG,KAAK,EAAE;AAC/B;;;AyCtIA,UAAU,EAAE,MAAM,CAAC,QAAQ;AACzB,UAAQ,MAAM,iCAAiC,GAAG;AAClD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["exports","module","exports","module","exports","module","exports","module","exports","module","Date","exports","module","exports","module","exports","module","exports","module","resolve","index","blocksize","exports","module","resolve","exports","module","exports","module","tomlType","str","exports","import_node_fs","import_node_path","import_node_fs","import_node_fs","Database","module","resolve","isRoot","import_node_fs","import_node_path","import_toml","import_node_fs","bus","bus","isRoot","import_node_child_process","import_node_fs","bus","import_node_fs","import_node_readline","bus","import_node_fs","import_node_path","TOML","bus","TOML","SEVERITY_RANK","SEVERITY_RANK","bus","import_node_fs","import_node_path","import_node_os","import_node_fs","import_node_path","import_node_os","process","os","tty","styles","chalk","styles","SEVERITY_COLORS","import_node_os","os","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_path","bus","import_node_fs","import_node_path","import_node_child_process","import_node_net","import_node_fs","DEFAULT_CONFIG","SEVERITY_RANK","bus","readVersion"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js","../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js","../src/daemon/index.ts","../src/daemon/paths.ts","../src/daemon/pidfile.ts","../src/daemon/ipc-server.ts","../src/daemon/event-bus.ts","../src/core/state.ts","../src/daemon/module-host.ts","../src/daemon/watchers/log-watcher.ts","../src/core/log-parser.ts","../src/daemon/watchers/journal-watcher.ts","../src/modules/network-monitor/index.ts","../src/modules/dns-monitor/index.ts","../src/core/config.ts","../src/daemon/alerts/smtp.ts","../src/daemon/alerts/discord.ts","../src/daemon/alerts/pagerduty.ts","../src/daemon/alerts/index.ts","../src/core/cli-config.ts","../src/commands/scan.ts","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js","../src/core/logger.ts","../src/core/run-result.ts","../../../packages/scan/src/types.ts","../../../packages/scan/src/code-rules.ts","../../../packages/scan/src/manifest-rules.ts","../../../packages/scan/src/secret-rules.ts","../../../packages/scan/src/text.ts","../../../packages/scan/src/node/walk.ts","../../../packages/scan/src/node/dependencies.ts","../../../packages/scan/src/node/sarif.ts","../src/commands/pentest.ts","../src/daemon/workers/runs-worker.ts","../src/daemon/rules/engine.ts","../src/daemon/rules/loader.ts","../src/daemon/rules/default-rules.ts","../src/daemon/firewall/adapters.ts","../src/daemon/firewall/remediation.ts","../src/core/telemetry.ts","../src/daemon-entry.ts"],"sourcesContent":["'use strict'\nconst ParserEND = 0x110000\nclass ParserError extends Error {\n /* istanbul ignore next */\n constructor (msg, filename, linenumber) {\n super('[ParserError] ' + msg, filename, linenumber)\n this.name = 'ParserError'\n this.code = 'ParserError'\n if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError)\n }\n}\nclass State {\n constructor (parser) {\n this.parser = parser\n this.buf = ''\n this.returned = null\n this.result = null\n this.resultTable = null\n this.resultArr = null\n }\n}\nclass Parser {\n constructor () {\n this.pos = 0\n this.col = 0\n this.line = 0\n this.obj = {}\n this.ctx = this.obj\n this.stack = []\n this._buf = ''\n this.char = null\n this.ii = 0\n this.state = new State(this.parseStart)\n }\n\n parse (str) {\n /* istanbul ignore next */\n if (str.length === 0 || str.length == null) return\n\n this._buf = String(str)\n this.ii = -1\n this.char = -1\n let getNext\n while (getNext === false || this.nextChar()) {\n getNext = this.runOne()\n }\n this._buf = null\n }\n nextChar () {\n if (this.char === 0x0A) {\n ++this.line\n this.col = -1\n }\n ++this.ii\n this.char = this._buf.codePointAt(this.ii)\n ++this.pos\n ++this.col\n return this.haveBuffer()\n }\n haveBuffer () {\n return this.ii < this._buf.length\n }\n runOne () {\n return this.state.parser.call(this, this.state.returned)\n }\n finish () {\n this.char = ParserEND\n let last\n do {\n last = this.state.parser\n this.runOne()\n } while (this.state.parser !== last)\n\n this.ctx = null\n this.state = null\n this._buf = null\n\n return this.obj\n }\n next (fn) {\n /* istanbul ignore next */\n if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn))\n this.state.parser = fn\n }\n goto (fn) {\n this.next(fn)\n return this.runOne()\n }\n call (fn, returnWith) {\n if (returnWith) this.next(returnWith)\n this.stack.push(this.state)\n this.state = new State(fn)\n }\n callNow (fn, returnWith) {\n this.call(fn, returnWith)\n return this.runOne()\n }\n return (value) {\n /* istanbul ignore next */\n if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'))\n if (value === undefined) value = this.state.buf\n this.state = this.stack.pop()\n this.state.returned = value\n }\n returnNow (value) {\n this.return(value)\n return this.runOne()\n }\n consume () {\n /* istanbul ignore next */\n if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'))\n this.state.buf += this._buf[this.ii]\n }\n error (err) {\n err.line = this.line\n err.col = this.col\n err.pos = this.pos\n return err\n }\n /* istanbul ignore next */\n parseStart () {\n throw new ParserError('Must declare a parseStart method')\n }\n}\nParser.END = ParserEND\nParser.Error = ParserError\nmodule.exports = Parser\n","'use strict'\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nmodule.exports = (d, num) => {\n num = String(num)\n while (num.length < d) num = '0' + num\n return num\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass FloatingDateTime extends Date {\n constructor (value) {\n super(value + 'Z')\n this.isFloating = true\n }\n toISOString () {\n const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n return `${date}T${time}`\n }\n}\n\nmodule.exports = value => {\n const date = new FloatingDateTime(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\nconst DateTime = global.Date\n\nclass Date extends DateTime {\n constructor (value) {\n super(value)\n this.isDate = true\n }\n toISOString () {\n return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass Time extends Date {\n constructor (value) {\n super(`0000-01-01T${value}Z`)\n this.isTime = true\n }\n toISOString () {\n return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Time(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\n/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */\nmodule.exports = makeParserClass(require('./parser.js'))\nmodule.exports.makeParserClass = makeParserClass\n\nclass TomlError extends Error {\n constructor (msg) {\n super(msg)\n this.name = 'TomlError'\n /* istanbul ignore next */\n if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError)\n this.fromTOML = true\n this.wrapped = null\n }\n}\nTomlError.wrap = err => {\n const terr = new TomlError(err.message)\n terr.code = err.code\n terr.wrapped = err\n return terr\n}\nmodule.exports.TomlError = TomlError\n\nconst createDateTime = require('./create-datetime.js')\nconst createDateTimeFloat = require('./create-datetime-float.js')\nconst createDate = require('./create-date.js')\nconst createTime = require('./create-time.js')\n\nconst CTRL_I = 0x09\nconst CTRL_J = 0x0A\nconst CTRL_M = 0x0D\nconst CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL\nconst CHAR_SP = 0x20\nconst CHAR_QUOT = 0x22\nconst CHAR_NUM = 0x23\nconst CHAR_APOS = 0x27\nconst CHAR_PLUS = 0x2B\nconst CHAR_COMMA = 0x2C\nconst CHAR_HYPHEN = 0x2D\nconst CHAR_PERIOD = 0x2E\nconst CHAR_0 = 0x30\nconst CHAR_1 = 0x31\nconst CHAR_7 = 0x37\nconst CHAR_9 = 0x39\nconst CHAR_COLON = 0x3A\nconst CHAR_EQUALS = 0x3D\nconst CHAR_A = 0x41\nconst CHAR_E = 0x45\nconst CHAR_F = 0x46\nconst CHAR_T = 0x54\nconst CHAR_U = 0x55\nconst CHAR_Z = 0x5A\nconst CHAR_LOWBAR = 0x5F\nconst CHAR_a = 0x61\nconst CHAR_b = 0x62\nconst CHAR_e = 0x65\nconst CHAR_f = 0x66\nconst CHAR_i = 0x69\nconst CHAR_l = 0x6C\nconst CHAR_n = 0x6E\nconst CHAR_o = 0x6F\nconst CHAR_r = 0x72\nconst CHAR_s = 0x73\nconst CHAR_t = 0x74\nconst CHAR_u = 0x75\nconst CHAR_x = 0x78\nconst CHAR_z = 0x7A\nconst CHAR_LCUB = 0x7B\nconst CHAR_RCUB = 0x7D\nconst CHAR_LSQB = 0x5B\nconst CHAR_BSOL = 0x5C\nconst CHAR_RSQB = 0x5D\nconst CHAR_DEL = 0x7F\nconst SURROGATE_FIRST = 0xD800\nconst SURROGATE_LAST = 0xDFFF\n\nconst escapes = {\n [CHAR_b]: '\\u0008',\n [CHAR_t]: '\\u0009',\n [CHAR_n]: '\\u000A',\n [CHAR_f]: '\\u000C',\n [CHAR_r]: '\\u000D',\n [CHAR_QUOT]: '\\u0022',\n [CHAR_BSOL]: '\\u005C'\n}\n\nfunction isDigit (cp) {\n return cp >= CHAR_0 && cp <= CHAR_9\n}\nfunction isHexit (cp) {\n return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9)\n}\nfunction isBit (cp) {\n return cp === CHAR_1 || cp === CHAR_0\n}\nfunction isOctit (cp) {\n return (cp >= CHAR_0 && cp <= CHAR_7)\n}\nfunction isAlphaNumQuoteHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_APOS\n || cp === CHAR_QUOT\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nfunction isAlphaNumHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nconst _type = Symbol('type')\nconst _declared = Symbol('declared')\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst defineProperty = Object.defineProperty\nconst descriptor = {configurable: true, enumerable: true, writable: true, value: undefined}\n\nfunction hasKey (obj, key) {\n if (hasOwnProperty.call(obj, key)) return true\n if (key === '__proto__') defineProperty(obj, '__proto__', descriptor)\n return false\n}\n\nconst INLINE_TABLE = Symbol('inline-table')\nfunction InlineTable () {\n return Object.defineProperties({}, {\n [_type]: {value: INLINE_TABLE}\n })\n}\nfunction isInlineTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_TABLE\n}\n\nconst TABLE = Symbol('table')\nfunction Table () {\n return Object.defineProperties({}, {\n [_type]: {value: TABLE},\n [_declared]: {value: false, writable: true}\n })\n}\nfunction isTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === TABLE\n}\n\nconst _contentType = Symbol('content-type')\nconst INLINE_LIST = Symbol('inline-list')\nfunction InlineList (type) {\n return Object.defineProperties([], {\n [_type]: {value: INLINE_LIST},\n [_contentType]: {value: type}\n })\n}\nfunction isInlineList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_LIST\n}\n\nconst LIST = Symbol('list')\nfunction List () {\n return Object.defineProperties([], {\n [_type]: {value: LIST}\n })\n}\nfunction isList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === LIST\n}\n\n// in an eval, to let bundlers not slurp in a util proxy\nlet _custom\ntry {\n const utilInspect = eval(\"require('util').inspect\")\n _custom = utilInspect.custom\n} catch (_) {\n /* eval require not available in transpiled bundle */\n}\n/* istanbul ignore next */\nconst _inspect = _custom || 'inspect'\n\nclass BoxedBigInt {\n constructor (value) {\n try {\n this.value = global.BigInt.asIntN(64, value)\n } catch (_) {\n /* istanbul ignore next */\n this.value = null\n }\n Object.defineProperty(this, _type, {value: INTEGER})\n }\n isNaN () {\n return this.value === null\n }\n /* istanbul ignore next */\n toString () {\n return String(this.value)\n }\n /* istanbul ignore next */\n [_inspect] () {\n return `[BigInt: ${this.toString()}]}`\n }\n valueOf () {\n return this.value\n }\n}\n\nconst INTEGER = Symbol('integer')\nfunction Integer (value) {\n let num = Number(value)\n // -0 is a float thing, not an int thing\n if (Object.is(num, -0)) num = 0\n /* istanbul ignore else */\n if (global.BigInt && !Number.isSafeInteger(num)) {\n return new BoxedBigInt(value)\n } else {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(num), {\n isNaN: {value: function () { return isNaN(this) }},\n [_type]: {value: INTEGER},\n [_inspect]: {value: () => `[Integer: ${value}]`}\n })\n }\n}\nfunction isInteger (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INTEGER\n}\n\nconst FLOAT = Symbol('float')\nfunction Float (value) {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(value), {\n [_type]: {value: FLOAT},\n [_inspect]: {value: () => `[Float: ${value}]`}\n })\n}\nfunction isFloat (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === FLOAT\n}\n\nfunction tomlType (value) {\n const type = typeof value\n if (type === 'object') {\n /* istanbul ignore if */\n if (value === null) return 'null'\n if (value instanceof Date) return 'datetime'\n /* istanbul ignore else */\n if (_type in value) {\n switch (value[_type]) {\n case INLINE_TABLE: return 'inline-table'\n case INLINE_LIST: return 'inline-list'\n /* istanbul ignore next */\n case TABLE: return 'table'\n /* istanbul ignore next */\n case LIST: return 'list'\n case FLOAT: return 'float'\n case INTEGER: return 'integer'\n }\n }\n }\n return type\n}\n\nfunction makeParserClass (Parser) {\n class TOMLParser extends Parser {\n constructor () {\n super()\n this.ctx = this.obj = Table()\n }\n\n /* MATCH HELPER */\n atEndOfWord () {\n return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine()\n }\n atEndOfLine () {\n return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M\n }\n\n parseStart () {\n if (this.char === Parser.END) {\n return null\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseTableOrList)\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (isAlphaNumQuoteHyphen(this.char)) {\n return this.callNow(this.parseAssignStatement)\n } else {\n throw this.error(new TomlError(`Unknown character \"${this.char}\"`))\n }\n }\n\n // HELPER, this strips any whitespace and comments to the end of the line\n // then RETURNS. Last state in a production.\n parseWhitespaceToEOL () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.goto(this.parseComment)\n } else if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n } else {\n throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'))\n }\n }\n\n /* ASSIGNMENT: key = value */\n parseAssignStatement () {\n return this.callNow(this.parseAssign, this.recordAssignStatement)\n }\n recordAssignStatement (kv) {\n let target = this.ctx\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n // unbox our numbers\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseWhitespaceToEOL)\n }\n\n /* ASSSIGNMENT expression, key = value possibly inside an inline table */\n parseAssign () {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n recordAssignKeyword (key) {\n if (this.state.resultTable) {\n this.state.resultTable.push(key)\n } else {\n this.state.resultTable = [key]\n }\n return this.goto(this.parseAssignKeywordPreDot)\n }\n parseAssignKeywordPreDot () {\n if (this.char === CHAR_PERIOD) {\n return this.next(this.parseAssignKeywordPostDot)\n } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.goto(this.parseAssignEqual)\n }\n }\n parseAssignKeywordPostDot () {\n if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n }\n\n parseAssignEqual () {\n if (this.char === CHAR_EQUALS) {\n return this.next(this.parseAssignPreValue)\n } else {\n throw this.error(new TomlError('Invalid character, expected \"=\"'))\n }\n }\n parseAssignPreValue () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseValue, this.recordAssignValue)\n }\n }\n recordAssignValue (value) {\n return this.returnNow({key: this.state.resultTable, value: value})\n }\n\n /* COMMENTS: #...eol */\n parseComment () {\n do {\n if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n }\n } while (this.nextChar())\n }\n\n /* TABLES AND LISTS, [foo] and [[foo]] */\n parseTableOrList () {\n if (this.char === CHAR_LSQB) {\n this.next(this.parseList)\n } else {\n return this.goto(this.parseTable)\n }\n }\n\n /* TABLE [foo.bar.baz] */\n parseTable () {\n this.ctx = this.obj\n return this.goto(this.parseTableNext)\n }\n parseTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseTableMore)\n }\n }\n parseTableMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n } else {\n this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table()\n this.ctx[_declared] = true\n }\n return this.next(this.parseWhitespaceToEOL)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n return this.next(this.parseTableNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* LIST [[a.b.c]] */\n parseList () {\n this.ctx = this.obj\n return this.goto(this.parseListNext)\n }\n parseListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseListMore)\n }\n }\n parseListMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx[keyword] = List()\n }\n if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isList(this.ctx[keyword])) {\n const next = Table()\n this.ctx[keyword].push(next)\n this.ctx = next\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListEnd)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isInlineTable(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline table\"))\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n parseListEnd (keyword) {\n if (this.char === CHAR_RSQB) {\n return this.next(this.parseWhitespaceToEOL)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* VALUE string, number, boolean, inline list, inline object */\n parseValue () {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key without value'))\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseDoubleString)\n } if (this.char === CHAR_APOS) {\n return this.next(this.parseSingleString)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n return this.goto(this.parseNumberSign)\n } else if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseNumberOrDateTime)\n } else if (this.char === CHAR_t || this.char === CHAR_f) {\n return this.goto(this.parseBoolean)\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseInlineList, this.recordValue)\n } else if (this.char === CHAR_LCUB) {\n return this.call(this.parseInlineTable, this.recordValue)\n } else {\n throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'))\n }\n }\n recordValue (value) {\n return this.returnNow(value)\n }\n\n parseInf () {\n if (this.char === CHAR_n) {\n return this.next(this.parseInf2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n parseInf2 () {\n if (this.char === CHAR_f) {\n if (this.state.buf === '-') {\n return this.return(-Infinity)\n } else {\n return this.return(Infinity)\n }\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n\n parseNan () {\n if (this.char === CHAR_a) {\n return this.next(this.parseNan2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n parseNan2 () {\n if (this.char === CHAR_n) {\n return this.return(NaN)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n\n /* KEYS, barewords or basic, literal, or dotted */\n parseKeyword () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseBasicString)\n } else if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralString)\n } else {\n return this.goto(this.parseBareKey)\n }\n }\n\n /* KEYS: barewords */\n parseBareKey () {\n do {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key ended without value'))\n } else if (isAlphaNumHyphen(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 0) {\n throw this.error(new TomlError('Empty bare keys are not allowed'))\n } else {\n return this.returnNow()\n }\n } while (this.nextChar())\n }\n\n /* STRINGS, single quoted (literal) */\n parseSingleString () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiStringMaybe)\n } else {\n return this.goto(this.parseLiteralString)\n }\n }\n parseLiteralString () {\n do {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiStringMaybe () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseLiteralMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseLiteralMultiStringContent)\n } else {\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiStringContent () {\n do {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiEnd () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd2)\n } else {\n this.state.buf += \"'\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiEnd2 () {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else {\n this.state.buf += \"''\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n\n /* STRINGS double quoted */\n parseDoubleString () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiStringMaybe)\n } else {\n return this.goto(this.parseBasicString)\n }\n }\n parseBasicString () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseEscape, this.recordEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n recordEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseBasicString)\n }\n parseMultiStringMaybe () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseMultiStringContent)\n } else {\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiStringContent () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n errorControlCharInString () {\n let displayCode = '\\\\u00'\n if (this.char < 16) {\n displayCode += '0'\n }\n displayCode += this.char.toString(16)\n\n return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))\n }\n recordMultiEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseMultiStringContent)\n }\n parseMultiEnd () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd2)\n } else {\n this.state.buf += '\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEnd2 () {\n if (this.char === CHAR_QUOT) {\n return this.return()\n } else {\n this.state.buf += '\"\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEscape () {\n if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else if (this.char === CHAR_SP || this.char === CTRL_I) {\n return this.next(this.parsePreMultiTrim)\n } else {\n return this.goto(this.parseEscape)\n }\n }\n parsePreMultiTrim () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else {\n throw this.error(new TomlError(\"Can't escape whitespace\"))\n }\n }\n parseMultiTrim () {\n // explicitly whitespace here, END should follow the same path as chars\n if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else {\n return this.returnNow()\n }\n }\n parseEscape () {\n if (this.char in escapes) {\n return this.return(escapes[this.char])\n } else if (this.char === CHAR_u) {\n return this.call(this.parseSmallUnicode, this.parseUnicodeReturn)\n } else if (this.char === CHAR_U) {\n return this.call(this.parseLargeUnicode, this.parseUnicodeReturn)\n } else {\n throw this.error(new TomlError('Unknown escape character: ' + this.char))\n }\n }\n parseUnicodeReturn (char) {\n try {\n const codePoint = parseInt(char, 16)\n if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {\n throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'))\n }\n return this.returnNow(String.fromCodePoint(codePoint))\n } catch (err) {\n throw this.error(TomlError.wrap(err))\n }\n }\n parseSmallUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 4) return this.return()\n }\n }\n parseLargeUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 8) return this.return()\n }\n }\n\n /* NUMBERS */\n parseNumberSign () {\n this.consume()\n return this.next(this.parseMaybeSignedInfOrNan)\n }\n parseMaybeSignedInfOrNan () {\n if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else {\n return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart)\n }\n }\n parseNumberIntegerStart () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberIntegerExponentOrDecimal)\n } else {\n return this.goto(this.parseNumberInteger)\n }\n }\n parseNumberIntegerExponentOrDecimal () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseNumberInteger () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseNoUnder () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNoUnderHexOctBinLiteral () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNumberFloat () {\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n parseNumberExponentSign () {\n if (isDigit(this.char)) {\n return this.goto(this.parseNumberExponent)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.call(this.parseNoUnder, this.parseNumberExponent)\n } else {\n throw this.error(new TomlError('Unexpected character, expected -, + or digit'))\n }\n }\n parseNumberExponent () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n\n /* NUMBERS or DATETIMES */\n parseNumberOrDateTime () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberBaseOrDateTime)\n } else {\n return this.goto(this.parseNumberOrDateTimeOnly)\n }\n }\n parseNumberOrDateTimeOnly () {\n // note, if two zeros are in a row then it MUST be a date\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length > 4) this.next(this.parseNumberInteger)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseDateTimeOnly () {\n if (this.state.buf.length < 4) {\n if (isDigit(this.char)) {\n return this.consume()\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n throw this.error(new TomlError('Expected digit while parsing year part of a date'))\n }\n } else {\n if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else {\n throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'))\n }\n }\n }\n parseNumberBaseOrDateTime () {\n if (this.char === CHAR_b) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin)\n } else if (this.char === CHAR_o) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct)\n } else if (this.char === CHAR_x) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex)\n } else if (this.char === CHAR_PERIOD) {\n return this.goto(this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseDateTimeOnly)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseIntegerHex () {\n if (isHexit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerOct () {\n if (isOctit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerBin () {\n if (isBit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n\n /* DATETIME */\n parseDateTime () {\n // we enter here having just consumed the year and about to consume the hyphen\n if (this.state.buf.length < 4) {\n throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateMonth)\n }\n parseDateMonth () {\n if (this.char === CHAR_HYPHEN) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateDay)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseDateDay () {\n if (this.char === CHAR_T || this.char === CHAR_SP) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseStartTimeHour)\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result + '-' + this.state.buf))\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseStartTimeHour () {\n if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result))\n } else {\n return this.goto(this.parseTimeHour)\n }\n }\n parseTimeHour () {\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result += 'T' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeMin)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeZoneOrFraction)\n }\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n\n parseOnlyTimeHour () {\n /* istanbul ignore else */\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeMin)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n return this.next(this.parseOnlyTimeFractionMaybe)\n }\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeFractionMaybe () {\n this.state.result += ':' + this.state.buf\n if (this.char === CHAR_PERIOD) {\n this.state.buf = ''\n this.next(this.parseOnlyTimeFraction)\n } else {\n return this.return(createTime(this.state.result))\n }\n }\n parseOnlyTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.atEndOfWord()) {\n if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'))\n return this.returnNow(createTime(this.state.result + '.' + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n\n parseTimeZoneOrFraction () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n this.next(this.parseDateTimeFraction)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseDateTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 1) {\n throw this.error(new TomlError('Expected digit in milliseconds'))\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseTimeZoneHour () {\n if (isDigit(this.char)) {\n this.consume()\n // FIXME: No more regexps\n if (/\\d\\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n parseTimeZoneSep () {\n if (this.char === CHAR_COLON) {\n this.consume()\n this.next(this.parseTimeZoneMin)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected colon'))\n }\n }\n parseTimeZoneMin () {\n if (isDigit(this.char)) {\n this.consume()\n if (/\\d\\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n\n /* BOOLEAN */\n parseBoolean () {\n /* istanbul ignore else */\n if (this.char === CHAR_t) {\n this.consume()\n return this.next(this.parseTrue_r)\n } else if (this.char === CHAR_f) {\n this.consume()\n return this.next(this.parseFalse_a)\n }\n }\n parseTrue_r () {\n if (this.char === CHAR_r) {\n this.consume()\n return this.next(this.parseTrue_u)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_u () {\n if (this.char === CHAR_u) {\n this.consume()\n return this.next(this.parseTrue_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_e () {\n if (this.char === CHAR_e) {\n return this.return(true)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_a () {\n if (this.char === CHAR_a) {\n this.consume()\n return this.next(this.parseFalse_l)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_l () {\n if (this.char === CHAR_l) {\n this.consume()\n return this.next(this.parseFalse_s)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_s () {\n if (this.char === CHAR_s) {\n this.consume()\n return this.next(this.parseFalse_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_e () {\n if (this.char === CHAR_e) {\n return this.return(false)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n /* INLINE LISTS */\n parseInlineList () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_RSQB) {\n return this.return(this.state.resultArr || InlineList())\n } else {\n return this.callNow(this.parseValue, this.recordInlineListValue)\n }\n }\n recordInlineListValue (value) {\n if (this.state.resultArr) {\n const listType = this.state.resultArr[_contentType]\n const valueType = tomlType(value)\n if (listType !== valueType) {\n throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))\n }\n } else {\n this.state.resultArr = InlineList(tomlType(value))\n }\n if (isFloat(value) || isInteger(value)) {\n // unbox now that we've verified they're ok\n this.state.resultArr.push(value.valueOf())\n } else {\n this.state.resultArr.push(value)\n }\n return this.goto(this.parseInlineListNext)\n }\n parseInlineListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineList)\n } else if (this.char === CHAR_RSQB) {\n return this.goto(this.parseInlineList)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n\n /* INLINE TABLE */\n parseInlineTable () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_RCUB) {\n return this.return(this.state.resultTable || InlineTable())\n } else {\n if (!this.state.resultTable) this.state.resultTable = InlineTable()\n return this.callNow(this.parseAssign, this.recordInlineTableValue)\n }\n }\n recordInlineTableValue (kv) {\n let target = this.state.resultTable\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseInlineTableNext)\n }\n parseInlineTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineTable)\n } else if (this.char === CHAR_RCUB) {\n return this.goto(this.parseInlineTable)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n }\n return TOMLParser\n}\n","'use strict'\nmodule.exports = prettyError\n\nfunction prettyError (err, buf) {\n /* istanbul ignore if */\n if (err.pos == null || err.line == null) return err\n let msg = err.message\n msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\\n`\n\n /* istanbul ignore else */\n if (buf && buf.split) {\n const lines = buf.split(/\\n/)\n const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length\n let linePadding = ' '\n while (linePadding.length < lineNumWidth) linePadding += ' '\n for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {\n let lineNum = String(ii + 1)\n if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum\n if (err.line === ii) {\n msg += lineNum + '> ' + lines[ii] + '\\n'\n msg += linePadding + ' '\n for (let hh = 0; hh < err.col; ++hh) {\n msg += ' '\n }\n msg += '^\\n'\n } else {\n msg += lineNum + ': ' + lines[ii] + '\\n'\n }\n }\n }\n err.message = msg + '\\n'\n return err\n}\n","'use strict'\nmodule.exports = parseString\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseString (str) {\n if (global.Buffer && global.Buffer.isBuffer(str)) {\n str = str.toString('utf8')\n }\n const parser = new TOMLParser()\n try {\n parser.parse(str)\n return parser.finish()\n } catch (err) {\n throw prettyError(err, str)\n }\n}\n","'use strict'\nmodule.exports = parseAsync\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseAsync (str, opts) {\n if (!opts) opts = {}\n const index = 0\n const blocksize = opts.blocksize || 40960\n const parser = new TOMLParser()\n return new Promise((resolve, reject) => {\n setImmediate(parseAsyncNext, index, blocksize, resolve, reject)\n })\n function parseAsyncNext (index, blocksize, resolve, reject) {\n if (index >= str.length) {\n try {\n return resolve(parser.finish())\n } catch (err) {\n return reject(prettyError(err, str))\n }\n }\n try {\n parser.parse(str.slice(index, index + blocksize))\n setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject)\n } catch (err) {\n reject(prettyError(err, str))\n }\n }\n}\n","'use strict'\nmodule.exports = parseStream\n\nconst stream = require('stream')\nconst TOMLParser = require('./lib/toml-parser.js')\n\nfunction parseStream (stm) {\n if (stm) {\n return parseReadable(stm)\n } else {\n return parseTransform(stm)\n }\n}\n\nfunction parseReadable (stm) {\n const parser = new TOMLParser()\n stm.setEncoding('utf8')\n return new Promise((resolve, reject) => {\n let readable\n let ended = false\n let errored = false\n function finish () {\n ended = true\n if (readable) return\n try {\n resolve(parser.finish())\n } catch (err) {\n reject(err)\n }\n }\n function error (err) {\n errored = true\n reject(err)\n }\n stm.once('end', finish)\n stm.once('error', error)\n readNext()\n\n function readNext () {\n readable = true\n let data\n while ((data = stm.read()) !== null) {\n try {\n parser.parse(data)\n } catch (err) {\n return error(err)\n }\n }\n readable = false\n /* istanbul ignore if */\n if (ended) return finish()\n /* istanbul ignore if */\n if (errored) return\n stm.once('readable', readNext)\n }\n })\n}\n\nfunction parseTransform () {\n const parser = new TOMLParser()\n return new stream.Transform({\n objectMode: true,\n transform (chunk, encoding, cb) {\n try {\n parser.parse(chunk.toString(encoding))\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n },\n flush (cb) {\n try {\n this.push(parser.finish())\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n }\n })\n}\n","'use strict'\nmodule.exports = require('./parse-string.js')\nmodule.exports.async = require('./parse-async.js')\nmodule.exports.stream = require('./parse-stream.js')\nmodule.exports.prettyError = require('./parse-pretty-error.js')\n","'use strict'\nmodule.exports = stringify\nmodule.exports.value = stringifyInline\n\nfunction stringify (obj) {\n if (obj === null) throw typeError('null')\n if (obj === void (0)) throw typeError('undefined')\n if (typeof obj !== 'object') throw typeError(typeof obj)\n\n if (typeof obj.toJSON === 'function') obj = obj.toJSON()\n if (obj == null) return null\n const type = tomlType(obj)\n if (type !== 'table') throw typeError(type)\n return stringifyObject('', '', obj)\n}\n\nfunction typeError (type) {\n return new Error('Can only stringify objects, not ' + type)\n}\n\nfunction arrayOneTypeError () {\n return new Error(\"Array values can't have mixed types\")\n}\n\nfunction getInlineKeys (obj) {\n return Object.keys(obj).filter(key => isInline(obj[key]))\n}\nfunction getComplexKeys (obj) {\n return Object.keys(obj).filter(key => !isInline(obj[key]))\n}\n\nfunction toJSON (obj) {\n let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}\n for (let prop of Object.keys(obj)) {\n if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {\n nobj[prop] = obj[prop].toJSON()\n } else {\n nobj[prop] = obj[prop]\n }\n }\n return nobj\n}\n\nfunction stringifyObject (prefix, indent, obj) {\n obj = toJSON(obj)\n var inlineKeys\n var complexKeys\n inlineKeys = getInlineKeys(obj)\n complexKeys = getComplexKeys(obj)\n var result = []\n var inlineIndent = indent || ''\n inlineKeys.forEach(key => {\n var type = tomlType(obj[key])\n if (type !== 'undefined' && type !== 'null') {\n result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))\n }\n })\n if (result.length > 0) result.push('')\n var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''\n complexKeys.forEach(key => {\n result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))\n })\n return result.join('\\n')\n}\n\nfunction isInline (value) {\n switch (tomlType(value)) {\n case 'undefined':\n case 'null':\n case 'integer':\n case 'nan':\n case 'float':\n case 'boolean':\n case 'string':\n case 'datetime':\n return true\n case 'array':\n return value.length === 0 || tomlType(value[0]) !== 'table'\n case 'table':\n return Object.keys(value).length === 0\n /* istanbul ignore next */\n default:\n return false\n }\n}\n\nfunction tomlType (value) {\n if (value === undefined) {\n return 'undefined'\n } else if (value === null) {\n return 'null'\n /* eslint-disable valid-typeof */\n } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {\n return 'integer'\n } else if (typeof value === 'number') {\n return 'float'\n } else if (typeof value === 'boolean') {\n return 'boolean'\n } else if (typeof value === 'string') {\n return 'string'\n } else if ('toISOString' in value) {\n return isNaN(value) ? 'undefined' : 'datetime'\n } else if (Array.isArray(value)) {\n return 'array'\n } else {\n return 'table'\n }\n}\n\nfunction stringifyKey (key) {\n var keyStr = String(key)\n if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {\n return keyStr\n } else {\n return stringifyBasicString(keyStr)\n }\n}\n\nfunction stringifyBasicString (str) {\n return '\"' + escapeString(str).replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction stringifyLiteralString (str) {\n return \"'\" + str + \"'\"\n}\n\nfunction numpad (num, str) {\n while (str.length < num) str = '0' + str\n return str\n}\n\nfunction escapeString (str) {\n return str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/[\\b]/g, '\\\\b')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\f/g, '\\\\f')\n .replace(/\\r/g, '\\\\r')\n /* eslint-disable no-control-regex */\n .replace(/([\\u0000-\\u001f\\u007f])/, c => '\\\\u' + numpad(4, c.codePointAt(0).toString(16)))\n /* eslint-enable no-control-regex */\n}\n\nfunction stringifyMultilineString (str) {\n let escaped = str.split(/\\n/).map(str => {\n return escapeString(str).replace(/\"(?=\"\")/g, '\\\\\"')\n }).join('\\n')\n if (escaped.slice(-1) === '\"') escaped += '\\\\\\n'\n return '\"\"\"\\n' + escaped + '\"\"\"'\n}\n\nfunction stringifyAnyInline (value, multilineOk) {\n let type = tomlType(value)\n if (type === 'string') {\n if (multilineOk && /\\n/.test(value)) {\n type = 'string-multiline'\n } else if (!/[\\b\\t\\n\\f\\r']/.test(value) && /\"/.test(value)) {\n type = 'string-literal'\n }\n }\n return stringifyInline(value, type)\n}\n\nfunction stringifyInline (value, type) {\n /* istanbul ignore if */\n if (!type) type = tomlType(value)\n switch (type) {\n case 'string-multiline':\n return stringifyMultilineString(value)\n case 'string':\n return stringifyBasicString(value)\n case 'string-literal':\n return stringifyLiteralString(value)\n case 'integer':\n return stringifyInteger(value)\n case 'float':\n return stringifyFloat(value)\n case 'boolean':\n return stringifyBoolean(value)\n case 'datetime':\n return stringifyDatetime(value)\n case 'array':\n return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))\n case 'table':\n return stringifyInlineTable(value)\n /* istanbul ignore next */\n default:\n throw typeError(type)\n }\n}\n\nfunction stringifyInteger (value) {\n /* eslint-disable security/detect-unsafe-regex */\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, '_')\n}\n\nfunction stringifyFloat (value) {\n if (value === Infinity) {\n return 'inf'\n } else if (value === -Infinity) {\n return '-inf'\n } else if (Object.is(value, NaN)) {\n return 'nan'\n } else if (Object.is(value, -0)) {\n return '-0.0'\n }\n var chunks = String(value).split('.')\n var int = chunks[0]\n var dec = chunks[1] || 0\n return stringifyInteger(int) + '.' + dec\n}\n\nfunction stringifyBoolean (value) {\n return String(value)\n}\n\nfunction stringifyDatetime (value) {\n return value.toISOString()\n}\n\nfunction isNumber (type) {\n return type === 'float' || type === 'integer'\n}\nfunction arrayType (values) {\n var contentType = tomlType(values[0])\n if (values.every(_ => tomlType(_) === contentType)) return contentType\n // mixed integer/float, emit as floats\n if (values.every(_ => isNumber(tomlType(_)))) return 'float'\n return 'mixed'\n}\nfunction validateArray (values) {\n const type = arrayType(values)\n if (type === 'mixed') {\n throw arrayOneTypeError()\n }\n return type\n}\n\nfunction stringifyInlineArray (values) {\n values = toJSON(values)\n const type = validateArray(values)\n var result = '['\n var stringified = values.map(_ => stringifyInline(_, type))\n if (stringified.join(', ').length > 60 || /\\n/.test(stringified)) {\n result += '\\n ' + stringified.join(',\\n ') + '\\n'\n } else {\n result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')\n }\n return result + ']'\n}\n\nfunction stringifyInlineTable (value) {\n value = toJSON(value)\n var result = []\n Object.keys(value).forEach(key => {\n result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))\n })\n return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'\n}\n\nfunction stringifyComplex (prefix, indent, key, value) {\n var valueType = tomlType(value)\n /* istanbul ignore else */\n if (valueType === 'array') {\n return stringifyArrayOfTables(prefix, indent, key, value)\n } else if (valueType === 'table') {\n return stringifyComplexTable(prefix, indent, key, value)\n } else {\n throw typeError(valueType)\n }\n}\n\nfunction stringifyArrayOfTables (prefix, indent, key, values) {\n values = toJSON(values)\n validateArray(values)\n var firstValueType = tomlType(values[0])\n /* istanbul ignore if */\n if (firstValueType !== 'table') throw typeError(firstValueType)\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n values.forEach(table => {\n if (result.length > 0) result += '\\n'\n result += indent + '[[' + fullKey + ']]\\n'\n result += stringifyObject(fullKey + '.', indent, table)\n })\n return result\n}\n\nfunction stringifyComplexTable (prefix, indent, key, value) {\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n if (getInlineKeys(value).length > 0) {\n result += indent + '[' + fullKey + ']\\n'\n }\n return result + stringifyObject(fullKey + '.', indent, value)\n}\n","'use strict'\nexports.parse = require('./parse.js')\nexports.stringify = require('./stringify.js')\n","import { appendFileSync, existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PATHS, ensureRuntimeDirs } from './paths.js';\nimport { findRunningDaemon, removePidFile, writePidFile } from './pidfile.js';\nimport { IpcServer } from './ipc-server.js';\nimport { ModuleHost } from './module-host.js';\nimport { AlertDispatcher } from './alerts/index.js';\nimport { RunsWorker } from './workers/runs-worker.js';\nimport { RuleEngine } from './rules/engine.js';\nimport { loadAllRules } from './rules/loader.js';\nimport { detectFirewallAdapter } from './firewall/adapters.js';\nimport { RemediationManager } from './firewall/remediation.js';\nimport { bus } from './event-bus.js';\nimport { initStateDB, closeDB } from '../core/state.js';\nimport { loadConfig } from '../core/config.js';\nimport { captureException, flushTelemetry, initTelemetry } from '../core/telemetry.js';\nimport type { ThreatEvent } from '../types/events.js';\n\nfunction readVersion(): string {\n try {\n const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));\n return pkg.version || '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction logLine(line: string): void {\n try {\n appendFileSync(PATHS.logFile, `${new Date().toISOString()} ${line}\\n`);\n } catch {\n // best-effort\n }\n}\n\nexport async function runDaemon(): Promise<void> {\n if (findRunningDaemon()) {\n console.error(`threatcrushd already running (pid file at ${PATHS.pidFile}).`);\n process.exit(1);\n }\n\n ensureRuntimeDirs();\n writePidFile();\n\n await initTelemetry('daemon');\n process.on('uncaughtException', (err) => {\n logLine(`[daemon] uncaughtException: ${err.message}`);\n captureException(err);\n });\n process.on('unhandledRejection', (reason) => {\n logLine(`[daemon] unhandledRejection: ${String(reason)}`);\n captureException(reason);\n });\n\n const version = readVersion();\n logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);\n\n try {\n initStateDB(PATHS.stateDb);\n } catch (err) {\n logLine(`[daemon] state db unavailable: ${(err as Error).message}`);\n }\n\n const config = loadConfig(existsSync(PATHS.configFile) ? PATHS.configFile : undefined);\n\n bus.on('event', (event: ThreatEvent) => {\n logLine(`[event] ${event.severity} ${event.module} ${event.message}`);\n });\n\n const moduleHost = new ModuleHost(bus);\n await moduleHost.start();\n\n // Detection rule engine (PRD 01)\n const ruleEngine = new RuleEngine((detection) => {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'rule-engine',\n category: (detection.raw_metadata?.category as any) || 'system',\n severity: detection.severity,\n message: `[DETECTION] ${detection.title}`,\n source_ip: detection.source_ip,\n details: {\n rule_id: detection.rule_id,\n username: detection.username,\n ...detection.raw_metadata,\n },\n };\n bus.publish(event);\n });\n ruleEngine.loadRules(loadAllRules());\n bus.on('event', (event) => {\n if (event.module !== 'rule-engine') ruleEngine.evaluate(event);\n });\n logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);\n setInterval(() => ruleEngine.cleanup(), 300_000);\n\n // Firewall auto-remediation (PRD 02)\n const firewallAdapter = detectFirewallAdapter();\n const remediation = new RemediationManager(firewallAdapter, bus, (config as any).remediation);\n bus.on('event', (event) => {\n if (event.module !== 'firewall-rules') {\n void remediation.handleDetection(event);\n }\n });\n logLine(`[daemon] firewall remediation active (backend=${firewallAdapter.name}, dry_run=${(config as any).remediation?.dry_run ?? true})`);\n\n new AlertDispatcher(bus, config);\n\n const runsWorker = new RunsWorker(bus);\n try {\n await runsWorker.start();\n } catch (err) {\n logLine(`[daemon] runs-worker failed to start: ${(err as Error).message}`);\n }\n\n const ipc = new IpcServer(version, moduleHost);\n await ipc.start();\n logLine(`[daemon] ipc listening on ${PATHS.socket}`);\n\n const shutdown = async (signal: string) => {\n logLine(`[daemon] received ${signal}, shutting down`);\n try { remediation.stop(); } catch {}\n try { runsWorker.stop(); } catch {}\n try { await moduleHost.stop(); } catch {}\n try { await ipc.stop(); } catch {}\n try { closeDB(); } catch {}\n try { await flushTelemetry(); } catch {}\n removePidFile();\n process.exit(0);\n };\n\n process.on('SIGINT', () => { void shutdown('SIGINT'); });\n process.on('SIGTERM', () => { void shutdown('SIGTERM'); });\n process.on('SIGHUP', () => { void shutdown('SIGHUP'); });\n\n // keep-alive\n setInterval(() => {}, 1 << 30);\n}\n\n// Note: auto-boot is handled by `src/daemon-entry.ts` so that importing this\n// module from the CLI bundle never accidentally starts a daemon.\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nfunction isRoot(): boolean {\n return (\n process.platform === 'linux' &&\n typeof process.getuid === 'function' &&\n process.getuid() === 0\n );\n}\n\nconst userBase = join(homedir(), '.threatcrush');\n\nconst SYSTEM_PATHS = {\n mode: 'system' as const,\n configDir: '/etc/threatcrush',\n configFile: '/etc/threatcrush/threatcrushd.conf',\n confD: '/etc/threatcrush/threatcrushd.conf.d',\n moduleDir: '/etc/threatcrush/modules',\n logDir: '/var/log/threatcrush',\n logFile: '/var/log/threatcrush/threatcrushd.log',\n stateDir: '/var/lib/threatcrush',\n stateDb: '/var/lib/threatcrush/state.db',\n runDir: '/var/run/threatcrush',\n pidFile: '/var/run/threatcrush/threatcrushd.pid',\n socket: '/var/run/threatcrush/threatcrushd.sock',\n};\n\nconst USER_PATHS = {\n mode: 'user' as const,\n configDir: userBase,\n configFile: join(userBase, 'threatcrushd.conf'),\n confD: join(userBase, 'threatcrushd.conf.d'),\n moduleDir: join(userBase, 'modules'),\n logDir: join(userBase, 'logs'),\n logFile: join(userBase, 'logs', 'threatcrushd.log'),\n stateDir: join(userBase, 'state'),\n stateDb: join(userBase, 'state', 'state.db'),\n runDir: join(userBase, 'run'),\n pidFile: join(userBase, 'run', 'threatcrushd.pid'),\n socket: join(userBase, 'run', 'threatcrushd.sock'),\n};\n\n// System paths (config/log/state/run under /etc and /var) are root-owned, so we\n// only run in system mode when actually root. Choosing system mode because\n// /etc/threatcrush happened to be writable, or because a stale system socket\n// existed, made `threatcrush start` as a normal user crash with EACCES trying\n// to open /var/log/threatcrush/threatcrushd.log. A non-root user always runs a\n// self-contained daemon under ~/.threatcrush instead.\nexport const PATHS = isRoot() ? SYSTEM_PATHS : USER_PATHS;\n\n// A non-root client command (status/stop/logs/tail) should still be able to\n// reach a daemon that root started. Prefer this process's own socket, but fall\n// back to the other mode's socket when only that one is present.\nexport function resolveClientSocket(): string {\n if (existsSync(PATHS.socket)) return PATHS.socket;\n const other = PATHS.mode === 'system' ? USER_PATHS.socket : SYSTEM_PATHS.socket;\n if (existsSync(other)) return other;\n return PATHS.socket;\n}\n\nexport function ensureRuntimeDirs(): void {\n for (const dir of [PATHS.configDir, PATHS.confD, PATHS.moduleDir, PATHS.logDir, PATHS.stateDir, PATHS.runDir]) {\n try {\n mkdirSync(dir, { recursive: true });\n } catch {\n // best-effort\n }\n }\n}\n","import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { PATHS, ensureRuntimeDirs } from './paths.js';\n\nexport function writePidFile(): void {\n ensureRuntimeDirs();\n writeFileSync(PATHS.pidFile, String(process.pid), 'utf-8');\n}\n\nexport function readPidFile(): number | null {\n if (!existsSync(PATHS.pidFile)) return null;\n const raw = readFileSync(PATHS.pidFile, 'utf-8').trim();\n const pid = parseInt(raw, 10);\n return Number.isFinite(pid) ? pid : null;\n}\n\nexport function removePidFile(): void {\n try {\n if (existsSync(PATHS.pidFile)) unlinkSync(PATHS.pidFile);\n } catch {\n // ignore\n }\n}\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means the process exists but the current user can't signal it\n // (common: a non-root client checking on a system-mode daemon running as\n // root). Only ESRCH means the process is actually gone.\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'EPERM';\n }\n}\n\nexport function findRunningDaemon(): number | null {\n const pid = readPidFile();\n if (pid && isProcessAlive(pid)) return pid;\n if (pid) removePidFile();\n return null;\n}\n","import { createServer, Server, Socket } from 'node:net';\nimport { existsSync, unlinkSync } from 'node:fs';\nimport type { ThreatEvent } from '../types/events.js';\nimport { PATHS } from './paths.js';\nimport { bus } from './event-bus.js';\nimport { getRecentEvents, getTopSources, getEventCount, getThreatCount } from '../core/state.js';\nimport type {\n IpcRequest,\n IpcResponse,\n IpcPush,\n DaemonStatusReply,\n} from './ipc-protocol.js';\nimport type { ModuleHost } from './module-host.js';\n\ninterface ClientState {\n id: number;\n socket: Socket;\n buffer: string;\n subscriptions: Set<'event' | 'module'>;\n}\n\nexport class IpcServer {\n private server: Server | null = null;\n private clients = new Map<number, ClientState>();\n private nextClientId = 1;\n private startedAt = new Date();\n private counters = { events: 0, threats: 0, alerts: 0 };\n\n constructor(\n private version: string,\n private moduleHost: ModuleHost,\n ) {\n bus.on('event', (event: ThreatEvent) => {\n this.counters.events++;\n if (event.severity === 'medium' || event.severity === 'high' || event.severity === 'critical') {\n this.counters.threats++;\n }\n this.broadcast({ push: 'event', payload: event }, 'event');\n });\n bus.on('alert', () => {\n this.counters.alerts++;\n });\n bus.on('module', (info) => {\n this.broadcast({ push: 'module', payload: info }, 'module');\n });\n }\n\n async start(): Promise<void> {\n if (existsSync(PATHS.socket)) {\n try { unlinkSync(PATHS.socket); } catch {}\n }\n return new Promise((resolve, reject) => {\n this.server = createServer((sock) => this.handleClient(sock));\n this.server.on('error', reject);\n this.server.listen(PATHS.socket, () => {\n const nodeFs = require('node:fs') as typeof import('node:fs');\n try { nodeFs.chmodSync(PATHS.socket, 0o660); } catch {}\n // When the daemon runs as root (system mode under systemd), regroup\n // the socket to `adm` so users in that group can talk to the daemon\n // without sudo. We use this group because it's the same one that\n // already governs read access to /var/log/{auth,syslog,nginx} — the\n // intent is \"people who can already inspect logs can talk to the\n // agent that watches them.\"\n const isRoot = process.platform === 'linux'\n && typeof process.getuid === 'function'\n && process.getuid() === 0;\n if (isRoot) {\n try {\n const { gid } = nodeFs.statSync('/var/log/auth.log');\n nodeFs.chownSync(PATHS.socket, 0, gid);\n } catch {\n // adm group not present, or /var/log/auth.log missing — leave as root:root\n }\n }\n resolve();\n });\n });\n }\n\n async stop(): Promise<void> {\n for (const c of this.clients.values()) {\n try { c.socket.destroy(); } catch {}\n }\n this.clients.clear();\n return new Promise((resolve) => {\n if (!this.server) {\n try { if (existsSync(PATHS.socket)) unlinkSync(PATHS.socket); } catch {}\n return resolve();\n }\n this.server.close(() => {\n try { if (existsSync(PATHS.socket)) unlinkSync(PATHS.socket); } catch {}\n resolve();\n });\n });\n }\n\n private handleClient(socket: Socket): void {\n const id = this.nextClientId++;\n const state: ClientState = { id, socket, buffer: '', subscriptions: new Set() };\n this.clients.set(id, state);\n\n socket.setEncoding('utf-8');\n socket.on('data', (chunk) => {\n state.buffer += chunk.toString();\n let idx;\n while ((idx = state.buffer.indexOf('\\n')) >= 0) {\n const line = state.buffer.slice(0, idx);\n state.buffer = state.buffer.slice(idx + 1);\n if (!line.trim()) continue;\n this.handleLine(state, line).catch((err) => {\n this.send(state, { id: 0, ok: false, error: String(err?.message || err) });\n });\n }\n });\n\n socket.on('close', () => { this.clients.delete(id); });\n socket.on('error', () => { this.clients.delete(id); });\n }\n\n private async handleLine(client: ClientState, line: string): Promise<void> {\n let req: IpcRequest;\n try {\n req = JSON.parse(line) as IpcRequest;\n } catch {\n return this.send(client, { id: 0, ok: false, error: 'invalid json' });\n }\n\n switch (req.method) {\n case 'ping':\n return this.send(client, { id: req.id, ok: true, result: 'pong' });\n\n case 'status': {\n const status: DaemonStatusReply = {\n pid: process.pid,\n startedAt: this.startedAt.toISOString(),\n uptimeSeconds: Math.floor((Date.now() - this.startedAt.getTime()) / 1000),\n version: this.version,\n mode: PATHS.mode,\n paths: {\n config: PATHS.configFile,\n log: PATHS.logFile,\n state: PATHS.stateDb,\n socket: PATHS.socket,\n },\n modules: this.moduleHost.summary(),\n counters: { ...this.counters },\n };\n return this.send(client, { id: req.id, ok: true, result: status });\n }\n\n case 'recent_events': {\n const limit = req.params?.limit ?? 50;\n const events = getRecentEvents(limit);\n return this.send(client, { id: req.id, ok: true, result: events });\n }\n\n case 'top_sources': {\n const limit = req.params?.limit ?? 10;\n return this.send(client, { id: req.id, ok: true, result: getTopSources(limit) });\n }\n\n case 'counters': {\n return this.send(client, {\n id: req.id,\n ok: true,\n result: {\n total: getEventCount(),\n threats: getThreatCount(),\n last24h: getEventCount(new Date(Date.now() - 86400000)),\n threats24h: getThreatCount(new Date(Date.now() - 86400000)),\n },\n });\n }\n\n case 'module_list':\n return this.send(client, { id: req.id, ok: true, result: this.moduleHost.summary() });\n\n case 'subscribe':\n for (const ch of req.params.channels) client.subscriptions.add(ch);\n return this.send(client, { id: req.id, ok: true, result: { subscribed: [...client.subscriptions] } });\n\n case 'shutdown':\n this.send(client, { id: req.id, ok: true, result: 'shutting down' });\n setTimeout(() => process.emit('SIGTERM' as NodeJS.Signals), 50);\n return;\n }\n }\n\n private send(client: ClientState, msg: IpcResponse | IpcPush): void {\n try {\n client.socket.write(JSON.stringify(msg) + '\\n');\n } catch {\n // client gone\n }\n }\n\n private broadcast(msg: IpcPush, channel: 'event' | 'module'): void {\n for (const client of this.clients.values()) {\n if (!client.subscriptions.has(channel)) continue;\n this.send(client, msg);\n }\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { ThreatEvent } from '../types/events.js';\n\nexport interface DaemonEvents {\n event: (event: ThreatEvent) => void;\n alert: (event: ThreatEvent) => void;\n module: (info: { name: string; status: string; detail?: string }) => void;\n}\n\nexport class EventBus extends EventEmitter {\n publish(event: ThreatEvent): void {\n this.emit('event', event);\n if (event.severity === 'high' || event.severity === 'critical') {\n this.emit('alert', event);\n }\n }\n\n announceModule(name: string, status: string, detail?: string): void {\n this.emit('module', { name, status, detail });\n }\n}\n\nexport const bus = new EventBus();\nbus.setMaxListeners(50);\n","import Database from 'better-sqlite3';\nimport type { ThreatEvent } from '../types/events.js';\n\nlet db: Database.Database | null = null;\nlet dbUnavailable = false;\n\nexport function isStateDbAvailable(): boolean {\n return db !== null;\n}\n\nexport function initStateDB(dbPath: string = '/var/lib/threatcrush/state.db'): Database.Database {\n if (db) return db;\n if (dbUnavailable) {\n throw new Error('state db unavailable (previous init failed)');\n }\n\n try {\n try {\n db = new Database(dbPath);\n } catch {\n // Fall back to in-memory if we can't write to the path\n db = new Database(':memory:');\n }\n } catch (err) {\n // Native binding missing or unloadable — mark DB unavailable so callers\n // can degrade gracefully instead of throwing on every IPC request.\n dbUnavailable = true;\n throw err;\n }\n\n db.pragma('journal_mode = WAL');\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n timestamp TEXT NOT NULL,\n module TEXT NOT NULL,\n category TEXT NOT NULL,\n severity TEXT NOT NULL,\n message TEXT NOT NULL,\n source_ip TEXT,\n details TEXT\n );\n\n CREATE TABLE IF NOT EXISTS module_state (\n module TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT,\n PRIMARY KEY (module, key)\n );\n\n CREATE TABLE IF NOT EXISTS stats (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);\n CREATE INDEX IF NOT EXISTS idx_events_module ON events(module);\n CREATE INDEX IF NOT EXISTS idx_events_severity ON events(severity);\n CREATE INDEX IF NOT EXISTS idx_events_source_ip ON events(source_ip);\n `);\n\n return db;\n}\n\nexport function insertEvent(event: ThreatEvent): number {\n const database = tryDb();\n if (!database) return -1;\n const stmt = database.prepare(`\n INSERT INTO events (timestamp, module, category, severity, message, source_ip, details)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n event.timestamp.toISOString(),\n event.module,\n event.category,\n event.severity,\n event.message,\n event.source_ip || null,\n event.details ? JSON.stringify(event.details) : null,\n );\n return result.lastInsertRowid as number;\n}\n\nfunction tryDb(): Database.Database | null {\n if (db) return db;\n if (dbUnavailable) return null;\n try {\n return initStateDB();\n } catch {\n return null;\n }\n}\n\nexport function getRecentEvents(limit: number = 50): ThreatEvent[] {\n const database = tryDb();\n if (!database) return [];\n const rows = database.prepare(`\n SELECT * FROM events ORDER BY timestamp DESC LIMIT ?\n `).all(limit) as any[];\n return rows.map(rowToEvent);\n}\n\nexport function getEventCount(since?: Date): number {\n const database = tryDb();\n if (!database) return 0;\n if (since) {\n return (database.prepare(`SELECT COUNT(*) as count FROM events WHERE timestamp >= ?`)\n .get(since.toISOString()) as any).count;\n }\n return (database.prepare(`SELECT COUNT(*) as count FROM events`).get() as any).count;\n}\n\nexport function getThreatCount(since?: Date): number {\n const database = tryDb();\n if (!database) return 0;\n const severities = \"('medium','high','critical')\";\n if (since) {\n return (database.prepare(\n `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities} AND timestamp >= ?`\n ).get(since.toISOString()) as any).count;\n }\n return (database.prepare(\n `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities}`\n ).get() as any).count;\n}\n\nexport function getTopSources(limit: number = 10): Array<{ ip: string; count: number }> {\n const database = tryDb();\n if (!database) return [];\n return database.prepare(`\n SELECT source_ip as ip, COUNT(*) as count FROM events\n WHERE source_ip IS NOT NULL\n GROUP BY source_ip ORDER BY count DESC LIMIT ?\n `).all(limit) as any[];\n}\n\nexport function getModuleState(module: string, key: string): unknown {\n const database = db || initStateDB();\n const row = database.prepare(`SELECT value FROM module_state WHERE module = ? AND key = ?`)\n .get(module, key) as any;\n if (!row) return undefined;\n try {\n return JSON.parse(row.value);\n } catch {\n return row.value;\n }\n}\n\nexport function setModuleState(module: string, key: string, value: unknown): void {\n const database = db || initStateDB();\n database.prepare(`\n INSERT OR REPLACE INTO module_state (module, key, value) VALUES (?, ?, ?)\n `).run(module, key, JSON.stringify(value));\n}\n\nfunction rowToEvent(row: any): ThreatEvent {\n return {\n id: row.id,\n timestamp: new Date(row.timestamp),\n module: row.module,\n category: row.category,\n severity: row.severity,\n message: row.message,\n source_ip: row.source_ip,\n details: row.details ? JSON.parse(row.details) : undefined,\n };\n}\n\nexport function closeDB(): void {\n if (db) {\n db.close();\n db = null;\n }\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport TOML from '@iarna/toml';\nimport type { EventBus } from './event-bus.js';\nimport { PATHS } from './paths.js';\nimport { LogWatcher } from './watchers/log-watcher.js';\nimport { JournalWatcher } from './watchers/journal-watcher.js';\nimport { NetworkMonitor } from '../modules/network-monitor/index.js';\nimport { DnsMonitor } from '../modules/dns-monitor/index.js';\nimport { loadModuleConfigs } from '../core/config.js';\nimport { getModuleState, setModuleState } from '../core/state.js';\nimport type { ModuleConfig, ModuleManifest } from '../types/config.js';\nimport type { ThreatEvent } from '../types/events.js';\nimport type { ModuleAlert, ThreatCrushModule } from '../types/module.js';\n\ninterface HostedModule {\n name: string;\n version: string;\n source: 'builtin' | 'installed';\n status: 'running' | 'loaded' | 'error' | 'disabled';\n events: number;\n detail?: string;\n path?: string;\n config?: ModuleConfig;\n instance?: ThreatCrushModule;\n}\n\nexport class ModuleHost {\n private modules = new Map<string, HostedModule>();\n private logWatcher: LogWatcher | null = null;\n private journalWatcher: JournalWatcher | null = null;\n private networkMonitor: NetworkMonitor | null = null;\n private dnsMonitor: DnsMonitor | null = null;\n\n constructor(private bus: EventBus) {\n bus.on('event', (event) => {\n const mod = this.modules.get(event.module);\n if (mod) mod.events++;\n for (const hosted of this.modules.values()) {\n if (hosted.status !== 'running' || !hosted.instance?.onEvent) continue;\n void hosted.instance.onEvent(event).catch((err) => {\n hosted.status = 'error';\n hosted.detail = `onEvent failed: ${String((err as Error).message || err)}`;\n this.bus.announceModule(hosted.name, 'error', hosted.detail);\n });\n }\n });\n }\n\n async start(): Promise<void> {\n this.registerBuiltins();\n await this.discoverAndStartInstalled();\n\n this.logWatcher = new LogWatcher(this.bus);\n const watched = this.logWatcher.start();\n\n for (const modName of this.logWatcher.activeModules()) {\n const mod = this.modules.get(modName);\n if (mod) {\n mod.status = 'running';\n mod.detail = `watching ${watched.length} log source(s)`;\n this.bus.announceModule(modName, 'running', mod.detail);\n }\n }\n\n this.journalWatcher = new JournalWatcher(this.bus);\n if (this.journalWatcher.start()) {\n const mod = this.modules.get('user-journal');\n if (mod) {\n mod.status = 'running';\n mod.detail = `tailing ${JournalWatcher.scopeArgs().includes('--user') ? 'user journal' : 'system journal'}`;\n this.bus.announceModule('user-journal', 'running', mod.detail);\n }\n }\n\n // Network monitor (PRD 04)\n this.networkMonitor = new NetworkMonitor(this.bus);\n if (this.networkMonitor.start()) {\n const nmod = this.modules.get('network-monitor');\n if (nmod) {\n nmod.status = 'running';\n nmod.detail = 'monitoring connections via conntrack/ss';\n this.bus.announceModule('network-monitor', 'running', nmod.detail);\n }\n }\n\n // DNS monitor (PRD 05)\n this.dnsMonitor = new DnsMonitor(this.bus);\n if (this.dnsMonitor.start()) {\n const dmod = this.modules.get('dns-monitor');\n if (dmod) {\n dmod.status = 'running';\n dmod.detail = 'monitoring DNS queries';\n this.bus.announceModule('dns-monitor', 'running', dmod.detail);\n }\n }\n }\n\n async stop(): Promise<void> {\n this.logWatcher?.stop();\n this.journalWatcher?.stop();\n this.networkMonitor?.stop();\n this.dnsMonitor?.stop();\n for (const mod of this.modules.values()) {\n try {\n if (mod.instance && mod.status === 'running') {\n await mod.instance.stop();\n }\n } catch (err) {\n mod.status = 'error';\n mod.detail = `stop failed: ${String((err as Error).message || err)}`;\n this.bus.announceModule(mod.name, 'error', mod.detail);\n continue;\n }\n mod.status = 'loaded';\n this.bus.announceModule(mod.name, 'stopped');\n }\n }\n\n summary(): Array<{ name: string; status: string; events: number; detail?: string }> {\n return [...this.modules.values()].map((m) => ({\n name: m.name,\n status: m.status,\n events: m.events,\n detail: m.detail,\n }));\n }\n\n private registerBuiltins(): void {\n const builtins: HostedModule[] = [\n { name: 'log-watcher', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'ssh-guard', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'user-journal', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'network-monitor', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n { name: 'dns-monitor', version: '0.1.0', source: 'builtin', status: 'loaded', events: 0 },\n ];\n for (const m of builtins) this.modules.set(m.name, m);\n }\n\n private async discoverAndStartInstalled(): Promise<void> {\n if (!existsSync(PATHS.moduleDir)) return;\n const configs = loadModuleConfigs(PATHS.confD);\n const entries = readdirSync(PATHS.moduleDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const manifestPath = join(PATHS.moduleDir, entry.name, 'mod.toml');\n if (!existsSync(manifestPath)) continue;\n try {\n const manifest = TOML.parse(readFileSync(manifestPath, 'utf-8')) as unknown as ModuleManifest;\n const name = manifest.module?.name || entry.name;\n const defaults = manifest.module?.config?.defaults || {};\n const config = {\n enabled: true,\n ...defaults,\n ...(configs.get(name) || {}),\n } as ModuleConfig;\n const hosted: HostedModule = {\n name,\n version: manifest.module?.version || '0.0.0',\n source: 'installed',\n status: config.enabled === false ? 'disabled' : 'loaded',\n events: 0,\n path: join(PATHS.moduleDir, entry.name),\n config,\n };\n this.modules.set(name, hosted);\n if (config.enabled === false) continue;\n await this.startInstalled(hosted);\n } catch (err) {\n const name = entry.name;\n this.modules.set(name, {\n name,\n version: '0.0.0',\n source: 'installed',\n status: 'error',\n events: 0,\n detail: `manifest load failed: ${String((err as Error).message || err)}`,\n path: join(PATHS.moduleDir, entry.name),\n });\n }\n }\n }\n\n private async startInstalled(hosted: HostedModule): Promise<void> {\n const entrypoint = this.installedEntrypoint(hosted.path!);\n if (!entrypoint) {\n hosted.status = 'loaded';\n hosted.detail = 'no built entrypoint found; run npm install && npm run build in the module directory';\n return;\n }\n\n try {\n const imported = await import(pathToFileURL(entrypoint).href);\n const exported = imported.default || imported.module || imported;\n const instance = typeof exported === 'function' ? new exported() : exported;\n if (!this.isThreatCrushModule(instance)) {\n throw new Error('entrypoint does not export a ThreatCrush module');\n }\n\n hosted.instance = instance;\n await instance.init(this.contextFor(hosted));\n await instance.start();\n hosted.status = 'running';\n hosted.detail = `started from ${entrypoint}`;\n this.bus.announceModule(hosted.name, 'running', hosted.detail);\n } catch (err) {\n hosted.status = 'error';\n hosted.detail = String((err as Error).message || err);\n this.bus.announceModule(hosted.name, 'error', hosted.detail);\n }\n }\n\n private installedEntrypoint(modulePath: string): string | null {\n const packageJson = join(modulePath, 'package.json');\n const candidates: string[] = [];\n if (existsSync(packageJson)) {\n try {\n const pkg = JSON.parse(readFileSync(packageJson, 'utf-8')) as { main?: string };\n if (pkg.main) candidates.push(join(modulePath, pkg.main));\n } catch {\n // fall through to conventional paths\n }\n }\n candidates.push(join(modulePath, 'dist', 'index.js'), join(modulePath, 'index.js'));\n return candidates.find((candidate) => existsSync(candidate)) || null;\n }\n\n private isThreatCrushModule(value: unknown): value is ThreatCrushModule {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as ThreatCrushModule).init === 'function' &&\n typeof (value as ThreatCrushModule).start === 'function' &&\n typeof (value as ThreatCrushModule).stop === 'function',\n );\n }\n\n private contextFor(hosted: HostedModule) {\n return {\n config: hosted.config || { enabled: true },\n logger: this.loggerFor(hosted.name),\n emit: (event: ThreatEvent) => this.bus.publish(event),\n subscribe: (eventType: string, handler: (event: ThreatEvent) => void) => {\n this.bus.on('event', (event) => {\n if (event.category === eventType || event.module === eventType) handler(event);\n });\n },\n alert: (alert: ModuleAlert) => {\n this.bus.emit('alert', alert.event || {\n timestamp: new Date(),\n module: hosted.name,\n category: 'system',\n severity: alert.severity,\n message: alert.title,\n details: alert.body ? { body: alert.body } : undefined,\n });\n },\n getState: (key: string) => getModuleState(hosted.name, key),\n setState: (key: string, value: unknown) => setModuleState(hosted.name, key, value),\n };\n }\n\n private loggerFor(moduleName: string) {\n return {\n debug: (msg: string, ...args: unknown[]) => console.debug(`[${moduleName}] ${msg}`, ...args),\n info: (msg: string, ...args: unknown[]) => console.info(`[${moduleName}] ${msg}`, ...args),\n warn: (msg: string, ...args: unknown[]) => console.warn(`[${moduleName}] ${msg}`, ...args),\n error: (msg: string, ...args: unknown[]) => console.error(`[${moduleName}] ${msg}`, ...args),\n };\n }\n}\n","import { existsSync, statSync, createReadStream, accessSync, constants } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { EventBus } from '../event-bus.js';\nimport { autoDetectParser, detectAttackPattern, parseAuthLog, parseNginxLog } from '../../core/log-parser.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventCategory, EventSeverity } from '../../types/events.js';\n\nexport interface LogSource {\n path: string;\n module: string;\n category: EventCategory;\n}\n\nexport const DEFAULT_SOURCES: LogSource[] = [\n { path: '/var/log/auth.log', module: 'ssh-guard', category: 'auth' },\n { path: '/var/log/secure', module: 'ssh-guard', category: 'auth' },\n { path: '/var/log/nginx/access.log', module: 'log-watcher', category: 'web' },\n { path: '/var/log/syslog', module: 'log-watcher', category: 'system' },\n];\n\nexport class LogWatcher {\n private timers = new Map<string, NodeJS.Timeout>();\n private positions = new Map<string, number>();\n private active = new Set<string>();\n\n constructor(private bus: EventBus, private sources: LogSource[] = DEFAULT_SOURCES) {}\n\n start(): string[] {\n const started: string[] = [];\n for (const src of this.sources) {\n if (!existsSync(src.path)) continue;\n try { accessSync(src.path, constants.R_OK); }\n catch { continue; }\n this.tail(src);\n started.push(src.path);\n }\n return started;\n }\n\n stop(): void {\n for (const t of this.timers.values()) clearInterval(t);\n this.timers.clear();\n this.positions.clear();\n this.active.clear();\n }\n\n activeModules(): string[] {\n return [...this.active];\n }\n\n private tail(src: LogSource): void {\n try {\n this.positions.set(src.path, statSync(src.path).size);\n } catch {\n this.positions.set(src.path, 0);\n }\n\n const timer = setInterval(() => this.poll(src), 1000);\n this.timers.set(src.path, timer);\n this.active.add(src.module);\n }\n\n private poll(src: LogSource): void {\n let stat;\n try { stat = statSync(src.path); } catch { return; }\n const prev = this.positions.get(src.path) ?? 0;\n\n if (stat.size < prev) {\n this.positions.set(src.path, 0); // rotated\n return;\n }\n if (stat.size === prev) return;\n\n const stream = createReadStream(src.path, { start: prev, encoding: 'utf-8' });\n stream.on('error', () => this.positions.set(src.path, stat.size));\n const rl = createInterface({ input: stream });\n rl.on('error', () => {});\n rl.on('line', (line) => {\n if (!line.trim()) return;\n this.process(line, src);\n });\n rl.on('close', () => this.positions.set(src.path, stat.size));\n }\n\n private process(line: string, src: LogSource): void {\n const parsed = autoDetectParser(line);\n if (!parsed) return;\n\n let severity: EventSeverity = 'info';\n let message = line;\n let sourceIp: string | undefined;\n\n if (parsed.source === 'auth') {\n const entry = parseAuthLog(line);\n if (!entry) return;\n sourceIp = entry.fields.ip;\n const msg = entry.fields.message;\n if (/failed password/i.test(msg)) {\n severity = 'high';\n message = `Failed SSH login for ${entry.fields.user || 'unknown'} from ${entry.fields.ip || 'unknown'}`;\n } else if (/invalid user/i.test(msg)) {\n severity = 'high';\n message = `Invalid SSH user: ${entry.fields.user || 'unknown'} from ${entry.fields.ip || 'unknown'}`;\n } else if (/accepted/i.test(msg)) {\n severity = 'info';\n message = `SSH login accepted for ${entry.fields.user || 'unknown'}`;\n } else {\n return;\n }\n } else if (parsed.source === 'nginx') {\n const entry = parseNginxLog(line);\n if (!entry) return;\n sourceIp = entry.fields.ip;\n const status = parseInt(entry.fields.status, 10);\n const attack = detectAttackPattern(entry.fields.path);\n if (attack) {\n severity = 'critical';\n message = `Attack [${attack.toUpperCase()}]: ${entry.fields.method} ${entry.fields.path}`;\n } else if (status >= 500) {\n severity = 'medium';\n message = `Server error ${status}: ${entry.fields.method} ${entry.fields.path}`;\n } else if (status >= 400) {\n severity = 'low';\n message = `Client error ${status}: ${entry.fields.method} ${entry.fields.path}`;\n } else {\n return;\n }\n } else {\n return;\n }\n\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: src.module,\n category: src.category,\n severity,\n message,\n source_ip: sourceIp,\n };\n\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n","import type { ParsedLogLine, NginxLogEntry, AuthLogEntry, SyslogEntry } from '../types/events.js';\n\n// Nginx combined log format:\n// 127.0.0.1 - - [04/Apr/2026:12:00:00 +0000] \"GET /path HTTP/1.1\" 200 1234 \"-\" \"Mozilla/5.0\"\nconst NGINX_REGEX = /^(\\S+) \\S+ \\S+ \\[([^\\]]+)\\] \"(\\S+) (\\S+) \\S+\" (\\d{3}) (\\d+) \"[^\"]*\" \"([^\"]*)\"/;\n\n// Auth.log format:\n// Apr 4 12:00:00 hostname sshd[1234]: Failed password for user from 1.2.3.4 port 22 ssh2\nconst AUTH_REGEX = /^(\\w+\\s+\\d+\\s+[\\d:]+)\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)/;\n\n// Syslog format:\n// Apr 4 12:00:00 hostname process[pid]: message\nconst SYSLOG_REGEX = /^(\\w+\\s+\\d+\\s+[\\d:]+)\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)/;\n\n// Extract IP from auth messages\nconst IP_REGEX = /(?:from|FROM)\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/;\nconst INVALID_USER_REGEX = /(?:for\\s+invalid\\s+user)\\s+(\\S+?)(?:\\s+from|\\s*$)/;\nconst USER_REGEX = /(?:for|user)\\s+(\\S+?)(?:\\s+from|\\s*$)/;\n\n// Attack pattern signatures\nexport const ATTACK_PATTERNS = {\n sqli: [\n /(?:union\\s+(?:all\\s+)?select)/i,\n /(?:select\\s+.*\\s+from\\s+)/i,\n /(?:insert\\s+into\\s+)/i,\n /(?:drop\\s+(?:table|database))/i,\n /(?:or\\s+1\\s*=\\s*1)/i,\n /(?:'\\s*(?:or|and)\\s+')/i,\n /(?:--\\s*$|;\\s*--)/,\n /(?:\\/\\*.*\\*\\/)/,\n ],\n xss: [\n /<script[^>]*>/i,\n /javascript\\s*:/i,\n /on(?:load|error|click|mouseover)\\s*=/i,\n /eval\\s*\\(/i,\n /document\\.(?:cookie|write|location)/i,\n ],\n path_traversal: [\n /\\.\\.\\//,\n /\\.\\.\\\\/, \n /etc\\/(?:passwd|shadow|hosts)/,\n /proc\\/self/,\n /windows\\/system32/i,\n ],\n rfi: [\n /(?:https?|ftp):\\/\\/.*\\?/i,\n /php:\\/\\/(?:input|filter)/i,\n /data:\\/\\//i,\n ],\n};\n\nexport function parseNginxLog(line: string): NginxLogEntry | null {\n const match = line.match(NGINX_REGEX);\n if (!match) return null;\n\n return {\n timestamp: parseNginxTimestamp(match[2]),\n raw: line,\n source: 'nginx',\n fields: {\n ip: match[1],\n method: match[3],\n path: match[4],\n status: match[5],\n size: match[6],\n user_agent: match[7],\n },\n };\n}\n\nexport function parseAuthLog(line: string): AuthLogEntry | null {\n const match = line.match(AUTH_REGEX);\n if (!match) return null;\n\n const ipMatch = match[3].match(IP_REGEX);\n const userMatch = match[3].match(INVALID_USER_REGEX) || match[3].match(USER_REGEX);\n\n return {\n timestamp: parseSyslogTimestamp(match[1]),\n raw: line,\n source: 'auth',\n fields: {\n process: match[2],\n message: match[3],\n ip: ipMatch?.[1],\n user: userMatch?.[1],\n },\n };\n}\n\nexport function parseSyslog(line: string): SyslogEntry | null {\n const match = line.match(SYSLOG_REGEX);\n if (!match) return null;\n\n return {\n timestamp: parseSyslogTimestamp(match[1]),\n raw: line,\n source: 'syslog',\n fields: {\n facility: 'syslog',\n process: match[2],\n message: match[3],\n },\n };\n}\n\nexport function detectAttackPattern(path: string): string | null {\n // nginx logs the request URI URL-encoded, so raw signatures like `<script`\n // or `or 1=1` never match an encoded payload (e.g. `%3Cscript%3E`,\n // `%27%20OR%201=1`). Test the raw value AND its URL-decoded forms so that\n // single- and double-encoded payloads are still caught. decodeURIComponent\n // throws on a malformed `%` sequence, so guard each decode.\n const candidates = new Set<string>([path]);\n let current = path;\n for (let i = 0; i < 2; i++) {\n let decoded: string | null = null;\n try {\n decoded = decodeURIComponent(current);\n } catch {\n decoded = null;\n }\n if (decoded === null || decoded === current) break;\n candidates.add(decoded);\n current = decoded;\n }\n\n for (const [type, patterns] of Object.entries(ATTACK_PATTERNS)) {\n for (const pattern of patterns) {\n for (const candidate of candidates) {\n if (pattern.test(candidate)) {\n return type;\n }\n }\n }\n }\n return null;\n}\n\nexport function autoDetectParser(line: string): ParsedLogLine | null {\n // Try nginx first (most specific format)\n const nginx = parseNginxLog(line);\n if (nginx) return nginx;\n\n // Try auth log\n const auth = parseAuthLog(line);\n if (auth) return auth;\n\n // Fall back to generic syslog\n return parseSyslog(line);\n}\n\nfunction parseNginxTimestamp(s: string): Date {\n // \"04/Apr/2026:12:00:00 +0000\"\n // new Date(<unparseable>) returns an Invalid Date instead of throwing, so the\n // old try/catch never triggered and an Invalid Date leaked into downstream\n // time-window logic. Check getTime() explicitly and fall back to now.\n const cleaned = s.replace(/(\\d{2})\\/(\\w{3})\\/(\\d{4}):/, '$2 $1, $3 ');\n const d = new Date(cleaned);\n return Number.isNaN(d.getTime()) ? new Date() : d;\n}\n\nfunction parseSyslogTimestamp(s: string): Date {\n // \"Apr 4 12:00:00\" — no year. Assume the most recent year that is not in the\n // future, so a December log parsed in early January is dated to the previous\n // year rather than the current one.\n const now = new Date();\n let d = new Date(`${s} ${now.getFullYear()}`);\n if (Number.isNaN(d.getTime())) return now;\n if (d.getTime() > now.getTime()) {\n const prev = new Date(`${s} ${now.getFullYear() - 1}`);\n if (!Number.isNaN(prev.getTime())) d = prev;\n }\n return d;\n}\n","import { spawn, type ChildProcess, spawnSync } from 'node:child_process';\nimport type { EventBus } from '../event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\n// Wraps `journalctl --user -o json -f` so threatcrushd can pick up user-session\n// events without needing to belong to the `adm` or `systemd-journal` group.\n// On systems without journalctl this watcher is a no-op.\nexport class JournalWatcher {\n private proc: ChildProcess | null = null;\n private buffer = '';\n private moduleName = 'user-journal';\n private active = false;\n\n constructor(private bus: EventBus) {}\n\n // When the daemon runs as root (system mode), tail the SYSTEM journal so\n // we pick up sshd / sudo / kernel / UFW events. Falling back to --user\n // would give us root's mostly-empty per-user journal. Otherwise we use\n // --user so the daemon can run unprivileged on a workstation.\n static scopeArgs(): string[] {\n const isRoot = process.platform === 'linux'\n && typeof process.getuid === 'function'\n && process.getuid() === 0;\n return isRoot ? [] : ['--user'];\n }\n\n static isAvailable(): boolean {\n const probe = spawnSync('journalctl', [...this.scopeArgs(), '-n', '0', '--no-pager'], {\n stdio: ['ignore', 'ignore', 'ignore'],\n });\n return probe.status === 0;\n }\n\n start(): boolean {\n if (!JournalWatcher.isAvailable()) return false;\n\n const child = spawn(\n 'journalctl',\n [...JournalWatcher.scopeArgs(), '-o', 'json', '-f', '--since', 'now'],\n { stdio: ['ignore', 'pipe', 'pipe'] },\n );\n if (!child.stdout) return false;\n child.stdout.setEncoding('utf-8');\n child.stdout.on('data', (chunk: string) => this.onData(chunk));\n child.on('exit', () => {\n this.proc = null;\n this.active = false;\n });\n this.proc = child;\n\n this.active = true;\n return true;\n }\n\n stop(): void {\n if (this.proc) {\n try { this.proc.kill('SIGTERM'); } catch {}\n this.proc = null;\n }\n this.active = false;\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n moduleNameValue(): string {\n return this.moduleName;\n }\n\n private onData(chunk: string): void {\n this.buffer += chunk;\n let idx;\n while ((idx = this.buffer.indexOf('\\n')) >= 0) {\n const line = this.buffer.slice(0, idx);\n this.buffer = this.buffer.slice(idx + 1);\n if (!line.trim()) continue;\n this.handleLine(line);\n }\n }\n\n private handleLine(line: string): void {\n let entry: Record<string, string>;\n try {\n entry = JSON.parse(line) as Record<string, string>;\n } catch {\n return;\n }\n\n const message = entry.MESSAGE;\n if (!message) return;\n\n const priority = parseInt(entry.PRIORITY ?? '6', 10);\n const severity = priorityToSeverity(priority);\n\n // Surface a couple of common suspicious-looking sources at a higher\n // severity even if the kernel disagrees with us.\n const ident = entry.SYSLOG_IDENTIFIER || entry._COMM || 'journal';\n const bumpedSeverity = bumpForIdent(ident, message, severity);\n\n const event: ThreatEvent = {\n timestamp: realtimeToDate(entry.__REALTIME_TIMESTAMP) || new Date(),\n module: this.moduleName,\n category: 'system',\n severity: bumpedSeverity,\n message: `[${ident}] ${message}`.slice(0, 500),\n };\n\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n\nfunction priorityToSeverity(priority: number): EventSeverity {\n // syslog priorities: 0 emerg, 1 alert, 2 crit, 3 err, 4 warning, 5 notice, 6 info, 7 debug\n if (priority <= 2) return 'critical';\n if (priority === 3) return 'high';\n if (priority === 4) return 'medium';\n if (priority === 5) return 'low';\n return 'info';\n}\n\nfunction bumpForIdent(ident: string, message: string, base: EventSeverity): EventSeverity {\n if (/sudo/i.test(ident) && /authentication failure|incorrect password|FAILED/i.test(message)) {\n return 'high';\n }\n if (/sshd/i.test(ident) && /failed|invalid user|break-in/i.test(message)) {\n return 'high';\n }\n return base;\n}\n\nfunction realtimeToDate(rt: string | undefined): Date | null {\n if (!rt) return null;\n const us = parseInt(rt, 10);\n if (!Number.isFinite(us)) return null;\n return new Date(Math.floor(us / 1000));\n}\n","/**\n * Network Monitor Module (PRD 04)\n *\n * Observes TCP/UDP connections via conntrack / ss / /proc/net.\n * Detects port scans and SYN-flood-style patterns.\n * Emits detections through the event bus for the rule engine.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport type { EventBus } from '../../daemon/event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\ninterface ConnectionRecord {\n source_ip: string;\n dest_port: number;\n timestamp: number;\n}\n\ninterface ScanTracker {\n ports: Set<number>;\n firstSeen: number;\n lastSeen: number;\n count: number;\n}\n\nexport class NetworkMonitor {\n private active = false;\n private pollTimer: NodeJS.Timeout | null = null;\n private scanTrackers = new Map<string, ScanTracker>();\n private halfOpenTrackers = new Map<string, { count: number; firstSeen: number }>();\n private lastConnections = new Set<string>();\n\n // Config\n private pollIntervalMs = 5000;\n private portScanThreshold = 10; // unique ports in window\n private portScanWindowMs = 30_000;\n private synFloodThreshold = 50; // half-open connections\n private synFloodWindowMs = 10_000;\n\n constructor(private bus: EventBus) {}\n\n start(): boolean {\n if (!this.hasConntrackOrSs()) {\n return false;\n }\n this.active = true;\n this.pollTimer = setInterval(() => this.poll(), this.pollIntervalMs);\n return true;\n }\n\n stop(): void {\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = null;\n this.active = false;\n }\n\n isActive(): boolean { return this.active; }\n\n private hasConntrackOrSs(): boolean {\n const ss = spawnSync('ss', ['--version'], { stdio: 'pipe' });\n if (ss.status === 0) return true;\n // Try /proc/net/tcp\n return existsSync('/proc/net/tcp');\n }\n\n private poll(): void {\n try {\n const connections = this.getConnections();\n this.analyzePortScans(connections);\n this.analyzeSynFlood(connections);\n this.cleanupTrackers();\n } catch {\n // Graceful degradation\n }\n }\n\n private getConnections(): ConnectionRecord[] {\n const records: ConnectionRecord[] = [];\n const now = Date.now();\n\n try {\n // Try conntrack first\n const ct = spawnSync('conntrack', ['-L', '-p', 'tcp', '-o', 'extended'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ct.status === 0 && ct.stdout) {\n for (const line of ct.stdout.split('\\n')) {\n const srcMatch = line.match(/src=(\\d+\\.\\d+\\.\\d+\\.\\d+)/);\n const dportMatch = line.match(/dport=(\\d+)/);\n if (srcMatch && dportMatch) {\n records.push({ source_ip: srcMatch[1], dest_port: parseInt(dportMatch[1]), timestamp: now });\n }\n }\n if (records.length > 0) return records;\n }\n } catch { /* fallthrough */ }\n\n try {\n // Fallback to ss\n const ss = spawnSync('ss', ['-tnp', '-H'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ss.status === 0 && ss.stdout) {\n for (const line of ss.stdout.split('\\n')) {\n // ss output: State Recv-Q Send-Q Local:Port Peer:Port Process\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 5) continue;\n const peerParts = parts[4].split(':');\n const localParts = parts[3].split(':');\n if (peerParts.length >= 2 && localParts.length >= 2) {\n const sourceIp = peerParts.slice(0, -1).join(':');\n const destPort = parseInt(localParts[localParts.length - 1]);\n if (sourceIp && !isNaN(destPort) && !this.isLocalIp(sourceIp)) {\n records.push({ source_ip: sourceIp, dest_port: destPort, timestamp: now });\n }\n }\n }\n }\n } catch { /* fallthrough */ }\n\n return records;\n }\n\n private analyzePortScans(connections: ConnectionRecord[]): void {\n const now = Date.now();\n\n for (const conn of connections) {\n const key = conn.source_ip;\n let tracker = this.scanTrackers.get(key);\n\n if (!tracker) {\n tracker = { ports: new Set(), firstSeen: now, lastSeen: now, count: 0 };\n this.scanTrackers.set(key, tracker);\n }\n\n tracker.ports.add(conn.dest_port);\n tracker.lastSeen = now;\n tracker.count++;\n\n // Check threshold within window\n if (tracker.ports.size >= this.portScanThreshold &&\n (now - tracker.firstSeen) <= this.portScanWindowMs) {\n this.emitEvent(\n 'high',\n `Port scan detected: ${conn.source_ip} probed ${tracker.ports.size} ports in ${Math.round((now - tracker.firstSeen) / 1000)}s`,\n conn.source_ip,\n { ports_scanned: tracker.ports.size, window_seconds: Math.round((now - tracker.firstSeen) / 1000) },\n );\n // Reset tracker after alert\n this.scanTrackers.delete(key);\n }\n }\n }\n\n private analyzeSynFlood(connections: ConnectionRecord[]): void {\n // Count SYN_RECV (half-open) states via ss\n try {\n const ss = spawnSync('ss', ['-tn', 'state', 'syn-recv', '-H'], {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 3000,\n });\n if (ss.status !== 0 || !ss.stdout) return;\n\n const perSource = new Map<string, number>();\n\n for (const line of ss.stdout.split('\\n')) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 5) continue;\n const peer = parts[4].split(':');\n const ip = peer.slice(0, -1).join(':');\n if (ip) perSource.set(ip, (perSource.get(ip) || 0) + 1);\n }\n\n for (const [ip, count] of perSource) {\n if (count >= this.synFloodThreshold) {\n this.emitEvent(\n 'critical',\n `SYN flood indicators: ${count} half-open connections from ${ip}`,\n ip,\n { half_open_count: count },\n );\n }\n }\n } catch { /* graceful */ }\n }\n\n private emitEvent(severity: EventSeverity, message: string, sourceIp?: string, details?: Record<string, unknown>): void {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'network-monitor',\n category: 'network',\n severity,\n message,\n source_ip: sourceIp,\n details,\n };\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n\n private cleanupTrackers(): void {\n const now = Date.now();\n for (const [key, tracker] of this.scanTrackers) {\n if (now - tracker.lastSeen > this.portScanWindowMs * 2) {\n this.scanTrackers.delete(key);\n }\n }\n }\n\n private isLocalIp(ip: string): boolean {\n return ip === '127.0.0.1' || ip === '::1' || ip === '0.0.0.0' || ip.startsWith('::ffff:127.');\n }\n}\n","/**\n * DNS Monitor Module (PRD 05)\n *\n * Observes DNS query activity for tunneling and DGA indicators.\n * Sources: resolver logs, systemd-resolved, dnsmasq logs, passive :53 observation.\n */\n\nimport { existsSync, statSync, createReadStream, accessSync, constants } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { EventBus } from '../../daemon/event-bus.js';\nimport { insertEvent } from '../../core/state.js';\nimport type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\ninterface DnsQuery {\n domain: string;\n type: string;\n source_ip?: string;\n timestamp: number;\n}\n\nconst DNS_LOG_SOURCES = [\n '/var/log/syslog', // systemd-resolved logs here\n '/var/log/dnsmasq.log', // dnsmasq\n '/var/log/named/queries.log', // bind9\n '/var/log/pihole.log', // Pi-hole\n];\n\nexport class DnsMonitor {\n private active = false;\n private timers = new Map<string, NodeJS.Timeout>();\n private positions = new Map<string, number>();\n\n // Tracking windows\n private txtQueryCounts = new Map<string, { count: number; firstSeen: number }>();\n private domainBuffer: DnsQuery[] = [];\n\n // Config\n private txtRateThreshold = 20; // TXT queries per source per window\n private txtWindowMs = 60_000;\n private dgaBurstThreshold = 15; // unique high-entropy domains per window\n private dgaWindowMs = 60_000;\n private entropyThreshold = 3.5; // Shannon entropy threshold for DGA\n\n constructor(private bus: EventBus) {}\n\n start(): boolean {\n const sources = DNS_LOG_SOURCES.filter(p => {\n if (!existsSync(p)) return false;\n try { accessSync(p, constants.R_OK); return true; }\n catch { return false; }\n });\n\n if (sources.length === 0) return false;\n\n this.active = true;\n for (const src of sources) {\n this.tailLog(src);\n }\n\n // Periodic analysis\n setInterval(() => this.analyzeBuffer(), 10_000);\n return true;\n }\n\n stop(): void {\n for (const t of this.timers.values()) clearInterval(t);\n this.timers.clear();\n this.active = false;\n }\n\n isActive(): boolean { return this.active; }\n\n private tailLog(path: string): void {\n try {\n this.positions.set(path, statSync(path).size);\n } catch {\n this.positions.set(path, 0);\n }\n\n const timer = setInterval(() => this.pollLog(path), 2000);\n this.timers.set(path, timer);\n }\n\n private pollLog(path: string): void {\n let stat;\n try { stat = statSync(path); } catch { return; }\n const prev = this.positions.get(path) ?? 0;\n\n if (stat.size < prev) { this.positions.set(path, 0); return; }\n if (stat.size === prev) return;\n\n const stream = createReadStream(path, { start: prev, encoding: 'utf-8' });\n stream.on('error', () => this.positions.set(path, stat.size));\n const rl = createInterface({ input: stream });\n rl.on('line', (line) => this.parseDnsLine(line));\n rl.on('close', () => this.positions.set(path, stat.size));\n }\n\n private parseDnsLine(line: string): void {\n // systemd-resolved pattern: \"query[TXT] suspicious.domain.com from 192.168.1.1\"\n const resolvedMatch = line.match(/query\\[(\\w+)\\]\\s+(\\S+)\\s+from\\s+(\\S+)/i);\n if (resolvedMatch) {\n this.domainBuffer.push({\n type: resolvedMatch[1],\n domain: resolvedMatch[2],\n source_ip: resolvedMatch[3],\n timestamp: Date.now(),\n });\n return;\n }\n\n // dnsmasq pattern: \"query[TXT] suspicious.domain.com from 192.168.1.1\"\n const dnsmasqMatch = line.match(/query\\[(\\w+)\\]\\s+(\\S+)\\s+from\\s+(\\S+)/i);\n if (dnsmasqMatch) {\n this.domainBuffer.push({\n type: dnsmasqMatch[1],\n domain: dnsmasqMatch[2],\n source_ip: dnsmasqMatch[3],\n timestamp: Date.now(),\n });\n return;\n }\n\n // Generic DNS query log pattern\n const genericMatch = line.match(/(?:query|lookup|resolve)[:\\s]+(\\S+)/i);\n if (genericMatch) {\n const typeMatch = line.match(/type[:\\s]+(\\w+)/i);\n this.domainBuffer.push({\n type: typeMatch?.[1] || 'A',\n domain: genericMatch[1],\n timestamp: Date.now(),\n });\n }\n }\n\n private analyzeBuffer(): void {\n const now = Date.now();\n const cutoff = now - this.txtWindowMs;\n\n // Prune old entries\n this.domainBuffer = this.domainBuffer.filter(q => q.timestamp > cutoff);\n\n this.detectTunneling();\n this.detectDga();\n }\n\n private detectTunneling(): void {\n // Check for high TXT query volume from single source\n const txtBySource = new Map<string, number>();\n const longLabelDomains: string[] = [];\n\n for (const q of this.domainBuffer) {\n if (q.type === 'TXT') {\n const key = q.source_ip || 'unknown';\n txtBySource.set(key, (txtBySource.get(key) || 0) + 1);\n }\n\n // DNS tunneling uses abnormally long subdomain labels\n const labels = q.domain.split('.');\n const maxLabel = Math.max(...labels.map(l => l.length));\n if (maxLabel > 50) {\n longLabelDomains.push(q.domain);\n }\n }\n\n for (const [source, count] of txtBySource) {\n if (count >= this.txtRateThreshold) {\n this.emitEvent(\n 'high',\n `DNS tunneling indicators: ${count} TXT queries from ${source} in ${this.txtWindowMs / 1000}s`,\n source !== 'unknown' ? source : undefined,\n { txt_query_count: count, type: 'tunneling' },\n );\n }\n }\n\n if (longLabelDomains.length >= 5) {\n this.emitEvent(\n 'high',\n `DNS tunneling: ${longLabelDomains.length} queries with abnormally long labels detected`,\n undefined,\n { domains: longLabelDomains.slice(0, 5), type: 'tunneling-labels' },\n );\n }\n }\n\n private detectDga(): void {\n // Find domains with high entropy (DGA-like)\n const highEntropyDomains: string[] = [];\n\n for (const q of this.domainBuffer) {\n const domain = q.domain.toLowerCase();\n // Extract the second-level domain\n const parts = domain.split('.');\n if (parts.length < 2) continue;\n const sld = parts[parts.length - 2];\n\n if (sld.length >= 8 && this.shannonEntropy(sld) >= this.entropyThreshold) {\n highEntropyDomains.push(domain);\n }\n }\n\n // Deduplicate\n const unique = [...new Set(highEntropyDomains)];\n if (unique.length >= this.dgaBurstThreshold) {\n this.emitEvent(\n 'critical',\n `DGA-like domain burst: ${unique.length} unique high-entropy domains detected`,\n undefined,\n { sample_domains: unique.slice(0, 10), type: 'dga', unique_count: unique.length },\n );\n }\n }\n\n private shannonEntropy(str: string): number {\n const freq = new Map<string, number>();\n for (const ch of str) {\n freq.set(ch, (freq.get(ch) || 0) + 1);\n }\n let entropy = 0;\n for (const count of freq.values()) {\n const p = count / str.length;\n if (p > 0) entropy -= p * Math.log2(p);\n }\n return entropy;\n }\n\n private emitEvent(severity: EventSeverity, message: string, sourceIp?: string, details?: Record<string, unknown>): void {\n const event: ThreatEvent = {\n timestamp: new Date(),\n module: 'dns-monitor',\n category: 'network',\n severity,\n message,\n source_ip: sourceIp,\n details,\n };\n try { insertEvent(event); } catch { /* db optional */ }\n this.bus.publish(event);\n }\n}\n","import { readFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport TOML from '@iarna/toml';\nimport type { ThreatCrushConfig, ModuleConfig } from '../types/config.js';\n\nconst DEFAULT_CONFIG_PATH = '/etc/threatcrush/threatcrushd.conf';\nconst DEFAULT_CONFDIR = '/etc/threatcrush/threatcrushd.conf.d';\n\nconst DEFAULT_CONFIG: ThreatCrushConfig = {\n daemon: {\n pid_file: '/var/run/threatcrush/threatcrushd.pid',\n log_level: 'info',\n log_file: '/var/log/threatcrush/threatcrushd.log',\n state_db: '/var/lib/threatcrush/state.db',\n },\n api: {\n enabled: true,\n bind: '127.0.0.1:9393',\n tls: false,\n },\n alerts: {},\n modules: {\n auto_update: true,\n update_interval: '24h',\n module_dir: '/etc/threatcrush/modules',\n config_dir: DEFAULT_CONFDIR,\n },\n};\n\nexport function loadConfig(configPath?: string): ThreatCrushConfig {\n const path = configPath || DEFAULT_CONFIG_PATH;\n if (!existsSync(path)) {\n return { ...DEFAULT_CONFIG };\n }\n\n try {\n const raw = readFileSync(path, 'utf-8');\n const parsed = TOML.parse(raw) as unknown as Partial<ThreatCrushConfig>;\n return {\n daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },\n api: { ...DEFAULT_CONFIG.api, ...parsed.api },\n alerts: parsed.alerts || {},\n modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },\n license: parsed.license,\n };\n } catch {\n return { ...DEFAULT_CONFIG };\n }\n}\n\nexport function loadModuleConfigs(confDir?: string): Map<string, ModuleConfig> {\n const dir = confDir || DEFAULT_CONFDIR;\n const configs = new Map<string, ModuleConfig>();\n\n if (!existsSync(dir)) {\n return configs;\n }\n\n const files = readdirSync(dir).filter((f) => f.endsWith('.conf'));\n for (const file of files) {\n try {\n const raw = readFileSync(join(dir, file), 'utf-8');\n const parsed = TOML.parse(raw) as Record<string, unknown>;\n for (const [name, config] of Object.entries(parsed)) {\n configs.set(name, config as ModuleConfig);\n }\n } catch {\n // skip bad configs\n }\n }\n\n return configs;\n}\n\nexport function generateDefaultConfig(detectedServices: string[]): string {\n const config: Record<string, unknown> = {\n daemon: DEFAULT_CONFIG.daemon,\n api: DEFAULT_CONFIG.api,\n modules: DEFAULT_CONFIG.modules,\n };\n\n return TOML.stringify(config as any);\n}\n\nexport function generateModuleConfig(\n moduleName: string,\n defaults: Record<string, unknown> = {},\n): string {\n const config: Record<string, unknown> = {\n [moduleName]: {\n enabled: true,\n ...defaults,\n },\n };\n return TOML.stringify(config as any);\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\ntype Mailer = {\n sendMail: (opts: Record<string, unknown>) => Promise<unknown>;\n};\n\nlet transporter: Mailer | null = null;\n// Lazy-load nodemailer so the CLI build doesn't pull it in when alerts are off.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet nodemailer: any = null;\n\nexport interface SmtpConfig {\n host?: string;\n port?: number;\n secure?: boolean;\n user?: string;\n pass?: string;\n from?: string;\n to?: string[] | string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nasync function ensureTransporter(config: SmtpConfig): Promise<Mailer | null> {\n if (!config.host || !config.from) return null;\n if (transporter) return transporter;\n\n if (!nodemailer) {\n try {\n nodemailer = await import('nodemailer');\n } catch {\n return null;\n }\n }\n\n transporter = nodemailer.createTransport({\n host: config.host,\n port: config.port ?? 587,\n secure: config.secure ?? false,\n auth: config.user && config.pass ? { user: config.user, pass: config.pass } : undefined,\n });\n return transporter;\n}\n\nfunction meetsSeverity(event: ThreatEvent, min?: SmtpConfig['min_severity']): boolean {\n if (!min) return true;\n return (SEVERITY_RANK[event.severity] ?? 0) >= (SEVERITY_RANK[min] ?? 0);\n}\n\nfunction renderBody(event: ThreatEvent): { text: string; html: string } {\n const ts = event.timestamp.toISOString();\n const ip = event.source_ip ? `\\nSource IP: ${event.source_ip}` : '';\n const text =\n `[${event.severity.toUpperCase()}] ${event.module}\\n\\n` +\n `${event.message}${ip}\\n\\n` +\n `When: ${ts}\\nCategory: ${event.category}`;\n const html =\n `<div style=\"font-family:system-ui,sans-serif;line-height:1.5\">` +\n `<h2 style=\"margin:0 0 8px\">⚠ ${event.severity.toUpperCase()} — ${event.module}</h2>` +\n `<p>${event.message}</p>` +\n (event.source_ip ? `<p><strong>Source IP:</strong> <code>${event.source_ip}</code></p>` : '') +\n `<p style=\"color:#888;margin-top:16px\"><small>${ts} · ${event.category}</small></p>` +\n `</div>`;\n return { text, html };\n}\n\nexport function smtpChannel(config: SmtpConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (!meetsSeverity(event, config.min_severity)) return;\n const t = await ensureTransporter(config);\n if (!t) return;\n\n const to = Array.isArray(config.to) ? config.to.join(', ') : config.to;\n if (!to) return;\n\n const { text, html } = renderBody(event);\n await t.sendMail({\n from: config.from,\n to,\n subject: `[ThreatCrush ${event.severity}] ${event.module} — ${event.message.slice(0, 60)}`,\n text,\n html,\n });\n };\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\nexport interface DiscordConfig {\n webhook_url: string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\nconst SEVERITY_COLORS: Record<string, number> = {\n info: 0x2ecc71, // green\n low: 0x3498db, // blue\n medium: 0xf39c12, // orange\n high: 0xe74c3c, // red\n critical: 0x9b59b6, // purple\n};\n\nexport function discordChannel(config: DiscordConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (config.min_severity) {\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[config.min_severity] ?? 0;\n if (eventRank < minRank) return;\n }\n\n const embed = {\n title: `${event.severity === 'critical' ? '🚨' : '⚠️'} [${event.severity.toUpperCase()}] ${event.module}`,\n description: event.message,\n color: SEVERITY_COLORS[event.severity] ?? 0xffffff,\n fields: [\n ...(event.source_ip ? [{ name: 'Source IP', value: `\\`${event.source_ip}\\``, inline: true }] : []),\n { name: 'Category', value: event.category, inline: true },\n { name: 'Time', value: event.timestamp.toISOString(), inline: true },\n ],\n footer: { text: 'ThreatCrush Security Alert' },\n };\n\n await fetch(config.webhook_url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ embeds: [embed] }),\n });\n };\n}\n","import type { ThreatEvent } from '../../types/events.js';\n\nexport interface PagerDutyConfig {\n routing_key: string;\n min_severity?: 'low' | 'medium' | 'high' | 'critical';\n}\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\n// Map ThreatCrush severity to PagerDuty severity\nconst PD_SEVERITY: Record<string, string> = {\n info: 'info',\n low: 'info',\n medium: 'warning',\n high: 'error',\n critical: 'critical',\n};\n\nexport function pagerdutyChannel(config: PagerDutyConfig): (event: ThreatEvent) => Promise<void> {\n return async (event) => {\n if (config.min_severity) {\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[config.min_severity] ?? 0;\n if (eventRank < minRank) return;\n }\n\n const payload = {\n routing_key: config.routing_key,\n event_action: 'trigger',\n payload: {\n summary: `[${event.severity.toUpperCase()}] ${event.module}: ${event.message}`,\n source: 'threatcrush',\n severity: PD_SEVERITY[event.severity] || 'warning',\n timestamp: event.timestamp.toISOString(),\n custom_details: {\n module: event.module,\n category: event.category,\n source_ip: event.source_ip,\n details: event.details,\n },\n },\n };\n\n await fetch('https://events.pagerduty.com/v2/enqueue', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n });\n };\n}\n","import type { ThreatCrushConfig, AlertChannelConfig } from '../../types/config.js';\nimport type { ThreatEvent } from '../../types/events.js';\nimport type { EventBus } from '../event-bus.js';\nimport { smtpChannel, type SmtpConfig } from './smtp.js';\nimport { discordChannel, type DiscordConfig } from './discord.js';\nimport { pagerdutyChannel, type PagerDutyConfig } from './pagerduty.js';\n\ntype Channel = (event: ThreatEvent) => Promise<void>;\n\nexport class AlertDispatcher {\n private channels: Channel[] = [];\n private rateLimits = new Map<string, number[]>();\n\n constructor(private bus: EventBus, private config: ThreatCrushConfig) {\n this.bindChannels();\n bus.on('alert', (event) => { void this.dispatch(event); });\n }\n\n private bindChannels(): void {\n const alerts = this.config.alerts || {};\n for (const [name, raw] of Object.entries(alerts)) {\n const cfg = raw as AlertChannelConfig;\n if (!cfg.enabled) continue;\n if (name === 'webhook' && typeof cfg.url === 'string') {\n this.channels.push(webhookChannel(cfg.url, cfg.secret as string | undefined));\n }\n if (name === 'slack' && typeof cfg.webhook_url === 'string') {\n this.channels.push(slackChannel(cfg.webhook_url));\n }\n if (name === 'email' && typeof cfg.host === 'string' && typeof cfg.from === 'string') {\n this.channels.push(smtpChannel(cfg as unknown as SmtpConfig));\n }\n if (name === 'discord' && typeof cfg.webhook_url === 'string') {\n this.channels.push(discordChannel(cfg as unknown as DiscordConfig));\n }\n if (name === 'pagerduty' && typeof cfg.routing_key === 'string') {\n this.channels.push(pagerdutyChannel(cfg as unknown as PagerDutyConfig));\n }\n }\n }\n\n private checkRateLimit(channelIdx: number, maxPerHour: number = 60): boolean {\n const key = String(channelIdx);\n const now = Date.now();\n const hour = 3600_000;\n let timestamps = this.rateLimits.get(key) || [];\n timestamps = timestamps.filter(t => t > now - hour);\n if (timestamps.length >= maxPerHour) return false;\n timestamps.push(now);\n this.rateLimits.set(key, timestamps);\n return true;\n }\n\n private async dispatch(event: ThreatEvent): Promise<void> {\n await Promise.all(this.channels.map((ch, idx) => {\n if (!this.checkRateLimit(idx)) return Promise.resolve();\n return ch(event).catch(() => {});\n }));\n }\n}\n\nfunction webhookChannel(url: string, secret?: string): Channel {\n return async (event) => {\n const body = JSON.stringify({ event });\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (secret) headers['X-Threatcrush-Signature'] = secret;\n await fetch(url, { method: 'POST', headers, body });\n };\n}\n\nfunction slackChannel(webhookUrl: string): Channel {\n return async (event) => {\n const emoji = event.severity === 'critical' ? ':rotating_light:' : ':warning:';\n const text = `${emoji} *[${event.severity.toUpperCase()}]* \\`${event.module}\\` — ${event.message}${event.source_ip ? ` (from ${event.source_ip})` : ''}`;\n await fetch(webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text }),\n });\n };\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport const CLI_CONFIG_DIR = join(homedir(), '.threatcrush');\nexport const CLI_CONFIG_PATH = join(CLI_CONFIG_DIR, 'config.json');\n\nexport interface CliConfig {\n email?: string;\n user_id?: string;\n token?: string;\n refresh_token?: string;\n expires_at?: number;\n display_name?: string;\n current_org_id?: string;\n current_org_slug?: string;\n}\n\nexport function readCliConfig(): CliConfig {\n try {\n return JSON.parse(readFileSync(CLI_CONFIG_PATH, 'utf-8')) as CliConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeCliConfig(config: CliConfig): void {\n if (!existsSync(CLI_CONFIG_DIR)) mkdirSync(CLI_CONFIG_DIR, { recursive: true });\n writeFileSync(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8');\n try { chmodSync(CLI_CONFIG_PATH, 0o600); } catch { /* non-posix */ }\n}\n\nexport function updateCliConfig(patch: Partial<CliConfig>): CliConfig {\n const current = readCliConfig();\n const next = { ...current, ...patch };\n writeCliConfig(next);\n return next;\n}\n\nexport function clearCliConfig(keys?: Array<keyof CliConfig>): void {\n const current = readCliConfig();\n if (!keys) {\n writeCliConfig({});\n return;\n }\n for (const key of keys) delete current[key];\n writeCliConfig(current);\n}\n\nexport function isLoggedIn(): boolean {\n const cfg = readCliConfig();\n if (!cfg.token) return false;\n if (cfg.expires_at && cfg.expires_at * 1000 < Date.now()) return false;\n return true;\n}\n\nexport function authHeaders(): Record<string, string> {\n const cfg = readCliConfig();\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (cfg.token) headers['Authorization'] = `Bearer ${cfg.token}`;\n return headers;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { banner, logger } from '../core/logger.js';\nimport type { RunResult, StructuredFinding } from '../core/run-result.js';\nimport { summarize } from '../core/run-result.js';\nimport { meetsFailThreshold, SEVERITY_ORDER } from '@threatcrush/scan';\nimport type { ScanFinding, Severity } from '@threatcrush/scan';\nimport { buildSarif, scanDependencies, scanPath } from '@threatcrush/scan/node';\n\nexport type ScanFormat = 'text' | 'json' | 'sarif';\n\nexport interface ScanCommandOptions {\n /**\n * `text` for humans, `sarif` for the Security tab and coverage validators,\n * `json` for anything else. Non-text formats put the payload on stdout (or\n * `--output`) and every human line on stderr, so\n * `threatcrush scan --format sarif > out.sarif` produces a valid file.\n */\n format?: ScanFormat;\n /** Write the machine-readable payload here instead of stdout. */\n output?: string;\n /** Exit non-zero when a finding at or above one of these severities exists. */\n failOn?: readonly Severity[];\n /** Prefix prepended to SARIF URIs when the scan root is not the repo root. */\n pathPrefix?: string;\n /** Print the paths that could not be read, not just the count. */\n verbose?: boolean;\n /**\n * Query OSV.dev for advisories against the resolved lockfile versions.\n * Off by default in the CLI because it is the only part of a scan that\n * needs the network — a CI job should opt in deliberately rather than\n * discover the dependency mid-run.\n */\n dependencies?: boolean;\n}\n\ninterface ScanOutcome {\n result: RunResult;\n findings: ScanFinding[];\n filesScanned: number;\n unreadable: string[];\n suppressed: number;\n root: string;\n}\n\nfunction readVersion(): string {\n for (const candidate of [\n join(__dirname, '..', 'package.json'),\n join(__dirname, '..', '..', 'package.json'),\n ]) {\n try {\n return (\n (JSON.parse(readFileSync(candidate, 'utf-8')) as { version?: string }).version ?? '0.0.0'\n );\n } catch {\n /* try the next candidate */\n }\n }\n return '0.0.0';\n}\n\nconst PKG_VERSION = readVersion();\n\n/** Parse `--fail-on critical,high` into severities, rejecting unknown names. */\nexport function parseFailOn(raw: string | undefined): Severity[] {\n if (!raw) return [];\n const requested = raw\n .split(',')\n .map((part) => part.trim().toLowerCase())\n .filter(Boolean);\n\n const unknown = requested.filter((name) => !SEVERITY_ORDER.includes(name as Severity));\n if (unknown.length > 0) {\n throw new Error(\n `unknown severity in --fail-on: ${unknown.join(', ')} (expected ${SEVERITY_ORDER.join(', ')})`,\n );\n }\n return requested as Severity[];\n}\n\nfunction toRunResult(\n targetPath: string,\n findings: readonly ScanFinding[],\n filesScanned: number,\n): RunResult {\n const structured: StructuredFinding[] = findings.map((finding) => ({\n type: finding.title,\n severity: finding.severity,\n message: finding.message,\n location: `${finding.file}:${finding.line}`,\n details: {\n file: finding.file,\n line: finding.line,\n snippet: finding.excerpt,\n ruleId: finding.ruleId,\n confidence: finding.confidence,\n ...(finding.cwe ? { cwe: finding.cwe } : {}),\n },\n }));\n const counts = summarize(structured);\n\n return {\n type: 'scan',\n target: targetPath,\n findings: structured,\n severity_summary: counts,\n summary:\n findings.length === 0\n ? `No issues found across ${filesScanned} files`\n : `${findings.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`,\n };\n}\n\nfunction failedResult(targetPath: string, message: string): RunResult {\n return {\n type: 'scan',\n target: targetPath,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `Scan failed: ${message}`,\n error: message,\n };\n}\n\n/**\n * Non-interactive scan used by the daemon and the runs worker.\n *\n * Includes dependency advisories, as it always has — the daemon runs on a\n * schedule against a server it can reach the network from, and an advisory\n * published since the last run is the main thing that changed.\n */\nexport async function runScan(targetPath: string): Promise<RunResult> {\n try {\n const report = scanPath(targetPath);\n const findings = [...report.findings, ...(await scanDependencies(targetPath))];\n return toRunResult(targetPath, findings, report.filesScanned);\n } catch (err) {\n return failedResult(targetPath, (err as Error).message);\n }\n}\n\nexport async function scanCommand(\n targetPath: string,\n options: ScanCommandOptions = {},\n): Promise<RunResult> {\n const format = options.format ?? 'text';\n const machineReadable = format !== 'text';\n // Human output goes to stderr whenever stdout is carrying a payload. A\n // banner in the middle of a SARIF document is exactly how \"the scan worked\n // but the pipeline reports zero findings\" happens.\n const say = machineReadable\n ? (line: string) => process.stderr.write(`${line}\\n`)\n : (line: string) => process.stdout.write(`${line}\\n`);\n\n if (!existsSync(targetPath)) {\n say(chalk.red(`Scan target does not exist: ${targetPath}`));\n process.exitCode = 2;\n return failedResult(targetPath, `no such path: ${targetPath}`);\n }\n\n if (!machineReadable) {\n banner();\n logger.info(`Scanning ${chalk.white(targetPath)} for security issues...\\n`);\n }\n\n const spinner = machineReadable ? null : ora({ text: 'Scanning files...', color: 'green' }).start();\n\n let outcome: ScanOutcome;\n try {\n let seen = 0;\n const report = scanPath(targetPath, {\n onFile: () => {\n seen += 1;\n if (spinner) spinner.text = `Scanning files... (${seen} files)`;\n },\n });\n if (options.dependencies) {\n if (spinner) spinner.text = 'Querying OSV.dev for dependency advisories...';\n report.findings.push(...(await scanDependencies(targetPath)));\n }\n outcome = {\n result: toRunResult(targetPath, report.findings, report.filesScanned),\n findings: report.findings,\n filesScanned: report.filesScanned,\n unreadable: report.unreadable,\n suppressed: report.suppressed,\n root: report.root,\n };\n } catch (err) {\n spinner?.fail(`Scan failed: ${(err as Error).message}`);\n process.exitCode = 2;\n return failedResult(targetPath, (err as Error).message);\n }\n\n spinner?.succeed(`Scanned ${outcome.filesScanned} files\\n`);\n\n if (outcome.unreadable.length > 0) {\n // Surfaced, never swallowed. An unexamined file is not a clean one, and a\n // scanner that hides read failures reports silence as safety.\n say(\n chalk.yellow(\n ` ! ${outcome.unreadable.length} path(s) could not be read and were NOT scanned`,\n ),\n );\n if (options.verbose) {\n for (const path of outcome.unreadable) say(chalk.gray(` ${path}`));\n }\n }\n\n if (outcome.suppressed > 0) {\n say(\n chalk.gray(\n ` · ${outcome.suppressed} finding(s) suppressed by inline threatcrush-disable comments`,\n ),\n );\n }\n\n if (machineReadable) {\n emitMachineReadable(format, outcome, targetPath, options, say);\n } else {\n printHuman(outcome);\n }\n\n const failOn = options.failOn ?? [];\n if (meetsFailThreshold(outcome.findings, failOn)) {\n say(\n chalk.red(\n `\\n ✗ findings at or above ${[...failOn].join('/')} — failing as requested by --fail-on`,\n ),\n );\n process.exitCode = 1;\n }\n\n return outcome.result;\n}\n\nfunction emitMachineReadable(\n format: ScanFormat,\n outcome: ScanOutcome,\n targetPath: string,\n options: ScanCommandOptions,\n say: (line: string) => void,\n): void {\n const payload =\n format === 'sarif'\n ? buildSarif(outcome.findings, {\n toolVersion: PKG_VERSION,\n pathPrefix: options.pathPrefix,\n // Relative to the working directory, NOT the scan root. `threatcrush\n // scan vulns` from a repo root must emit `vulns/secrets/x.env`, not\n // `secrets/x.env` — the second form matches nothing in the\n // consumer's view of the repository, so every finding lands\n // \"outside\" whatever it scoped to and a working scan reads as 0%.\n // This is the single most expensive mistake in the whole pipeline\n // and it fails silently. `--path-prefix` covers the remaining case:\n // a scan run from inside the subdirectory it is scanning.\n base: process.cwd(),\n root: resolve(outcome.root),\n })\n : {\n tool: 'threatcrush',\n version: PKG_VERSION,\n target: targetPath,\n filesScanned: outcome.filesScanned,\n unreadable: outcome.unreadable,\n suppressed: outcome.suppressed,\n summary: outcome.result.severity_summary,\n findings: outcome.findings,\n };\n\n const serialized = `${JSON.stringify(payload, null, 2)}\\n`;\n\n if (options.output) {\n mkdirSync(dirname(resolve(options.output)), { recursive: true });\n writeFileSync(options.output, serialized, 'utf-8');\n say(\n chalk.gray(\n ` ${format.toUpperCase()} written to ${options.output} (${outcome.findings.length} finding(s))`,\n ),\n );\n return;\n }\n process.stdout.write(serialized);\n}\n\nfunction printHuman(outcome: ScanOutcome): void {\n const { findings, filesScanned } = outcome;\n\n if (findings.length === 0) {\n console.log(chalk.green.bold(' ✓ No security issues found!'));\n console.log();\n return;\n }\n\n const counts = outcome.result.severity_summary;\n console.log(chalk.white.bold(' Scan Results'));\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.red.bold(counts.critical + ' critical')} ` +\n `${chalk.red(counts.high + ' high')} ` +\n `${chalk.yellow(counts.medium + ' medium')} ` +\n `${chalk.gray(counts.low + ' low')}`,\n );\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log();\n\n for (const finding of findings) {\n const label = finding.severity.toUpperCase();\n const badge =\n finding.severity === 'critical'\n ? chalk.bgRed.white.bold(` ${label} `)\n : finding.severity === 'high'\n ? chalk.red(`[${label}]`)\n : finding.severity === 'medium'\n ? chalk.yellow(`[${label}]`)\n : chalk.gray(`[${label}]`);\n\n console.log(` ${badge} ${chalk.white.bold(finding.title)}`);\n console.log(\n ` ${chalk.gray('File:')} ${chalk.cyan(finding.file)}:${chalk.yellow(String(finding.line))}`,\n );\n console.log(` ${chalk.gray('Info:')} ${finding.message}`);\n if (finding.consequence) {\n console.log(` ${chalk.gray('Risk:')} ${chalk.dim(finding.consequence)}`);\n }\n if (finding.excerpt) {\n console.log(` ${chalk.gray('Code:')} ${finding.excerpt}`);\n }\n console.log(\n ` ${chalk.gray('Rule:')} ${chalk.dim(finding.ruleId)}` +\n (finding.cwe ? chalk.dim(` · ${finding.cwe}`) : '') +\n chalk.dim(` · confidence: ${finding.confidence}`),\n );\n console.log();\n }\n\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.white.bold(`${findings.length} issue(s) found`)} across ${filesScanned} files`,\n );\n console.log();\n}\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n","// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n","import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n","import chalk from 'chalk';\nimport type { EventSeverity } from '../types/events.js';\n\nconst SEVERITY_COLORS: Record<EventSeverity, (s: string) => string> = {\n info: chalk.green,\n low: chalk.cyan,\n medium: chalk.yellow,\n high: chalk.red,\n critical: chalk.bgRed.white.bold,\n};\n\nconst LEVEL_COLORS: Record<string, (s: string) => string> = {\n debug: chalk.gray,\n info: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n};\n\nexport function severityColor(severity: EventSeverity, text: string): string {\n return (SEVERITY_COLORS[severity] || chalk.white)(text);\n}\n\nexport function formatTimestamp(date: Date = new Date()): string {\n return chalk.gray(date.toISOString().replace('T', ' ').slice(0, 19));\n}\n\nexport function formatEvent(\n module: string,\n severity: EventSeverity,\n message: string,\n ip?: string,\n): string {\n const ts = formatTimestamp();\n const sev = severityColor(severity, `[${severity.toUpperCase()}]`.padEnd(10));\n const mod = chalk.cyan(`[${module}]`.padEnd(14));\n const src = ip ? chalk.magenta(` (${ip})`) : '';\n return `${ts} ${sev} ${mod} ${message}${src}`;\n}\n\nexport const logger = {\n debug: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.debug('[DEBUG]')} ${msg}`),\n info: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.info('[INFO]')} ${msg}`),\n warn: (msg: string) => console.log(`${formatTimestamp()} ${LEVEL_COLORS.warn('[WARN]')} ${msg}`),\n error: (msg: string) => console.error(`${formatTimestamp()} ${LEVEL_COLORS.error('[ERROR]')} ${msg}`),\n success: (msg: string) => console.log(`${formatTimestamp()} ${chalk.green('[OK]')} ${msg}`),\n threat: (msg: string, ip?: string) => {\n const src = ip ? chalk.magenta(` from ${ip}`) : '';\n console.log(`${formatTimestamp()} ${chalk.red.bold('[THREAT]')} ${chalk.red(msg)}${src}`);\n },\n};\n\nexport function banner(): void {\n console.log(chalk.green.bold(`\n ████████╗██╗ ██╗██████╗ ███████╗ █████╗ ████████╗ ██████╗██████╗ ██╗ ██╗███████╗██╗ ██╗\n ╚══██╔══╝██║ ██║██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗██║ ██║██╔════╝██║ ██║\n ██║ ███████║██████╔╝█████╗ ███████║ ██║ ██║ ██████╔╝██║ ██║███████╗███████║\n ██║ ██╔══██║██╔══██╗██╔══╝ ██╔══██║ ██║ ██║ ██╔══██╗██║ ██║╚════██║██╔══██║\n ██║ ██║ ██║██║ ██║███████╗██║ ██║ ██║ ╚██████╗██║ ██║╚██████╔╝███████║██║ ██║\n ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝\n `));\n console.log(chalk.gray(' All-in-one security agent daemon — v0.1.0\\n'));\n}\n","import os from 'node:os';\n\nexport type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';\n\nexport interface StructuredFinding {\n type: string;\n severity: Severity;\n message: string;\n location?: string;\n details?: Record<string, unknown>;\n}\n\nexport interface RunResult {\n type: 'scan' | 'pentest';\n target: string;\n findings: StructuredFinding[];\n severity_summary: Record<Severity, number>;\n summary: string;\n error?: string;\n}\n\nexport function emptyCounts(): Record<Severity, number> {\n return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };\n}\n\nexport function summarize(findings: StructuredFinding[]): Record<Severity, number> {\n const counts = emptyCounts();\n for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;\n return counts;\n}\n\nexport function workerId(): string {\n return `${os.hostname()}/${process.pid}`;\n}\n","/**\n * Shared vocabulary for `threatcrush scan`.\n *\n * The scan pipeline is deliberately three separable pieces — rules produce\n * findings, the engine walks the tree, the reporters serialise. Keeping the\n * types here means a reporter never has to import a rule table to know what a\n * finding looks like.\n */\n\nexport type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';\n\n/**\n * How much the scanner is claiming.\n *\n * `pattern` the dangerous construct is present on the line. Nothing more.\n * `contextual` the construct sits alongside something that looks like\n * attacker-controlled input. Still not proof of exploitability,\n * but a materially stronger claim — and the only one allowed to\n * present at the rule's full severity.\n * `evidence` the match *is* the finding, not a proxy for it. A hardcoded\n * AWS key is a committed credential whether or not any request\n * ever reaches it, so the severity cap below does not apply.\n *\n * This mirrors the confidence model in `modules/code-scanner` (PRD 0004), for\n * the same reason: a regex is not data-flow analysis, and a scanner that blurs\n * the two produces confident-sounding findings that waste triage time.\n */\nexport type Confidence = 'pattern' | 'contextual' | 'evidence';\n\nexport type ScanLanguage =\n | 'javascript'\n | 'typescript'\n | 'python'\n | 'ruby'\n | 'go'\n | 'java'\n | 'php'\n | 'shell'\n | 'config'\n | 'other';\n\nexport interface ScanFinding {\n /** Stable rule identifier, e.g. `js-sql-string-building`. Used as the SARIF ruleId. */\n ruleId: string;\n /** Short human title for the construct, e.g. \"SQL assembled by concatenation\". */\n title: string;\n /** Path relative to the scan root, POSIX-separated. */\n file: string;\n /** 1-based. Whole-file findings report 1, never 0 — SARIF forbids 0. */\n line: number;\n severity: Severity;\n confidence: Confidence;\n /** What was found, in a sentence. Shown to the operator. */\n message: string;\n /** What happens if it is real. An operator triages on consequence. */\n consequence?: string;\n /** `CWE-89`. Absent for findings with no clean CWE mapping. */\n cwe?: string;\n /**\n * The matched source line, trimmed. Redacted by the reporters for secret\n * findings — see `redactSecret`.\n */\n excerpt: string;\n /** True when `excerpt` may contain credential material. */\n sensitive?: boolean;\n category: 'secret' | 'code' | 'manifest' | 'dependency' | 'file';\n}\n\nexport const SEVERITY_ORDER: readonly Severity[] = ['info', 'low', 'medium', 'high', 'critical'];\n\nexport function severityRank(severity: Severity): number {\n const index = SEVERITY_ORDER.indexOf(severity);\n return index === -1 ? 0 : index;\n}\n\n/**\n * Cap for a bare pattern match.\n *\n * A construct that merely *exists* never presents as high or critical. Enforced\n * centrally rather than per-rule so no future rule can opt out of it by\n * accident.\n */\nexport function severityFor(declared: Severity, confidence: Confidence): Severity {\n if (confidence !== 'pattern') return declared;\n return severityRank(declared) > severityRank('medium') ? 'medium' : declared;\n}\n","/**\n * Code-level vulnerability rules for `threatcrush scan`.\n *\n * Why this file exists\n * --------------------\n * Measured against the public testbed at `profullstack/malware-test-prs`, the\n * CLI scored 15.6% true-positive rate with a 0.0% false-positive rate: it found\n * every hardcoded credential and none of the code-level classes — no SQL\n * injection, XSS, SSRF, command injection, deserialisation or template\n * injection. ThreatCrush was a secrets scanner wearing a code scanner's name.\n *\n * These rules close that gap without giving up the number that was actually\n * worth having. The false-positive denominator in that testbed is a control\n * group of `SAFE:` lines — each one a *correct* implementation of the same\n * pattern the neighbouring vulnerable code gets wrong. A scanner that flags one\n * is pattern-matching on syntax instead of following the data. So every rule\n * here is built against both halves: it must fire on the vulnerable shape and\n * stay silent on the corrected shape standing next to it.\n *\n * Three mechanisms do that work:\n *\n * 1. **Shape, not keyword.** `db.query(\"SELECT … $1\", [id])` and\n * `db.query(\"SELECT … '\" + id + \"'\")` both contain `SELECT`. Only the\n * second concatenates, and only the second matches.\n * 2. **Guard windows.** A construct is exonerated by the code around it —\n * an allow-list two lines up, a `realpath` on the same line, an\n * `ObjectInputFilter` installed before the `readObject()`. Comment lines\n * are excluded from the window, because a comment saying \"no allow-list\n * here\" is not an allow-list.\n * 3. **Confidence.** A construct that merely exists is capped at medium.\n * Escalation requires visible untrusted input. See `types.ts`.\n *\n * What this is not: data-flow analysis. It is line-oriented matching with a\n * small amount of local context, and it says so. Classes that genuinely need\n * whole-function reasoning — missing CSRF tokens, check-then-use races,\n * integer overflow — are deliberately absent rather than approximated by a\n * rule that would flag every session read in the codebase. See KNOWN_GAPS.\n */\n\nimport type { Confidence, ScanLanguage, Severity } from './types';\nimport { severityFor } from './types';\n\nexport interface CodeRule {\n id: string;\n title: string;\n /** What happens if it is real. An operator triages on consequence. */\n consequence: string;\n cwe: string;\n severity: Severity;\n /** Languages the rule applies to. `undefined` means every language. */\n languages?: readonly ScanLanguage[];\n pattern: RegExp;\n /**\n * The rule describes a construct that is ordinary on its own — reading a\n * file from a computed path is just software. Only report it when untrusted\n * input is visible nearby.\n */\n needsContext?: boolean;\n /**\n * The construct *is* the defect, so its severity does not depend on context.\n *\n * The default model caps a finding at medium unless untrusted input is\n * visible nearby, which is right for injection: `exec(cmd)` is only a\n * vulnerability once `cmd` can be influenced. It is wrong for a whole class\n * of rules where nothing nearby changes the answer. `curl -k` against HTTPS\n * is a machine-in-the-middle hole whether or not a positional parameter\n * appears six lines above it; DES is broken in every file that uses it.\n *\n * Marking those rules `inherent` reports them at confidence `evidence` and\n * at their declared severity, the same treatment the credential rules get\n * for the same reason — a committed AWS key is a committed AWS key.\n *\n * Do not reach for this to make a rule look important. It is for rules whose\n * finding text would be identical no matter what surrounds the line.\n */\n inherent?: boolean;\n /**\n * Extra evidence that must appear in the guard window for the rule to fire.\n * Used where the dangerous part is the *combination* — a base64 blob is\n * harmless until something executes it.\n */\n requires?: RegExp;\n /**\n * Evidence that must appear somewhere in the file, not merely in the guard\n * window.\n *\n * For rules whose *applicability* is settled far from the match. Whether a\n * `.parse()` call is XML parsing is decided by an import at the top of the\n * file, which in a 1,600-line source is nowhere near the line that matched;\n * widening `guardBack` far enough to reach it would drag in unrelated\n * evidence for every other rule. Distinct from `requires`, which asks\n * whether the surrounding lines complete a dangerous combination.\n */\n fileRequires?: RegExp;\n /**\n * Evidence that the construct is already handled. `false` opts the rule out\n * of the generic guard entirely — the CWE-532 rules are *about* reading\n * `process.env`, so the generic guard would veto every true positive.\n */\n guard?: RegExp | false;\n /**\n * Evidence — on the matched line ONLY — that this occurrence is safe.\n *\n * Distinct from `guard`, which also searches the surrounding window. That\n * breadth is right for \"the value was sanitised three lines up\" but wrong\n * for properties of the line itself: a static `innerHTML` assignment says\n * nothing about a dynamic one two lines below it, and a context-scoped\n * guard would silently veto the dynamic one too.\n */\n lineGuard?: RegExp;\n /** Lines of context searched backwards for guards and required evidence. */\n guardBack?: number;\n /**\n * Lines searched *forwards*. Zero for almost everything: code that fixes a\n * problem generally runs before the problem. XML parser hardening is the\n * exception — the factory is constructed, then configured, so the evidence\n * is below the match.\n */\n guardForward?: number;\n}\n\n/**\n * Things that look like attacker-controlled input, per language family.\n *\n * Deliberately shallow. It is a heuristic for *ranking*, not a taint-source\n * model. A real source list would be framework-aware and interprocedural,\n * which is exactly what this subsystem promises not to pretend to be.\n */\n/**\n * `searchParams` is a read *and* a write API. `params.get('q')` is inbound\n * data; `url.searchParams.set('limit', 50)` is an outbound URL being built,\n * and treating the two alike marked every client of every third-party API as\n * taking untrusted input — which is what made the SSRF rule fire on requests\n * whose host is a compile-time constant. Only the reading half is evidence.\n */\nconst UNTRUSTED_JS =\n /\\b(?:req|request|ctx|context)\\s*\\.\\s*(?:body|query|params|param|headers|cookies|url|files)\\b|\\bprocess\\.argv\\b|\\bwindow\\.location\\b|\\bdocument\\.location\\b|\\blocation\\.(?:search|hash|href)\\b|\\bsearchParams\\s*\\.\\s*(?:get|getAll|has|entries|keys|values|forEach)\\b|\\bgetParameter\\s*\\(|\\bgetQueryString\\s*\\(|\\bgetInputStream\\s*\\(/;\n\nconst UNTRUSTED_PY = /\\brequest\\b|\\bparams\\b|\\bflask\\b|\\bsys\\.argv\\b|\\bos\\.environ\\b\\s*\\[/;\n\nconst UNTRUSTED_RB = /\\bparams\\s*\\[|\\brequest\\b|\\bcookies\\s*\\[/;\n\nconst UNTRUSTED_GO =\n /\\br\\s*\\.\\s*(?:URL|Form|Body|Header|PostForm)\\b|\\bFormValue\\s*\\(|\\bQuery\\s*\\(\\s*\\)\\s*\\.\\s*Get\\s*\\(|\\bmux\\.Vars\\s*\\(/;\n\nconst UNTRUSTED_JAVA =\n /\\bgetParameter\\s*\\(|\\bgetQueryString\\s*\\(|\\bgetHeader\\s*\\(|\\bgetInputStream\\s*\\(|\\bgetCookies\\s*\\(|\\b@RequestParam\\b|\\b@PathVariable\\b/;\n\n/**\n * Untrusted input to a shell script: what the caller controls.\n *\n * Positional parameters and `read` are the whole surface. Environment\n * variables are deliberately absent — a script's own configuration arrives\n * that way, so treating `$PREFIX` as attacker-controlled would mark every\n * line of every installer.\n */\nconst UNTRUSTED_SH =\n /\\$\\{?[1-9]\\d*\\b|\\$[@*]|\\$\\{@\\}|\\bread\\s+(?:-\\S+\\s+)*[A-Za-z_]\\w*|\\$\\{?REPLY\\b|\\$\\{?QUERY_STRING\\b/;\n\n/** PHP's superglobals are the request, verbatim. */\nconst UNTRUSTED_PHP =\n /\\$_(?:GET|POST|REQUEST|COOKIE|FILES|SERVER)\\b|\\bphp:\\/\\/input\\b|\\bgetallheaders\\s*\\(/;\n\nexport function untrustedPatternFor(language: ScanLanguage): RegExp {\n switch (language) {\n case 'php':\n return UNTRUSTED_PHP;\n case 'shell':\n return UNTRUSTED_SH;\n case 'python':\n return UNTRUSTED_PY;\n case 'ruby':\n return UNTRUSTED_RB;\n case 'go':\n return UNTRUSTED_GO;\n case 'java':\n return UNTRUSTED_JAVA;\n default:\n return UNTRUSTED_JS;\n }\n}\n\n/**\n * Evidence that the dangerous construct on this line is already handled.\n *\n * Every entry here was added because a *correct* implementation in the testbed\n * corpus was otherwise flagged. They are named after what the safe code does,\n * not after what the finding is:\n *\n * allow/whitelist an allow-list decides what reaches the sink\n * escape/sanitize the value is encoded for its output context\n * realpath/… the path is resolved and re-checked before use\n * process.env/… the value comes from the environment, not the request\n * ObjectInputFilter a class allow-list is installed on the stream\n *\n * A guard match suppresses the finding rather than downgrading it. Reporting\n * \"we saw an allow-list but flagged it anyway\" is the behaviour that makes\n * operators stop reading scanner output.\n */\nexport const GENERIC_GUARD =\n // `esc(`, `aEsc(`, `htmlEscape(`, `escapeHtml(` — the escaper is almost\n // never *named* `escapeHtml` in real code. It gets aliased to something\n // short because it is called on nearly every interpolation, so matching only\n // the long spellings reported the codebases that escape most rigorously.\n //\n // The identifier must END at the escaper (with at most a known output-context\n // suffix). An earlier, looser form also matched `describe(`, which would have\n // silenced findings across every test file in every repository.\n /\\ballow(?:ed|list|_list|ed_hosts)?\\b|\\bwhitelist\\b|\\b\\w{0,6}[Ee]sc(?:ape)?(?:[Hh]tml|HTML|[Xx]ml|XML|[Ss]ql|[Aa]ttr|[Jj]s|[Uu]ri|[Uu]rl)?\\s*\\(|\\bhtml_escape\\b|\\bhtmlspecialchars\\s*\\(|\\bsanitiz\\w*\\b|\\bencoded\\b|\\brealpath\\b|\\bcommonpath\\b|\\bresolve\\(\\)\\.startsWith\\b|\\bprocess\\.env\\b|\\bos\\.environ\\b|\\bgetenv\\b|\\bENV\\s*\\[|setObjectInputFilter|ObjectInputFilter/i;\n\n/** Evidence that an XML parser factory has been hardened against XXE. */\nconst XXE_GUARD =\n /FEATURE_SECURE_PROCESSING|setExpandEntityReferences|disallow-doctype-decl|external-general-entities|external-parameter-entities|setXIncludeAware\\s*\\(\\s*false/;\n\n/**\n * Evidence that a Java source parses XML at all.\n *\n * The package names are the reliable half: a file that reaches for\n * `javax.xml.parsers` or `org.xml.sax` has declared its intent at the top,\n * whatever the local variable ends up being called. The bare type names cover\n * sources that import by wildcard or sit in the same package.\n */\nconst XML_PARSING_FILE =\n /\\b(?:javax\\.xml|org\\.xml\\.sax|org\\.w3c\\.dom|org\\.jdom2?|org\\.dom4j|XmlPullParser|DocumentBuilderFactory|DocumentBuilder|SAXParserFactory|SAXParser|XMLInputFactory|XMLReaderFactory|XMLReader|SAXBuilder|SAXReader)\\b/;\n\n/** A sink that executes whatever string reaches it. */\nconst CODE_SINK =\n /\\bglobalThis\\s*\\[|\\bconstructor\\b|\\beval\\b|\\bFunction\\b|\\brun\\s*\\(|\\bvm\\s*\\.\\s*run/;\n\n/** A sink whose output is retained: a log, a console, an outbound request. */\nconst EXFIL_SINK = /\\bconsole\\s*\\.\\s*(?:log|debug|info|warn|error)\\s*\\(|\\bfetch\\s*\\(|\\baxios\\b|\\brequest\\s*\\(|\\.\\s*send\\s*\\(/;\n\n/**\n * SQL text that is being *assembled* rather than parameterised.\n *\n * The four tails are the four ways to build a string in the languages this\n * covers: `+` concatenation, `${}` template interpolation, `%`/`.format()`\n * substitution, and Ruby's `#{}`. A bound placeholder (`$1`, `?`, `%s` passed\n * as an argument) leaves a comma after the closing quote and matches none of\n * them — which is exactly how the safe counterparts stay unflagged.\n */\n// Each verb requires the clause that makes it SQL rather than an English word.\n//\n// The bare forms — `INSERT`, `UPDATE`, `DELETE`, `DROP`, a lone `SELECT` — were\n// the source of this rule's false positives: `\\bINSERT\\b` matches the `insert`\n// in a React key `` `insert-${i}` ``, and `\\bUPDATE\\b` matches `Update` in a\n// log line `` `Update finished in ${ms}ms` ``. Both read as SQL injection.\n//\n// Real SQL pairs the verb with structure — `SELECT … FROM`, `INSERT INTO`,\n// `UPDATE … SET`, `DELETE FROM`, `DROP TABLE`. Requiring it keeps every\n// injection shape the corpus and the unit tests exercise (all of which are\n// `SELECT … FROM` or `DELETE FROM`) while a verb standing alone as prose no\n// longer qualifies. The `SELECT`/`UPDATE` look-aheads stay inside one string\n// literal — the character class excludes quotes and backticks — so the clause\n// must live in the same statement, not merely somewhere later on the line.\nconst SQL_KEYWORDS =\n \"SELECT\\\\b(?=[^`'\\\"\\\\n]*\\\\bFROM\\\\b)\" +\n \"|INSERT\\\\s+INTO\" +\n \"|UPDATE\\\\b(?=[^`'\\\"\\\\n]*\\\\bSET\\\\b)\" +\n \"|DELETE\\\\s+FROM\" +\n \"|DROP\\\\s+(?:TABLE|DATABASE|INDEX|VIEW|SCHEMA)\" +\n \"|TRUNCATE\\\\s+TABLE\" +\n \"|UNION\\\\s+SELECT\";\n\n/**\n * A quoted string containing a SQL verb.\n *\n * Two variants, one per quote character, because the interesting strings\n * contain the *other* quote:\n *\n * \"SELECT id FROM users WHERE id = '\" + id + \"'\"\n *\n * A single `[\"'][^\"'\\n]*` class stops dead at that inner `'` and matches\n * nothing — which silently drops the most common SQL-injection shape in every\n * language at once. Match a double-quoted string with a class that excludes\n * only `\"`, and vice versa.\n */\nconst SQL_IN_DOUBLE = `\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*\"`;\nconst SQL_IN_SINGLE = `'[^'\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^'\\\\n]*'`;\nconst SQL_STRING = `(?:${SQL_IN_DOUBLE}|${SQL_IN_SINGLE})`;\n\nexport const CODE_RULES: readonly CodeRule[] = [\n // ── Injection: SQL ───────────────────────────────────────────────────────\n {\n id: 'sql-string-concatenation',\n title: 'SQL assembled by concatenation or interpolation',\n consequence:\n 'A quote in the interpolated value changes the query’s meaning — the query runs as the attacker wrote it, not as you wrote it.',\n cwe: 'CWE-89',\n severity: 'critical',\n // The tail is what distinguishes assembly from parameterisation. A bound\n // query leaves a comma after the closing quote (`\"… = $1\", [id]`) and\n // matches none of these.\n pattern: new RegExp(\n `${SQL_STRING}\\\\s*\\\\+|` +\n `${SQL_STRING}\\\\s*%\\\\s*[\\\\w(]|` +\n `${SQL_STRING}\\\\s*\\\\.\\\\s*format\\\\s*\\\\(|` +\n '\\\\+\\\\s*(?:\"[^\"\\\\n]*|\\'[^\\'\\\\n]*)(?:WHERE|ORDER\\\\s+BY|VALUES|SET)\\\\b',\n 'i',\n ),\n },\n {\n id: 'sql-template-interpolation',\n title: 'SQL built from a template literal or f-string',\n consequence:\n 'Template interpolation is string concatenation with nicer syntax — it binds nothing and escapes nothing.',\n cwe: 'CWE-89',\n severity: 'critical',\n pattern: new RegExp(\n `\\`[^\\`\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\\`\\\\n]*\\\\$\\\\{|` +\n `\\\\bf\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*\\\\{|` +\n `\\\\bf'[^'\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^'\\\\n]*\\\\{`,\n 'i',\n ),\n },\n {\n id: 'sql-format-call',\n title: 'SQL text produced by a format helper',\n consequence:\n '`Sprintf`/`String.format` substitute without quoting; the resulting string is concatenated SQL by another name.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['go', 'java'],\n pattern: new RegExp(\n `\\\\b(?:fmt\\\\.Sprintf|String\\\\.format)\\\\s*\\\\(\\\\s*\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b`,\n 'i',\n ),\n },\n {\n id: 'rb-sql-interpolation',\n title: 'ActiveRecord query built by string interpolation',\n consequence:\n '`where(\"… #{value}\")` interpolates before the adapter sees it, so no binding ever happens.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['ruby'],\n pattern:\n /\\b(?:where|find_by_sql|execute|select_all|select_values|order|group|pluck)\\s*[( ]\\s*(?:\"[^\"\\n]*|'[^'\\n]*)#\\{/,\n },\n\n // ── Injection: OS command ────────────────────────────────────────────────\n {\n id: 'js-shell-exec-interpolation',\n title: 'shell execution with an interpolated string',\n consequence: 'A `;` or `$(…)` in the interpolated value runs as the server user.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:exec|execSync|spawn|spawnSync)\\s*\\(\\s*(?:`[^`]*\\$\\{|['\"][^'\"]*['\"]\\s*\\+|[a-zA-Z_$][\\w$]*\\s*\\+)/,\n },\n {\n id: 'py-shell-command-string',\n title: 'shell command built from a string',\n consequence:\n '`os.system` and `shell=True` hand the string to `/bin/sh`, which happily interprets metacharacters.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['python'],\n pattern:\n /\\bos\\.(?:system|popen)\\s*\\(\\s*(?:f?['\"][^'\"]*['\"]\\s*(?:\\+|%|\\.\\s*format)|f['\"]|[a-zA-Z_]\\w*\\s*[,)])|\\bsubprocess\\.(?:run|call|check_call|check_output|Popen)\\s*\\([^)]*\\bshell\\s*=\\s*True/,\n },\n {\n id: 'go-shell-exec-command',\n title: 'exec.Command invoking a shell',\n consequence:\n 'Passing `sh -c` re-introduces the shell that `exec.Command`’s argv interface exists to avoid.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['go'],\n pattern: /\\bexec\\.Command(?:Context)?\\s*\\(\\s*(?:ctx\\s*,\\s*)?\"(?:\\/bin\\/)?(?:sh|bash|zsh|cmd|powershell)\"\\s*,\\s*\"(?:-c|\\/c)\"/,\n },\n {\n id: 'rb-backtick-interpolation',\n title: 'backtick command with interpolation',\n consequence: 'Ruby backticks are a shell invocation; `#{}` inside one is command injection.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['ruby'],\n pattern: /`[^`\\n]*#\\{|\\bsystem\\s*\\(\\s*[\"'][^\"'\\n]*#\\{|%x\\[[^\\]]*#\\{/,\n },\n\n // ── Injection: dynamic code ──────────────────────────────────────────────\n {\n id: 'js-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence: 'Any string reaching this call executes as code with the process’ privileges.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\beval\\s*\\(|\\bnew\\s+Function\\s*\\(|\\bvm\\s*\\.\\s*run(?:InThisContext|InNewContext|InContext)\\s*\\(|\\bset(?:Timeout|Interval)\\s*\\(\\s*(?:['\"`]|(?:req|request|ctx|params|query|body)\\b)/,\n },\n {\n id: 'js-indirect-code-sink',\n title: 'code sink reached indirectly',\n consequence:\n 'Resolving `eval`/`Function` through `globalThis[…]` or `.constructor` hides the sink from literal matching. Legitimate code has no reason to.',\n cwe: 'CWE-506',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bglobalThis\\s*\\[\\s*[a-zA-Z_$][\\w$]*\\s*\\]|\\(\\s*function\\s*\\(\\s*\\)\\s*\\{\\s*\\}\\s*\\)\\s*\\.\\s*constructor/,\n },\n {\n id: 'js-encoded-payload-execution',\n title: 'encoded blob decoded next to a code sink',\n consequence:\n 'A base64 literal that is decoded and executed is the standard shape of a planted backdoor; the encoding exists to defeat review.',\n cwe: 'CWE-506',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bBuffer\\.from\\s*\\(\\s*[\\w.$]+\\s*,\\s*['\"]base64['\"]\\s*\\)|\\batob\\s*\\(\\s*[\\w.$]+\\s*\\)/,\n requires: CODE_SINK,\n guardBack: 6,\n guardForward: 3,\n },\n {\n id: 'py-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence: 'Any string reaching this call executes as Python with the process’ privileges.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\b(?:eval|exec)\\s*\\(\\s*(?!['\"]\\s*\\))[a-zA-Z_(f'\"]/,\n needsContext: true,\n },\n {\n id: 'rb-dynamic-dispatch',\n title: 'dynamic code execution or unrestricted #send',\n consequence:\n '`eval` runs arbitrary Ruby; unrestricted `#send` lets the caller invoke any method on the receiver, including private ones.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['ruby'],\n pattern: /\\beval\\s*\\(|\\binstance_eval\\s*\\(|\\bclass_eval\\s*\\(|\\.\\s*send\\s*\\(\\s*(?:params|request|args)\\b/,\n },\n\n // ── Cross-site scripting ─────────────────────────────────────────────────\n {\n id: 'js-unescaped-html-sink',\n title: 'unescaped HTML rendering',\n consequence: 'A script tag in the value executes in the victim’s session — stored or reflected XSS.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bdangerouslySetInnerHTML\\s*=|\\.\\s*(?:innerHTML|outerHTML)\\s*=\\s*(?!\\s*['\"`]\\s*['\"`]\\s*;?\\s*$)|\\bdocument\\s*\\.\\s*write(?:ln)?\\s*\\(|\\.\\s*insertAdjacentHTML\\s*\\(/,\n /**\n * A whole-statement assignment of a string with no interpolation and no\n * concatenation carries no data, so it cannot carry attacker data. This\n * was the single largest source of noise: a codebase that builds its UI\n * with innerHTML reports every static heading and spinner as XSS, and a\n * rule that flags 40 safe lines to catch one real one gets switched off.\n *\n * Line-scoped on purpose — see `lineGuard`.\n */\n lineGuard:\n /(?:innerHTML|outerHTML)\\s*=\\s*(?:'[^'\\\\]*'|\"[^\"\\\\]*\"|`[^`$\\\\]*`)\\s*;?\\s*$/,\n },\n {\n id: 'java-html-writer-concatenation',\n title: 'HTML written to the response by concatenation',\n consequence:\n 'The servlet writer performs no encoding; a value concatenated into markup is rendered as markup.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['java'],\n pattern: /\\b(?:println|print|write)\\s*\\(\\s*\"[^\"\\n]*<[^\"\\n]*\"\\s*\\+/,\n },\n {\n id: 'rb-unescaped-output',\n title: 'Rails output escaping bypassed',\n consequence:\n '`html_safe` and `raw` tell Rails the string is already safe. If it came from a parameter, it is not.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['ruby'],\n pattern: /\\.\\s*html_safe\\b|\\braw\\s*\\(\\s*(?:params|request|@)|\\blink_to\\s+[^,\\n]+,\\s*params\\s*\\[/,\n },\n {\n id: 'py-template-autoescape-off',\n title: 'template rendering with escaping disabled',\n consequence:\n 'With autoescape off — or a `|safe` filter — every interpolated value is rendered as markup.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['python'],\n pattern: /\\bEnvironment\\s*\\([^)]*\\bautoescape\\s*=\\s*False|\\|\\s*safe\\b|\\bMarkup\\s*\\(\\s*(?!['\"])/,\n },\n {\n id: 'py-template-from-input',\n title: 'template compiled from a non-literal source',\n consequence:\n 'Server-side template injection. In Jinja2 the sandbox is escapable, so this escalates from XSS to remote code execution.',\n cwe: 'CWE-1336',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\bTemplate\\s*\\(\\s*(?!['\"])[a-zA-Z_]/,\n needsContext: true,\n },\n\n // ── Server-side request forgery ──────────────────────────────────────────\n {\n id: 'js-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\bfetch\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]|\\bhttps?\\s*\\.\\s*(?:get|request)\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]|\\baxios\\s*\\.\\s*get\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*[,)]/,\n needsContext: true,\n },\n {\n id: 'py-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['python'],\n pattern:\n /\\brequests\\.(?:get|request|head)\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]|\\burlopen\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]|\\bhttpx\\.get\\s*\\(\\s*[a-zA-Z_]\\w*\\s*[,)]/,\n needsContext: true,\n },\n {\n id: 'go-ssrf-outbound-request',\n title: 'outbound request to a non-constant URL',\n consequence:\n 'An attacker who controls the URL reaches the cloud metadata endpoint, localhost, and every service on the private network.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['go'],\n pattern: /\\bhttp\\.(?:Get|Post|Head)\\s*\\(\\s*(?:[a-zA-Z_]\\w*\\s*[,)]|\"[^\"]*\"\\s*\\+)/,\n needsContext: true,\n },\n\n // ── Open redirect ────────────────────────────────────────────────────────\n {\n id: 'js-open-redirect',\n title: 'redirect to a non-constant destination',\n consequence:\n 'Your domain becomes the credible first hop of a phishing chain; the victim sees your hostname in the link they clicked.',\n cwe: 'CWE-601',\n severity: 'medium',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:res|response)\\s*\\.\\s*redirect\\s*\\(\\s*[a-zA-Z_$][\\w$]*\\s*\\)|\\bwindow\\s*\\.\\s*location(?:\\s*\\.\\s*(?:href|replace))?\\s*(?:=\\s*[a-zA-Z_$]|\\(\\s*[a-zA-Z_$][\\w$]*\\s*\\))/,\n needsContext: true,\n },\n\n // ── Deserialisation ──────────────────────────────────────────────────────\n {\n id: 'py-unsafe-deserialization',\n title: 'deserialisation of untrusted data',\n consequence:\n '`pickle` and `yaml.load` instantiate arbitrary types during parsing — a crafted payload is remote code execution, not a parse error.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['python'],\n pattern: /\\bpickle\\.loads?\\s*\\(|\\bcPickle\\.loads?\\s*\\(|\\bmarshal\\.loads\\s*\\(|\\byaml\\.load\\s*\\(|\\bjsonpickle\\.decode\\s*\\(/,\n },\n {\n id: 'java-unsafe-deserialization',\n title: 'Java deserialisation without a class filter',\n consequence:\n 'A gadget chain in the classpath turns `readObject()` on attacker bytes into remote code execution.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['java'],\n pattern: /\\breadObject\\s*\\(\\s*\\)|\\bnew\\s+ObjectInputStream\\s*\\(/,\n guardBack: 8,\n // The stream is constructed, *then* filtered. Without a forward window the\n // guarded case matches on its constructor line and reports a correct\n // implementation as a finding.\n guardForward: 6,\n },\n {\n id: 'js-unsafe-yaml-load',\n title: 'YAML parsed with type resolution enabled',\n consequence: 'A crafted document can instantiate arbitrary types during parsing.',\n cwe: 'CWE-502',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern: /\\byaml\\s*\\.\\s*load\\s*\\((?![^)]*safe)|\\bloadAll\\s*\\([^)]*unsafe/i,\n },\n\n // ── XML external entities ────────────────────────────────────────────────\n //\n // Evidence that a file parses XML at all. The XXE rules match on receiver\n // *names* — `builder.parse(is)` is the shape the vulnerability actually takes,\n // and the declared type is rarely on that line — so without this the pattern\n // reads any `.parse()` on anything suffixed Builder, Parser or Reader as XML.\n // In practice that meant a hostname-mask parser (`HostMask.Parser.parse(...)`)\n // was reported as CWE-611 at high severity.\n //\n // An import is the cheapest honest signal: a file that parses XML says so at\n // the top, and one that never mentions XML is not parsing it.\n {\n id: 'java-xxe-parser-defaults',\n title: 'XML parser left on its insecure defaults',\n consequence:\n 'External entity expansion reads local files and makes outbound requests on the parser’s behalf — file disclosure and SSRF from a document.',\n cwe: 'CWE-611',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\b(?:DocumentBuilderFactory|SAXParserFactory|XMLInputFactory|TransformerFactory|SchemaFactory)\\s*\\.\\s*newInstance\\s*\\(\\s*\\)/,\n guard: XXE_GUARD,\n guardBack: 4,\n guardForward: 8,\n },\n {\n id: 'java-xxe-parse-call',\n title: 'XML parsed by a builder that was never hardened',\n consequence:\n 'The expansion happens at `parse()`. Flagging only the factory misses the line where the document is actually read.',\n cwe: 'CWE-611',\n severity: 'high',\n languages: ['java'],\n // Receiver-qualified so `LocalDate.parse(s)` and friends stay out of it.\n // The suffix alone is not enough — plenty of parsers parse things that are\n // not XML — so `fileRequires` decides whether the file is in scope at all.\n pattern: /\\b\\w*(?:[Bb]uilder|[Pp]arser|[Rr]eader)\\s*\\.\\s*parse\\s*\\(/,\n fileRequires: XML_PARSING_FILE,\n guard: XXE_GUARD,\n guardBack: 6,\n guardForward: 4,\n },\n\n // ── Path traversal ───────────────────────────────────────────────────────\n {\n id: 'py-path-traversal',\n title: 'file opened at a path built from input',\n consequence: 'A `../` sequence — or an absolute path — reads or writes outside the intended directory.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['python'],\n pattern: /\\bopen\\s*\\(\\s*(?:os\\.path\\.join\\s*\\(|[a-zA-Z_]\\w*\\s*\\+|f['\"])/,\n needsContext: true,\n },\n {\n id: 'js-path-traversal',\n title: 'file path built from a variable',\n consequence: 'A `../` sequence in the value reads or writes outside the intended directory.',\n cwe: 'CWE-22',\n severity: 'medium',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\b(?:readFile|readFileSync|writeFile|writeFileSync|createReadStream|createWriteStream|unlink|unlinkSync|sendFile)\\s*\\(\\s*(?:`[^`]*\\$\\{|[a-zA-Z_$][\\w$]*\\s*\\+|path\\.join\\s*\\([^)]*(?:req|request)\\b)/,\n needsContext: true,\n },\n\n // ── Cryptography, tokens, randomness ─────────────────────────────────────\n {\n id: 'js-jwt-decode-without-verify',\n title: 'JWT decoded without verifying the signature',\n consequence:\n '`decode` parses the claims and checks nothing. Anyone can mint a token with any `sub` and any `role`.',\n cwe: 'CWE-347',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bjwt\\s*\\.\\s*decode\\s*\\(|\\bjsonwebtoken\\s*\\.\\s*decode\\s*\\(|\\bdecodeJwt\\s*\\(/,\n },\n {\n id: 'tls-verification-disabled',\n inherent: true,\n title: 'TLS certificate verification disabled',\n consequence:\n 'Every connection made this way is trivially interceptable; the encryption is decorative.',\n cwe: 'CWE-295',\n severity: 'high',\n pattern:\n /rejectUnauthorized\\s*:\\s*false|NODE_TLS_REJECT_UNAUTHORIZED\\s*[=:]\\s*['\"]?0|strictSSL\\s*:\\s*false|\\bverify\\s*=\\s*False\\b|InsecureSkipVerify\\s*:\\s*true/,\n },\n {\n id: 'weak-hash-on-credential',\n title: 'broken hash used on a credential',\n consequence: 'MD5 and SHA-1 are fast and collision-prone; hashed passwords are recoverable.',\n cwe: 'CWE-327',\n severity: 'high',\n pattern:\n /(?:createHash|hashlib|MessageDigest\\.getInstance|Digest::)\\s*[.(]?\\s*['\"]?(?:md5|MD5|sha1|SHA-?1)['\"]?\\s*\\)?[\\s\\S]{0,80}(?:password|passwd|secret|token|credential)/i,\n },\n {\n id: 'insecure-randomness-for-secret',\n title: 'predictable randomness used for a security value',\n consequence:\n '`Math.random`/`random.random` are predictable; tokens, session ids and reset codes built from them are guessable.',\n cwe: 'CWE-338',\n severity: 'high',\n pattern:\n /(?:token|secret|password|salt|nonce|session|otp|reset|apikey|api_key)[\\w]*\\s*[:=][^;\\n]{0,60}(?:Math\\s*\\.\\s*random\\s*\\(|\\brandom\\s*\\.\\s*(?:random|randint|choice)\\s*\\(|\\brand\\s*\\()/i,\n },\n {\n id: 'redos-nested-quantifier',\n title: 'regex with nested unbounded quantifiers',\n consequence:\n 'Catastrophic backtracking: a crafted input of a few dozen characters pins a CPU core for minutes.',\n cwe: 'CWE-1333',\n severity: 'medium',\n pattern: /\\([^)\\n]*[+*]\\s*\\)\\s*[+*]|\\([^)\\n]*\\{\\d+,\\}\\s*\\)\\s*[+*{]/,\n },\n\n // ── Temporary files ──────────────────────────────────────────────────────\n {\n id: 'insecure-temp-file',\n title: 'predictable temporary file path',\n consequence:\n 'A predictable name in a world-writable directory is a symlink attack: an attacker pre-creates the path and your process writes through it.',\n cwe: 'CWE-377',\n severity: 'medium',\n // A hardcoded path under /tmp is the finding whether or not it is\n // formatted: `\"/tmp/application.log.tmp\"` is worse than the PID-based one,\n // because every process on the host can predict it exactly.\n pattern:\n /\\btempfile\\.mktemp\\s*\\(|\\bos\\.tmpnam\\s*\\(|['\"]\\/tmp\\/[^'\"\\n]+['\"]|['\"]\\/tmp\\/[^'\"\\n]*\\{|\\bFile\\.createTempFile\\s*\\(/,\n },\n\n // ── Information exposure ─────────────────────────────────────────────────\n {\n id: 'py-stack-trace-returned',\n title: 'stack trace returned to the caller',\n consequence:\n 'Tracebacks leak absolute paths, dependency versions and source fragments — the reconnaissance an attacker would otherwise have to guess at.',\n cwe: 'CWE-209',\n severity: 'medium',\n languages: ['python'],\n pattern: /\\breturn\\b[^\\n]*\\btraceback\\.(?:format_exc|format_exception|print_exc)\\s*\\(|\\breturn\\b[^\\n]*\\bstr\\s*\\(\\s*e\\s*\\)/,\n },\n {\n id: 'js-environment-exfiltration',\n title: 'process environment serialised into a payload',\n consequence:\n 'The environment is where every secret lives. Serialising it whole into a request body is credential exfiltration regardless of the endpoint.',\n cwe: 'CWE-532',\n severity: 'critical',\n languages: ['javascript', 'typescript'],\n pattern: /\\bJSON\\.stringify\\s*\\(\\s*\\{?[^)]*\\bprocess\\.env\\b(?!\\s*\\.)/,\n guard: false,\n },\n {\n id: 'js-credential-logged',\n title: 'credential read from the environment into a log sink',\n consequence:\n 'CI retains job logs, and on public forks it publishes them. A token printed once is a token leaked permanently.',\n cwe: 'CWE-532',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern: /\\b(?:token|apiKey|api_key|secret|password|credential|auth)\\w*\\s*:\\s*process\\.env\\.\\w+/i,\n requires: EXFIL_SINK,\n guard: false,\n guardBack: 4,\n guardForward: 1,\n },\n\n // ── Prototype pollution ──────────────────────────────────────────────────\n {\n id: 'js-prototype-pollution',\n title: 'write to a prototype-reachable key',\n consequence:\n 'An attacker-supplied `__proto__` key changes behaviour for every object in the process, including ones it never touched.',\n cwe: 'CWE-1321',\n severity: 'high',\n languages: ['javascript', 'typescript'],\n pattern:\n /\\[\\s*['\"]__proto__['\"]\\s*\\]|\\bObject\\s*\\.\\s*assign\\s*\\(\\s*[\\w.$]*\\.prototype\\b|\\.\\s*__proto__\\s*=/,\n },\n\n // ── Shell ────────────────────────────────────────────────────────────────\n //\n // `shell` was a language the type system knew about and no rule targeted, so\n // a repository written entirely in bash got secret detection and nothing\n // else. Installers, CI helpers and packaging scripts are where a great deal\n // of privileged work actually happens, and they run as whoever invoked them.\n {\n id: 'sh-remote-script-execution',\n inherent: true,\n title: 'network output piped into a shell',\n consequence:\n 'Whatever that URL serves at the moment this runs is executed as the invoking user. There is no version, no signature, and no review — a compromise of the host, or anyone able to answer for it, is a compromise of every machine that runs the script.',\n cwe: 'CWE-494',\n severity: 'high',\n languages: ['shell'],\n // The pipe must be the *next* thing: `curl -o f url && sh f` is a different\n // (and checkable) shape, and `curl url | jq` is not an execution at all.\n pattern: /\\b(?:curl|wget)\\b[^|\\n]*\\|\\s*(?:sudo\\s+(?:-\\S+\\s+)*)?(?:\\/bin\\/|\\/usr\\/bin\\/)?(?:ba|da|k|z|a)?sh\\b/,\n // Nothing on this line can exonerate it. Integrity checking happens in a\n // separate step by construction, so a window guard would only mislead.\n guard: false,\n },\n {\n id: 'sh-eval-expansion',\n title: 'eval on an expanded string',\n consequence:\n 'The expansion is re-parsed as shell source, so a `;` or `$(…)` anywhere in the value runs as a command rather than arriving as data.',\n cwe: 'CWE-78',\n severity: 'high',\n languages: ['shell'],\n // Matched against eval's *argument*, not against the rest of the line.\n //\n // `\\beval\\b.*\\$` looks equivalent and is not: bash's ordinary dynamic-range\n // idiom, `eval echo {$((k + 1))..$((k + n))}`, contains `$k` inside the\n // arithmetic, so a line-wide search finds an expansion in a construct that\n // cannot carry a command — `$((…))` is parsed as an expression, where a `;`\n // is a syntax error rather than a second command. That spelling reported\n // 355 findings in one 3,500-line script, all of them the same safe loop.\n //\n // What is left is the form where eval is handed a value directly —\n // `eval \"$cmd\"`, `eval $cmd`, `eval \"$(…)\"` — which is the shape that\n // actually re-parses untrusted text as source. `eval echo $x` is not\n // covered; catching it without also catching the range idiom needs to know\n // which expansions are arithmetic, which is parsing, not matching.\n pattern: /\\beval\\s+(?:-\\S+\\s+)*(?:\"\\s*)?\\$(?:\\{?[A-Za-z_]\\w*|\\((?!\\())/,\n // The shell-init idiom `eval \"$(tool init -)\"` is the documented interface\n // of most version managers. It is still eval of program output, but the\n // program is a fixed local binary, and flagging it reports every developer\n // dotfile in existence.\n lineGuard:\n /\\beval\\s+\"?\\$\\(\\s*(?:ssh-agent|dircolors|direnv|rbenv|pyenv|nodenv|goenv|jenv|tfenv|opam|luarocks|conda|mamba|zoxide|starship|mise|asdf|fnm|nvm|brew|thefuck|register-python-argcomplete|_\\w+_completion)\\b/,\n },\n {\n id: 'sh-unquoted-expansion-destructive',\n title: 'unquoted expansion in a destructive command',\n consequence:\n 'An unquoted expansion is word-split and glob-expanded before the command sees it. A value with a space removes two paths instead of one; an empty value removes the argument entirely, which is how `rm -rf $DIR/` becomes `rm -rf /`.',\n cwe: 'CWE-78',\n severity: 'high',\n languages: ['shell'],\n // `[^\"'\\n]*?` cannot cross a quote, so `rm -rf \"$dir\"` — the correct form —\n // never reaches the `$` and never matches. Only a genuinely bare expansion\n // does. Restricted to recursive/forced removal: a bare `$f` in `rm $f` is\n // sloppy, but it is not the shape that erases a filesystem.\n pattern: /\\brm\\s+(?:-[a-zA-Z-]*[rRf][a-zA-Z-]*\\s+)+[^\"'\\n]*?\\$\\{?[A-Za-z_]/,\n },\n {\n id: 'sh-insecure-transport-flag',\n inherent: true,\n title: 'certificate verification disabled',\n consequence:\n 'Anyone positioned between this host and the server can substitute the response. When the response is a package, a key or a script, that is remote code execution with the transport doing nothing to stop it.',\n cwe: 'CWE-295',\n severity: 'high',\n languages: ['shell'],\n pattern:\n /\\b(?:curl|wget)\\b[^\\n|]*(?:\\s-k(?=\\s|$)|\\s--insecure\\b|\\s--no-check-certificate\\b)/,\n // Over plain HTTP there is no certificate to skip, so the flag is inert and\n // this rule has nothing to say — `sh-plaintext-download` is the finding\n // that fits. Reporting both put two entries on one line, one of which\n // recommended a fix that would change nothing.\n lineGuard: /^(?!.*https:\\/\\/).*\\bhttp:\\/\\//,\n },\n {\n id: 'sh-plaintext-download',\n inherent: true,\n title: 'download over plain HTTP',\n consequence:\n 'The response arrives unauthenticated over a channel any intermediary can rewrite. Where the payload is an archive, a package list or a key, substituting it is straightforward and leaves nothing for the script to notice.',\n cwe: 'CWE-319',\n severity: 'high',\n languages: ['shell'],\n pattern: /\\b(?:curl|wget)\\b[^\\n|]*\\bhttp:\\/\\//,\n // Loopback and link-local are not carried over a network anyone can sit on.\n lineGuard:\n /http:\\/\\/(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[::1\\]|169\\.254\\.|host\\.docker\\.internal)\\b/,\n },\n {\n id: 'sh-world-writable-permissions',\n inherent: true,\n title: 'world-writable permissions',\n consequence:\n 'Any local account can rewrite the file. If it is a script, a config or anything on a privileged path, the next process to read it runs someone else’s content.',\n cwe: 'CWE-732',\n severity: 'medium',\n languages: ['shell'],\n pattern: /\\bchmod\\s+(?:-[a-zA-Z-]+\\s+)*(?:0?777|a\\+rwx|ugo\\+rwx|a=rwx)\\b/,\n },\n {\n id: 'sh-predictable-temp-path',\n title: 'predictable temporary file',\n consequence:\n 'The name is guessable, so a local attacker can create it first — as a symlink to somewhere that matters — and the script writes through it with its own privileges.',\n cwe: 'CWE-377',\n severity: 'medium',\n languages: ['shell'],\n // Redirection or an explicit write into a literal `/tmp` path. A `$$` or\n // `$RANDOM` suffix is still predictable, so it is not treated as a fix;\n // `mktemp` is, and it is the guard below.\n pattern: /(?:>{1,2}\\s*|\\b(?:tee|touch|cp|mv|install)\\s+(?:-\\S+\\s+)*)\\/tmp\\/[\\w.$-]+/,\n guard: /\\bmktemp\\b/,\n guardBack: 6,\n guardForward: 2,\n },\n\n // ── PHP ──────────────────────────────────────────────────────────────────\n //\n // `php` was the second language in `ScanLanguage` that no rule targeted, for\n // the same reason `shell` was: nothing checks the two lists against each\n // other. `LANGUAGE_COVERAGE` in the tests does now.\n {\n id: 'php-sql-interpolation',\n title: 'SQL assembled by interpolation',\n consequence:\n 'PHP interpolates variables inside double-quoted strings, so the value is part of the statement before the driver ever sees it. A quote in the value ends the literal and the rest is parsed as SQL.',\n cwe: 'CWE-89',\n severity: 'critical',\n languages: ['php'],\n // Interpolation (`\"… $id …\"`, `\"… {$id} …\"`) or concatenation onto a SQL\n // string. A prepared statement passes placeholders and binds separately,\n // so its query string contains neither.\n pattern: new RegExp(\n `\\\\b(?:mysqli_query|mysql_query|pg_query|->\\\\s*(?:query|exec|unprepared))\\\\s*\\\\([^)]*(?:\"[^\"\\\\n]*(?:${SQL_KEYWORDS})\\\\b[^\"\\\\n]*(?:\\\\$\\\\w+|\\\\{\\\\$)|${SQL_STRING}\\\\s*\\\\.)`,\n 'i',\n ),\n },\n {\n id: 'php-shell-exec-interpolation',\n title: 'shell command built from a variable',\n consequence:\n 'The string is handed to `/bin/sh`, which interprets `;`, `|` and `$(…)` in whatever the variable held.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['php'],\n pattern:\n /\\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec)\\s*\\(\\s*(?:\"[^\"\\n]*(?:\\$\\w+|\\{\\$)|'[^'\\n]*'\\s*\\.|\\$\\w+\\s*\\.)/,\n // `escapeshellarg`/`escapeshellcmd` are the correct answer and are usually\n // applied inline, so a line-scoped guard is the right shape.\n lineGuard: /\\bescapeshell(?:arg|cmd)\\s*\\(/,\n },\n {\n id: 'php-dynamic-code-execution',\n title: 'dynamic code execution',\n consequence:\n 'Whatever reaches this call is executed as PHP source with the privileges of the web process.',\n cwe: 'CWE-95',\n severity: 'critical',\n languages: ['php'],\n pattern: /\\b(?:eval|assert|create_function)\\s*\\(\\s*(?:\\$\\w+|\"[^\"\\n]*(?:\\$\\w+|\\{\\$))/,\n guard: false,\n },\n {\n id: 'php-dynamic-file-inclusion',\n title: 'include path built from a variable',\n consequence:\n 'The included file is executed, not read. A traversal sequence reaches any file the process can open, and with a remote wrapper enabled the path need not be local at all.',\n cwe: 'CWE-98',\n severity: 'critical',\n languages: ['php'],\n pattern:\n /\\b(?:include|include_once|require|require_once)\\s*(?:\\(\\s*)?(?:\\$\\w+|\"[^\"\\n]*(?:\\$\\w+|\\{\\$)|'[^'\\n]*'\\s*\\.)/,\n // A basename-and-allow-list is the standard fix; `basename` alone still\n // leaves the extension open, but it defeats traversal, which is the part\n // this rule is about.\n lineGuard: /\\bbasename\\s*\\(/,\n },\n {\n id: 'php-unserialize-untrusted',\n title: 'unserialize on request data',\n consequence:\n 'PHP object deserialisation instantiates classes and runs their magic methods. With a suitable class in scope this is remote code execution, and no `unserialize` option short of `allowed_classes => false` prevents it.',\n cwe: 'CWE-502',\n severity: 'critical',\n languages: ['php'],\n pattern: /\\bunserialize\\s*\\(\\s*(?:\\$_(?:GET|POST|REQUEST|COOKIE)\\b|\\$\\w+)/,\n // The key is an array key and is normally quoted: `['allowed_classes' => false]`.\n lineGuard: /[\"']?allowed_classes[\"']?\\s*=>\\s*(?:false|\\[)/,\n needsContext: true,\n },\n {\n id: 'php-unescaped-output',\n title: 'request data echoed without escaping',\n consequence:\n 'The value is written into the response verbatim, so markup in it becomes markup in the page — script that runs with the victim’s session.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['php'],\n pattern:\n /\\b(?:echo|print)\\s+[^;\\n]*\\$_(?:GET|POST|REQUEST|COOKIE|SERVER)\\b|<\\?=\\s*\\$_(?:GET|POST|REQUEST|COOKIE)\\b/,\n },\n {\n id: 'php-request-path-traversal',\n title: 'file path taken from the request',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory, and the process reads or writes wherever it lands.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['php'],\n pattern:\n /\\b(?:file_get_contents|file_put_contents|fopen|readfile|unlink|copy|rename|opendir|scandir)\\s*\\(\\s*[^)\\n]*\\$_(?:GET|POST|REQUEST|COOKIE)\\b/,\n lineGuard: /\\bbasename\\s*\\(|\\brealpath\\s*\\(/,\n },\n {\n id: 'php-variable-injection',\n title: 'request data expanded into local variables',\n consequence:\n '`extract` creates a variable per key, so a request can overwrite any local already in scope — including the one a subsequent authorisation check reads.',\n cwe: 'CWE-621',\n severity: 'high',\n languages: ['php'],\n pattern: /\\bextract\\s*\\(\\s*\\$_(?:GET|POST|REQUEST|COOKIE)\\b|\\bimport_request_variables\\s*\\(/,\n guard: false,\n },\n\n // ── Java and Go: classes the other languages already had ─────────────────\n //\n // Command injection, SSRF and path traversal were implemented for JavaScript\n // and, in part, for Go, and never for Java — so the same defect in the same\n // codebase was reported or not depending on which file it lived in. TLS\n // verification, weak hashing and insecure randomness are deliberately absent\n // here: `tls-verification-disabled`, `weak-hash-on-credential` and\n // `insecure-randomness-for-secret` are language-agnostic and already cover\n // both, including Go's `InsecureSkipVerify` and Java's `MessageDigest`.\n {\n id: 'java-runtime-exec-concatenation',\n title: 'Runtime.exec with a concatenated command',\n consequence:\n 'The single-string form of `exec` is split on whitespace and handed to the OS. A value carrying a space becomes extra arguments, and where a shell is invoked, `;` and `$(…)` become extra commands.',\n cwe: 'CWE-78',\n severity: 'critical',\n languages: ['java'],\n // The array form — `exec(new String[]{\"git\", arg})` — passes argv and is\n // the fix, so it is not matched: the `+` has to be inside the string\n // argument for this to fire.\n pattern:\n /\\b(?:Runtime\\s*\\.\\s*getRuntime\\s*\\(\\s*\\)\\s*\\.\\s*exec|ProcessBuilder)\\s*\\(\\s*(?:\"[^\"\\n]*\"\\s*\\+|\\w+\\s*\\+\\s*\")/,\n },\n {\n id: 'java-ssrf-outbound-request',\n title: 'outbound request to a computed URL',\n consequence:\n 'The destination is chosen by the caller, so the request can be aimed at internal services and cloud metadata endpoints that are reachable from this host and from nowhere else.',\n cwe: 'CWE-918',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\bnew\\s+URL\\s*\\(\\s*(?!\\s*\"[a-z]+:\\/\\/[^\"\\n]*\"\\s*\\))[^)\\n]*\\w|\\bHttpRequest\\s*\\.\\s*newBuilder\\s*\\(\\s*\\)\\s*\\.\\s*uri\\s*\\(\\s*URI\\s*\\.\\s*create\\s*\\(\\s*[^\"\\n)]/,\n needsContext: true,\n },\n {\n id: 'java-request-path-traversal',\n title: 'file path built from request data',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory. The process then reads or writes wherever it lands, with its own privileges.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['java'],\n pattern:\n /\\b(?:new\\s+File|new\\s+FileInputStream|new\\s+FileOutputStream|Paths\\s*\\.\\s*get|Files\\s*\\.\\s*(?:readAllBytes|newInputStream|newOutputStream|copy|delete))\\s*\\([^)\\n]*\\+/,\n // `getCanonicalPath().startsWith(base)` is the check that makes this safe,\n // and it is normally a line or two below the construction.\n guard: /getCanonicalPath|toRealPath|normalize\\s*\\(\\s*\\)|\\bstartsWith\\s*\\(/,\n guardForward: 4,\n needsContext: true,\n },\n {\n id: 'java-broken-cipher',\n inherent: true,\n title: 'broken cipher or ECB mode',\n consequence:\n 'DES, RC2, RC4 and Blowfish are broken or too small to rely on. ECB encrypts identical plaintext blocks to identical ciphertext blocks, so structure in the data survives encryption and is readable straight off the ciphertext.',\n cwe: 'CWE-327',\n severity: 'high',\n languages: ['java'],\n // Bare `\"AES\"` is included: the JCE resolves it to `AES/ECB/PKCS5Padding`,\n // so the default is the mode this rule exists to catch.\n pattern:\n /\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"(?:DES|DESede|RC2|RC4|ARCFOUR|Blowfish)(?:\\/|\")|\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"[^\"\\n]*\\/ECB\\/|\\bCipher\\s*\\.\\s*getInstance\\s*\\(\\s*\"AES\"\\s*\\)/,\n guard: false,\n },\n {\n id: 'go-request-path-traversal',\n title: 'file path built from request data',\n consequence:\n 'A `../` sequence in the value walks out of the intended directory, and the handler serves or writes whatever it reaches.',\n cwe: 'CWE-22',\n severity: 'high',\n languages: ['go'],\n pattern:\n /\\b(?:os\\s*\\.\\s*(?:Open|OpenFile|ReadFile|Create|Remove|WriteFile)|ioutil\\s*\\.\\s*(?:ReadFile|WriteFile)|http\\s*\\.\\s*ServeFile)\\s*\\([^)\\n]*(?:r\\s*\\.\\s*URL|FormValue|Query\\s*\\(\\s*\\)\\s*\\.\\s*Get|mux\\s*\\.\\s*Vars|\\bfilepath\\s*\\.\\s*Join\\s*\\([^)\\n]*\\w)/,\n // `filepath.Clean` alone does not bound the result to a directory, so it is\n // not a guard here — the containment check is.\n guard: /\\bstrings\\s*\\.\\s*HasPrefix\\s*\\(|\\bfilepath\\s*\\.\\s*Rel\\s*\\(|\\bfs\\s*\\.\\s*ValidPath\\s*\\(|\\bhttp\\s*\\.\\s*Dir\\b/,\n guardBack: 5,\n guardForward: 3,\n needsContext: true,\n },\n {\n id: 'go-template-escaping-bypass',\n title: 'value marked as pre-escaped HTML',\n consequence:\n '`template.HTML` tells `html/template` the value is already safe, which switches off the contextual escaping that makes the package worth using. Markup in the value reaches the page intact.',\n cwe: 'CWE-79',\n severity: 'high',\n languages: ['go'],\n // A conversion of a *variable*. `template.HTML(\"<br>\")` on a literal is a\n // constant the author wrote and is not a finding.\n pattern: /\\btemplate\\s*\\.\\s*(?:HTML|JS|CSS|HTMLAttr|URL|Srcset)\\s*\\(\\s*(?!\\s*[`\"])/,\n needsContext: true,\n },\n];\n\n/**\n * Classes deliberately not implemented, and why.\n *\n * Recorded in code rather than in a document because the reason is a design\n * constraint, not a backlog item: each of these needs reasoning this scanner\n * does not do, and the line-oriented approximation of each one flags ordinary\n * software. A missing detection is a known number. A rule that fires on every\n * session read is a scanner nobody runs twice.\n */\nexport const KNOWN_GAPS: readonly { cwe: string; name: string; why: string }[] = [\n {\n cwe: 'CWE-352',\n name: 'Missing CSRF token',\n why: 'Requires knowing that a handler is state-changing and that no token check dominates the mutation. Line-locally, the vulnerable and the guarded handler are the same code.',\n },\n {\n cwe: 'CWE-362',\n name: 'Check-then-use race (TOCTOU)',\n why: 'Requires pairing a check with a later use of the same path across statements. A rule matching either half alone flags every `os.path.exists`.',\n },\n {\n cwe: 'CWE-190',\n name: 'Integer overflow / unchecked narrowing',\n why: 'Requires range reasoning about the operands. Flagging arithmetic on a request value would flag arithmetic.',\n },\n {\n cwe: 'CWE-1321',\n name: 'Prototype pollution via generic dynamic assignment',\n why: '`target[key] = source[key]` is both the vulnerable merge and the guarded one; only a denylist several lines away distinguishes them. The explicit `__proto__` shapes are covered.',\n },\n];\n\nexport interface MatchContext {\n /** All lines of the file, 0-indexed. */\n lines: readonly string[];\n /** 0-indexed position of the line being tested. */\n index: number;\n language: ScanLanguage;\n /**\n * Indexes inside a multi-line string or block comment, from `proseLines`.\n * Treated exactly like comment lines: not scanned, not guard evidence.\n */\n prose?: ReadonlySet<number>;\n}\n\nconst COMMENT_PREFIX = /^\\s*(?:\\/\\/|\\/\\*|\\*|#|--|<!--)/;\n\n/**\n * A line that introduces a name rather than doing something with it.\n *\n * Excluded from guard windows because a *name* is not evidence. The corpus\n * contains `def sanitize_path_vulnerable(path):` directly above three\n * catastrophic-backtracking regexes: reading that signature as proof of\n * sanitisation suppressed all three. Naming a function `sanitize` does not\n * sanitise anything, and neither does calling one `validate` or `escape`.\n */\nconst DEFINITION_PREFIX =\n /^\\s*(?:(?:export|public|private|protected|static|final|async|abstract)\\s+)*(?:def|function|func|class|module|interface|struct|impl|fn|sub)\\b/;\n\n/**\n * Comment lines are documentation, not code.\n *\n * Excluded from guard windows for a reason found the hard way: the testbed's\n * vulnerable cases carry comments like \"No `__proto__` guard\" and \"without\n * allow-list validation\". Reading those as evidence of a guard suppresses\n * exactly the findings the corpus exists to measure.\n */\nexport function isComment(line: string): boolean {\n return COMMENT_PREFIX.test(line);\n}\n\n/**\n * Line indexes belonging to multi-line strings and block comments.\n *\n * Python module docstrings are the case that forced this. Every file in the\n * testbed opens with a `\"\"\"…\"\"\"` header describing the vulnerability it\n * contains — `pickle.loads`, `(a+)+`, `autoescape=False` — and scanning that\n * prose produces findings *about the documentation*, reported at line 9 of a\n * file whose code starts at line 18. They are unattributable by construction,\n * and they are the scanner reading its own description back to itself.\n */\nexport function proseLines(lines: readonly string[]): Set<number> {\n const inside = new Set<number>();\n let delimiter: string | null = null;\n\n lines.forEach((line, index) => {\n if (delimiter) {\n inside.add(index);\n if (line.includes(delimiter)) delimiter = null;\n return;\n }\n for (const candidate of ['\"\"\"', \"'''\"]) {\n const start = line.indexOf(candidate);\n if (start === -1) continue;\n // A docstring opened and closed on one line encloses nothing.\n if (line.indexOf(candidate, start + candidate.length) !== -1) return;\n delimiter = candidate;\n inside.add(index);\n return;\n }\n });\n\n return inside;\n}\n\nfunction skippable(line: string, index: number, prose?: ReadonlySet<number>): boolean {\n return isComment(line) || DEFINITION_PREFIX.test(line) || (prose?.has(index) ?? false);\n}\n\nfunction windowText(\n lines: readonly string[],\n index: number,\n back: number,\n forward: number,\n prose?: ReadonlySet<number>,\n): string {\n const from = Math.max(0, index - back);\n const to = Math.min(lines.length - 1, index + forward);\n const collected: string[] = [];\n for (let i = from; i <= to; i += 1) {\n const line = lines[i] ?? '';\n if (i !== index && skippable(line, i, prose)) continue;\n collected.push(line);\n }\n return collected.join('\\n');\n}\n\n/**\n * Whole-file text, memoised on the `lines` array it came from.\n *\n * `fileRequires` asks a question no window can answer, but joining the file on\n * every line of every rule would make scanning quadratic in file length. The\n * caller already reuses one `lines` array for the whole file, so keying on its\n * identity gives one join per file. A `WeakMap` keeps nothing alive after the\n * file is done with.\n */\nconst FILE_TEXT = new WeakMap<readonly string[], string>();\n\nfunction fileTextOf(lines: readonly string[]): string {\n let text = FILE_TEXT.get(lines);\n if (text === undefined) {\n text = lines.join('\\n');\n FILE_TEXT.set(lines, text);\n }\n return text;\n}\n\nexport interface RuleMatch {\n rule: CodeRule;\n confidence: Confidence;\n severity: Severity;\n}\n\n/**\n * Test one rule against one line.\n *\n * Returns `null` when the rule does not apply, does not match, is guarded, or\n * needs context it cannot see.\n */\n/**\n * Blank out single-quoted spans before looking for untrusted input.\n *\n * The shell performs no expansion inside single quotes, so a `$1` there is the\n * two characters `$1` and never a positional parameter. Without this, an awk\n * or sed program written inline — `gawk -F '=' '{print $2}'` — reads as\n * attacker-controlled input.\n *\n * That was not theoretical. In `ralyodio/debtap` it escalated one `curl -k`\n * line to `contextual`, and the ±6-line window carried the escalation to four\n * neighbouring findings, so the same defect reported `high` on lines 103–111\n * and `medium` on 113, 120 and 128 — decided entirely by distance from an awk\n * one-liner. A `--fail-on high` gate would have caught five of eight identical\n * problems.\n */\nfunction withoutSingleQuoted(text: string): string {\n return text.replace(/'[^'\\n]*'/g, \"''\");\n}\n\nexport function evaluateRule(rule: CodeRule, ctx: MatchContext): RuleMatch | null {\n if (rule.languages && !rule.languages.includes(ctx.language)) return null;\n\n const line = ctx.lines[ctx.index] ?? '';\n if (isComment(line) || ctx.prose?.has(ctx.index)) return null;\n if (!rule.pattern.test(line)) return null;\n\n // Before any window work: a rule whose file-level precondition fails does not\n // apply to this file at all.\n if (rule.fileRequires && !rule.fileRequires.test(fileTextOf(ctx.lines))) return null;\n\n const back = rule.guardBack ?? 8;\n const forward = rule.guardForward ?? 0;\n const context = windowText(ctx.lines, ctx.index, back, forward, ctx.prose);\n\n if (rule.requires && !rule.requires.test(context)) return null;\n\n if (rule.lineGuard?.test(line)) return null;\n\n const guard = rule.guard === undefined ? GENERIC_GUARD : rule.guard;\n if (guard && (guard.test(line) || guard.test(context))) return null;\n\n const untrusted = untrustedPatternFor(ctx.language);\n const probeLine = ctx.language === 'shell' ? withoutSingleQuoted(line) : line;\n const probeContext = ctx.language === 'shell' ? withoutSingleQuoted(context) : context;\n const contextual = untrusted.test(probeLine) || untrusted.test(probeContext);\n if (rule.needsContext && !contextual) return null;\n\n // `inherent` short-circuits the whole context question. See the field's\n // documentation: for these rules the construct is the defect, so nearby\n // input cannot make it worse and its absence cannot make it better.\n const confidence: Confidence = rule.inherent\n ? 'evidence'\n : contextual\n ? 'contextual'\n : 'pattern';\n return { rule, confidence, severity: severityFor(rule.severity, confidence) };\n}\n","/**\n * Dependency-manifest rules — typosquats, dependency confusion, and\n * install-time lifecycle scripts.\n *\n * This is the one detector here that does not need a vulnerability to exist\n * yet. `event-stream` (2018), `ua-parser-js` (2021) and `node-ipc` (2022) were\n * all advisory-clean at the moment they were installed; the advisory gets\n * written *after* somebody notices. What they shared was a name you would\n * misread and a lifecycle script that ran with the installing user's\n * privileges. Both are visible in the manifest, before anything is fetched.\n */\n\nimport type { Severity } from './types';\n\nexport interface ManifestFinding {\n ruleId: string;\n title: string;\n line: number;\n severity: Severity;\n cwe: string;\n message: string;\n consequence: string;\n excerpt: string;\n}\n\n/**\n * Popular package names, by ecosystem.\n *\n * Not a registry mirror and not trying to be. It is the set of names worth\n * *impersonating* — a typosquat only pays off against a package people install\n * without looking. A longer list would not find more attacks; it would find\n * more legitimate packages that happen to sit one edit from something famous.\n */\nconst POPULAR_NPM = [\n 'react', 'react-dom', 'lodash', 'express', 'axios', 'chalk', 'commander', 'debug',\n 'moment', 'dayjs', 'uuid', 'dotenv', 'typescript', 'webpack', 'vite', 'rollup',\n 'eslint', 'prettier', 'jest', 'vitest', 'mocha', 'chai', 'sinon', 'request',\n 'node-fetch', 'cross-env', 'rimraf', 'glob', 'minimist', 'yargs', 'inquirer',\n 'colors', 'ora', 'semver', 'ws', 'socket.io', 'mongoose', 'sequelize', 'knex',\n 'pg', 'mysql', 'mysql2', 'redis', 'ioredis', 'jsonwebtoken', 'bcrypt', 'passport',\n 'cors', 'helmet', 'morgan', 'body-parser', 'multer', 'nodemailer', 'puppeteer',\n 'playwright', 'cheerio', 'sharp', 'canvas', 'esbuild', 'babel', 'postcss',\n 'tailwindcss', 'next', 'nuxt', 'vue', 'svelte', 'angular', 'rxjs', 'zod',\n];\n\nconst POPULAR_PYPI = [\n 'requests', 'urllib3', 'numpy', 'pandas', 'scipy', 'flask', 'django', 'fastapi',\n 'sqlalchemy', 'pydantic', 'click', 'jinja2', 'pyyaml', 'boto3', 'botocore',\n 'setuptools', 'wheel', 'pip', 'six', 'certifi', 'idna', 'chardet', 'attrs',\n 'python-dateutil', 'pytz', 'pytest', 'tox', 'black', 'flake8', 'mypy', 'isort',\n 'beautifulsoup4', 'lxml', 'pillow', 'matplotlib', 'seaborn', 'scikit-learn',\n 'tensorflow', 'torch', 'transformers', 'openai', 'anthropic', 'httpx', 'aiohttp',\n 'celery', 'redis', 'psycopg2', 'pymongo', 'cryptography', 'paramiko', 'colorama',\n];\n\n/**\n * Names that read as belonging to a private registry.\n *\n * A manifest that asks a public index for a package whose name announces it is\n * internal is the dependency-confusion setup: whoever registers the name\n * publicly first wins, and the build takes their copy.\n */\nconst INTERNAL_MARKER = /(?:^|[-_/@])(?:internal|private|corp|intranet|inhouse|confidential)(?:$|[-_/])/i;\n\n/** Strip the separators a squatter varies but a reader does not notice. */\nfunction normalizeName(name: string): string {\n return name.toLowerCase().replace(/^@/, '').replace(/[-_.\\s]/g, '');\n}\n\n/**\n * Damerau-Levenshtein distance, capped.\n *\n * Damerau rather than plain Levenshtein because the single most common\n * typosquat is a transposition — `lodahs` for `lodash`, `reqeust` for\n * `request`. Levenshtein scores those as 2, the same as two unrelated edits,\n * which puts them below any threshold tight enough to be useful.\n */\nexport function editDistance(a: string, b: string, cap = 3): number {\n if (a === b) return 0;\n if (Math.abs(a.length - b.length) > cap) return cap + 1;\n\n const rows: number[][] = [];\n for (let i = 0; i <= a.length; i += 1) {\n rows.push(new Array<number>(b.length + 1).fill(0));\n rows[i]![0] = i;\n }\n for (let j = 0; j <= b.length; j += 1) rows[0]![j] = j;\n\n for (let i = 1; i <= a.length; i += 1) {\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let best = Math.min(\n rows[i - 1]![j]! + 1,\n rows[i]![j - 1]! + 1,\n rows[i - 1]![j - 1]! + cost,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, rows[i - 2]![j - 2]! + 1);\n }\n rows[i]![j] = best;\n }\n }\n return rows[a.length]![b.length]!;\n}\n\nexport interface SquatVerdict {\n impersonates: string;\n /** `separator` when only punctuation differs, `edit` when a character does. */\n kind: 'separator' | 'edit';\n}\n\n/**\n * Whether `name` looks like an attempt to be mistaken for a popular package.\n *\n * Exact matches return null first, always. The check that follows is\n * deliberately asymmetric: a name is suspicious for being *close to* a popular\n * package, never for being popular itself.\n */\nexport function detectTyposquat(name: string, ecosystem: 'npm' | 'pypi'): SquatVerdict | null {\n const popular = ecosystem === 'npm' ? POPULAR_NPM : POPULAR_PYPI;\n const lower = name.toLowerCase();\n\n // A scoped name is left alone, scope and all.\n //\n // Discarding the scope before comparing was this rule's largest source of\n // false positives, and it fired on some of the most widely installed packages\n // there are: `@babel/core`, `@angular/core`, `@nestjs/core` and\n // `@capacitor/core` all reduce to `core`, which sits one edit from `cors`.\n //\n // Scopes are owned. Publishing `@babel/anything` requires control of the\n // `@babel` scope, so a squat cannot be planted inside a legitimate one, and\n // nobody typing `npm i cors` arrives at `@capacitor/core` by accident. The\n // misreading this rule exists to catch does not cross the scope boundary, so\n // a name that has one is not a candidate.\n //\n // The scoped attack that *is* real is a lookalike scope — `@babeljs/core` for\n // `@babel/core`. Catching it means comparing scopes against a list of popular\n // scopes, which is a different check than this one rather than a variation on\n // it. Stripping the scope never performed that check; it only compared the\n // part after the slash, so nothing is lost here.\n if (/^@[^/]+\\//.test(lower)) return null;\n\n if (popular.includes(lower)) return null;\n if (lower.length < 4) return null;\n\n const normalized = normalizeName(lower);\n for (const candidate of popular) {\n const candidateNormalized = normalizeName(candidate);\n // `urllib-3` and `pythondateutil` normalise onto their targets exactly.\n // Nothing legitimate reaches a popular package's spelling by deleting or\n // inserting punctuation.\n if (normalized === candidateNormalized) return { impersonates: candidate, kind: 'separator' };\n if (editDistance(normalized, candidateNormalized, 1) === 1) {\n return { impersonates: candidate, kind: 'edit' };\n }\n }\n return null;\n}\n\nconst LIFECYCLE_SCRIPTS = ['preinstall', 'install', 'postinstall', 'prepare', 'prepublish'];\n\n/**\n * Scan a `package.json`.\n *\n * Text-oriented rather than object-oriented so every finding can carry the\n * line it came from. A finding an operator cannot navigate to is a finding\n * they will not act on.\n */\nexport function scanPackageJson(text: string): ManifestFinding[] {\n const findings: ManifestFinding[] = [];\n const lines = text.split('\\n');\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return findings;\n }\n\n const lineOf = (needle: string): number => {\n const index = lines.findIndex((line) => line.includes(`\"${needle}\"`));\n return index === -1 ? 1 : index + 1;\n };\n\n const depBuckets = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];\n for (const bucket of depBuckets) {\n const deps = parsed[bucket];\n if (!deps || typeof deps !== 'object') continue;\n for (const name of Object.keys(deps as Record<string, unknown>)) {\n const line = lineOf(name);\n\n if (INTERNAL_MARKER.test(name)) {\n findings.push({\n ruleId: 'manifest-dependency-confusion',\n title: 'internal-looking package resolved from a public registry',\n line,\n severity: 'critical',\n cwe: 'CWE-1357',\n message: `\"${name}\" names itself as internal but carries no registry pin`,\n consequence:\n 'Whoever registers this name publicly first wins the resolution, and their code runs in your build.',\n excerpt: (lines[line - 1] ?? '').trim(),\n });\n continue;\n }\n\n const squat = detectTyposquat(name, 'npm');\n if (squat) {\n findings.push({\n ruleId: 'manifest-typosquat',\n title: 'dependency name close to a popular package',\n line,\n severity: 'high',\n cwe: 'CWE-1357',\n message:\n squat.kind === 'separator'\n ? `\"${name}\" differs from \"${squat.impersonates}\" only in punctuation`\n : `\"${name}\" is one edit from \"${squat.impersonates}\"`,\n consequence:\n 'A reviewer scanning a diff reads the name they expected. The package that installs is the one that was written.',\n excerpt: (lines[line - 1] ?? '').trim(),\n });\n }\n }\n }\n\n const scripts = parsed.scripts;\n if (scripts && typeof scripts === 'object') {\n for (const [name, body] of Object.entries(scripts as Record<string, unknown>)) {\n if (!LIFECYCLE_SCRIPTS.includes(name)) continue;\n findings.push({\n ruleId: 'manifest-install-lifecycle-script',\n title: 'install-time lifecycle script',\n line: lineOf(name),\n severity: 'medium',\n cwe: 'CWE-506',\n message: `\"${name}\" runs automatically on install: ${String(body).slice(0, 120)}`,\n consequence:\n 'Lifecycle scripts run with the installing user’s privileges and network access, before any code is reviewed. It is the execution vector every notable npm compromise has used.',\n excerpt: (lines[lineOf(name) - 1] ?? '').trim(),\n });\n }\n }\n\n return findings;\n}\n\n/** Scan a `requirements.txt`. Same checks, different grammar. */\nexport function scanRequirementsTxt(text: string): ManifestFinding[] {\n const findings: ManifestFinding[] = [];\n const lines = text.split('\\n');\n\n lines.forEach((raw, index) => {\n const line = raw.trim();\n if (!line || line.startsWith('#') || line.startsWith('-')) return;\n\n const match = /^([A-Za-z0-9_.-]+)\\s*(?:[=<>!~]=|@|$)/.exec(line);\n const name = match?.[1];\n if (!name) return;\n\n if (INTERNAL_MARKER.test(name)) {\n findings.push({\n ruleId: 'manifest-dependency-confusion',\n title: 'internal-looking package resolved from a public index',\n line: index + 1,\n severity: 'critical',\n cwe: 'CWE-1357',\n message: `\"${name}\" names itself as internal but carries no index pin`,\n consequence:\n 'pip resolves the highest version across every configured index, so a public package of the same name shadows the private one.',\n excerpt: line,\n });\n return;\n }\n\n const squat = detectTyposquat(name, 'pypi');\n if (squat) {\n findings.push({\n ruleId: 'manifest-typosquat',\n title: 'dependency name close to a popular package',\n line: index + 1,\n severity: 'high',\n cwe: 'CWE-1357',\n message:\n squat.kind === 'separator'\n ? `\"${name}\" differs from \"${squat.impersonates}\" only in punctuation`\n : `\"${name}\" is one edit from \"${squat.impersonates}\"`,\n consequence:\n 'A reviewer scanning a diff reads the name they expected. The package that installs is the one that was written.',\n excerpt: line,\n });\n }\n });\n\n return findings;\n}\n","/**\n * Credential-shape rules for `threatcrush scan`.\n *\n * These are the rules ThreatCrush already scored 0.0% false positives on\n * against the public testbed's control group, so the bar for changing one is\n * high: a secret rule earns its place by matching material that is a\n * credential, not by matching material that looks vaguely random.\n *\n * The distinction that keeps the false-positive rate at zero is *shape with a\n * vendor prefix*. `AKIA…`, `ghp_…`, `xoxb-…`, `sk_live_…` are issued formats —\n * nothing else produces them. Entropy alone is not a rule here, because\n * entropy alone flags every UUID, hash and minified bundle in the tree.\n *\n * Two lines in the testbed corpus are the reason for that discipline. Both\n * live in the same `.env` file as five real credentials:\n *\n * AWS_ROLE_ARN=arn:aws:iam::123456789012:role/app-runtime\n * DATABASE_URL_SSM_PARAMETER=/prod/app/database-url\n *\n * An identifier and a lookup path. Both sit under secret-shaped variable\n * names, and neither is a credential. A rule keyed on the variable name would\n * flag both.\n */\n\nimport type { Severity } from './types';\n\nexport interface SecretRule {\n id: string;\n /** Vendor-facing name, e.g. \"AWS Access Key\". */\n name: string;\n pattern: RegExp;\n severity: Severity;\n cwe: string;\n /** What an attacker does with it. */\n consequence: string;\n}\n\nexport const SECRET_RULES: readonly SecretRule[] = [\n {\n id: 'secret-aws-access-key',\n name: 'AWS Access Key',\n pattern: /\\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Paired with a secret key, grants the API access of whatever IAM principal issued it.',\n },\n {\n id: 'secret-aws-secret-key',\n name: 'AWS Secret Access Key',\n pattern:\n /(?:aws_secret_access_key|AWS_SECRET(?:_ACCESS_KEY)?)\\s*[=:]\\s*['\"]?([A-Za-z0-9/+=]{40})['\"]?/i,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'The other half of an AWS credential pair; on its own it is still the hard half to guess.',\n },\n {\n id: 'secret-github-token',\n name: 'GitHub Token',\n pattern: /\\b(?:ghp_[A-Za-z0-9]{36}|gho_[A-Za-z0-9]{36}|ghu_[A-Za-z0-9]{36}|ghs_[A-Za-z0-9]{36}|ghr_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,})\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Repository read or write as the issuing account, including the ability to push workflow changes.',\n },\n {\n id: 'secret-npm-token',\n name: 'npm Token',\n pattern: /\\bnpm_[A-Za-z0-9]{36}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Publish rights to every package the account owns — a supply-chain compromise in one command.',\n },\n {\n id: 'secret-private-key',\n name: 'Private Key',\n pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Key material, committed. Rotation is the only remediation.',\n },\n {\n id: 'secret-slack-token',\n name: 'Slack Token',\n pattern: /\\bxox[bpoasr]-[A-Za-z0-9-]{10,}/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Read and post access to the workspace as the installing app.',\n },\n {\n id: 'secret-slack-webhook',\n name: 'Slack Webhook URL',\n pattern: /https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9_+\\/-]{6,}/,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'The URL *is* the credential — anyone holding it can post to that channel.',\n },\n {\n id: 'secret-stripe-key',\n name: 'Stripe Key',\n pattern: /\\b(?:sk_live_|rk_live_|sk_test_|rk_test_)[A-Za-z0-9]{20,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Charge, refund and customer-data access against the account.',\n },\n {\n id: 'secret-sendgrid-key',\n name: 'SendGrid API Key',\n pattern: /\\bSG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Send mail as the domain — the credential behind most convincing phishing from a real sender.',\n },\n {\n id: 'secret-google-api-key',\n name: 'Google API Key',\n pattern: /\\bAIza[0-9A-Za-z_-]{35}\\b/,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Quota theft at minimum; API access to whatever the key was scoped to at worst.',\n },\n {\n id: 'secret-openai-key',\n name: 'OpenAI API Key',\n pattern: /\\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Billed inference against the owner’s account, with no per-key spend limit by default.',\n },\n {\n id: 'secret-anthropic-key',\n name: 'Anthropic API Key',\n pattern: /\\bsk-ant-(?:api\\d{2}-)?[A-Za-z0-9_-]{32,}\\b/,\n severity: 'critical',\n cwe: 'CWE-798',\n consequence: 'Billed inference against the owner’s account.',\n },\n {\n id: 'secret-database-url',\n name: 'Database URL with credentials',\n // Requires a credential segment before the `@` — `postgres://localhost/db`\n // is a hostname, not a secret.\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|amqp|clickhouse):\\/\\/[^\\s'\"@\\/]*:[^\\s'\"@\\/]*@[^\\s'\"]+/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Direct database access, usually bypassing every application-level authorisation check.',\n },\n {\n id: 'secret-jwt',\n name: 'JSON Web Token',\n pattern: /\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_.+/=-]*/,\n severity: 'medium',\n cwe: 'CWE-798',\n consequence: 'Session or service identity until it expires — and committed tokens are usually long-lived.',\n },\n {\n id: 'secret-generic-api-key',\n name: 'Generic API Key',\n // Quoted assignment only. An unquoted value in a `.env` is covered by the\n // vendor-prefixed rules above; matching it here is what starts flagging\n // ARNs and parameter-store paths.\n pattern: /(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token)\\s*[=:]\\s*['\"]([A-Za-z0-9\\-_.]{20,})['\"]/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'Whatever the third-party service lets the key do, for as long as it stays valid.',\n },\n {\n id: 'secret-generic-credential',\n name: 'Hardcoded Credential',\n pattern: /(?:secret|password|passwd|pwd|token)\\s*[=:]\\s*['\"]([^'\"\\s]{8,})['\"]/i,\n severity: 'high',\n cwe: 'CWE-798',\n consequence: 'A password in source is a password in every clone, fork and CI cache of that source.',\n },\n {\n id: 'secret-hex-token',\n name: 'High-entropy Hex Token',\n pattern: /(?:token|key|secret|auth|signing)\\w*\\s*[=:]\\s*['\"]?([0-9a-f]{32,})['\"]?/i,\n severity: 'medium',\n cwe: 'CWE-798',\n consequence: 'Signing secrets and session keys are usually hex; a leaked one forges anything they sign.',\n },\n];\n\n/**\n * Values that satisfy a credential shape but are not credentials.\n *\n * Kept deliberately short. Every entry is a documented, publicly-published\n * placeholder — not a guess that something \"looks like a test value\". A\n * generous allow-list here is how a scanner talks itself out of a real finding.\n */\nconst KNOWN_PLACEHOLDERS = [\n // Deliberately NOT here: AWS's published documentation key/secret pair\n // (`AKIAIOSFODNN7EXAMPLE`, `wJalrXUtnFEMI/…`). GitHub allow-lists them, and\n // the argument for following suit is that they authenticate nothing. The\n // argument against is stronger: they appear in a repository because someone\n // pasted a credentials template and left it there, and the remediation —\n // move this to the secret manager — is identical to the one for a live key.\n // Exempting them means the scanner goes quiet on the file most likely to\n // acquire a real key next.\n /\\bEXAMPLE_?KEY\\b/i,\n /\\bYOUR_[A-Z_]*(?:KEY|TOKEN|SECRET|PASSWORD)\\b/,\n /\\b(?:xxx+|X{4,}|\\*{4,}|<[a-z-]+>)\\b/,\n /\\bchangeme\\b/i,\n];\n\n/**\n * Whether the matched text is a documented placeholder rather than material.\n *\n * Note what this does *not* do: it does not exempt a value for being all\n * zeros, all A's, or otherwise \"obviously fake\". Those shapes are exactly what\n * the testbed's fixtures use, deliberately, and a scanner that skips them\n * scores zero on a corpus of real credential formats. Only values a vendor has\n * published as examples are exempt.\n */\nexport function isKnownPlaceholder(text: string): boolean {\n return KNOWN_PLACEHOLDERS.some((pattern) => pattern.test(text));\n}\n\n/**\n * Replace anything that looks like credential material with asterisks.\n *\n * Applied to every excerpt on a secret finding before it reaches a terminal, a\n * SARIF file, a CI log or a PR comment. A scanner that prints the secret it\n * found has moved the secret somewhere new, and CI logs are retained and, on\n * public forks, published.\n */\nexport function redactSecret(line: string): string {\n return line.replace(/([A-Za-z0-9+/=_.-]{12,})/g, (match) => {\n if (match.length <= 12) return match;\n return `${match.slice(0, 3)}${'*'.repeat(Math.min(16, match.length - 3))}`;\n });\n}\n\n/** Files whose mere presence is worth reporting, independent of content. */\nexport const SENSITIVE_FILES: readonly { pattern: string; message: string; severity: Severity }[] = [\n { pattern: '.env', message: 'Environment file committed — the usual home of every runtime credential', severity: 'high' },\n { pattern: '.env.local', message: 'Local environment file committed', severity: 'high' },\n { pattern: '.env.production', message: 'Production environment file committed', severity: 'critical' },\n { pattern: 'id_rsa', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: 'id_ed25519', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: 'id_ecdsa', message: 'Private SSH key committed', severity: 'critical' },\n { pattern: '.pem', message: 'PEM certificate or key file committed', severity: 'high' },\n { pattern: '.p12', message: 'PKCS#12 keystore committed', severity: 'high' },\n { pattern: '.pfx', message: 'PKCS#12 keystore committed', severity: 'high' },\n { pattern: '.keystore', message: 'Java keystore committed', severity: 'high' },\n // Deliberately not `.npmrc`. Its presence is normal; only an `_authToken`\n // line in it is a credential, and that is a content match, not a filename\n // match. Reporting the file itself trades a real finding for a chore.\n];\n","/**\n * The scan engine, minus the filesystem: run every rule set over text.\n *\n * Kept free of I/O entirely — no reading, no printing, no exit codes, no\n * SARIF. The command layer decides how to present what this returns, which is\n * what lets the same scan feed a terminal, a SARIF file and a daemon run\n * without three implementations drifting apart.\n *\n * The absence of `node:` imports here is load-bearing, not incidental. This\n * module is the package's default entry point, and the browser surfaces —\n * web, extension, desktop renderer — import it directly. A single\n * `import … from 'node:fs'` anywhere in this file's dependency graph breaks\n * every one of their bundles, so the tree walker lives in `./node/walk.ts`\n * and everything here works on strings that somebody else read.\n */\n\nimport { CODE_RULES, evaluateRule, proseLines } from './code-rules';\nimport { scanPackageJson, scanRequirementsTxt } from './manifest-rules';\nimport { isKnownPlaceholder, redactSecret, SECRET_RULES, SENSITIVE_FILES } from './secret-rules';\nimport type { ScanFinding, ScanLanguage, Severity } from './types';\nimport { severityRank } from './types';\n\n/**\n * `extname` and `basename`, reimplemented in three lines each.\n *\n * Importing them from `node:path` is what would otherwise put this module —\n * and therefore the package's whole default entry point — out of reach of a\n * browser bundle, for two functions that are pure string arithmetic.\n *\n * Semantics match the originals on the inputs that reach them: a leading dot\n * is not an extension, so `.env` has none, and a name with no dot has none\n * either. Only `/` is treated as a separator, which is what the callers pass —\n * repository-relative paths and shebang interpreter paths.\n */\nfunction baseNameOf(path: string): string {\n return path.slice(path.lastIndexOf('/') + 1);\n}\n\nfunction extensionOf(path: string): string {\n const base = baseNameOf(path);\n const dot = base.lastIndexOf('.');\n return dot <= 0 ? '' : base.slice(dot);\n}\n\nexport const SKIP_DIRS = new Set([\n 'node_modules', '.git', '.next', '.nuxt', 'dist', 'build', 'out', '__pycache__',\n '.venv', 'venv', 'vendor', '.terraform', 'coverage', '.cache', '.pnpm-store',\n 'target', '.gradle', '.idea', '.vscode', 'bower_components', '.svelte-kit',\n]);\n\nexport const SCAN_EXTENSIONS = new Set([\n '.ts', '.js', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts',\n '.py', '.rb', '.go', '.java', '.kt', '.scala', '.php', '.rs',\n '.c', '.cc', '.cpp', '.h', '.hpp', '.cs', '.swift',\n '.yml', '.yaml', '.json', '.toml', '.ini', '.cfg', '.conf', '.env',\n '.sh', '.bash', '.zsh', '.tf', '.hcl', '.xml', '.properties', '.gradle',\n '.txt', '.md', '.sql', '.erb', '.ejs', '.vue', '.svelte',\n]);\n\nconst LANGUAGE_BY_EXTENSION: Record<string, ScanLanguage> = {\n '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',\n '.ts': 'typescript', '.tsx': 'typescript', '.mts': 'typescript', '.cts': 'typescript',\n '.vue': 'javascript', '.svelte': 'javascript', '.ejs': 'javascript',\n '.py': 'python',\n '.rb': 'ruby', '.erb': 'ruby',\n '.go': 'go',\n '.java': 'java', '.kt': 'java', '.scala': 'java',\n '.php': 'php',\n '.sh': 'shell', '.bash': 'shell', '.zsh': 'shell',\n '.yml': 'config', '.yaml': 'config', '.json': 'config', '.toml': 'config',\n '.ini': 'config', '.cfg': 'config', '.conf': 'config', '.env': 'config',\n '.tf': 'config', '.hcl': 'config', '.properties': 'config',\n};\n\nexport function languageOf(filename: string): ScanLanguage {\n if (filename.startsWith('.env') || filename.endsWith('.env')) return 'config';\n return LANGUAGE_BY_EXTENSION[extensionOf(filename).toLowerCase()] ?? 'other';\n}\n\n/** Interpreters worth recognising, by the language their scripts are written in. */\nconst LANGUAGE_BY_INTERPRETER: Record<string, ScanLanguage> = {\n sh: 'shell', bash: 'shell', zsh: 'shell', dash: 'shell', ksh: 'shell', ash: 'shell',\n python: 'python', python2: 'python', python3: 'python',\n ruby: 'ruby',\n node: 'javascript', nodejs: 'javascript', deno: 'javascript', bun: 'javascript',\n php: 'php',\n};\n\n/**\n * The language a `#!` line declares, or `null` if the line is not a shebang.\n *\n * An executable in a repository root is routinely named for the command it\n * provides rather than the language it is written in — `debtap`, `configure`,\n * `gradlew`. Extension-based detection skips every one of them, which is worst\n * exactly where it matters: a project whose entire source is one extensionless\n * script gets a clean scan because nothing was read.\n *\n * The shebang is the authoritative answer to a question the filename cannot\n * answer, and the kernel already treats it that way.\n */\nexport function languageOfShebang(firstLine: string): ScanLanguage | null {\n const match = /^#!\\s*(\\S+)(?:\\s+(.+?))?\\s*$/.exec(firstLine);\n if (!match) return null;\n\n // `#!/usr/bin/env bash` names the interpreter in the argument, not the path.\n const command = baseNameOf(match[1]!);\n const args = match[2]?.trim().split(/\\s+/) ?? [];\n const splitString = args[0] === '-S' || args[0] === '--split-string';\n const name = command === 'env' ? baseNameOf(args[splitString ? 1 : 0] ?? '') : command;\n\n const exact = LANGUAGE_BY_INTERPRETER[name];\n if (exact) return exact;\n\n // `python3.11` and `bash5` are the same interpreters with a version glued on.\n const stripped = name.replace(/[\\d.]+$/, '');\n return (stripped ? LANGUAGE_BY_INTERPRETER[stripped] : undefined) ?? null;\n}\n\n\n/**\n * Inline suppression, matching the convention `modules/code-scanner` already\n * uses so a repository does not learn two syntaxes for the same idea.\n *\n * // threatcrush-disable-next-line secret-aws-access-key fixture, not a key\n * // threatcrush-disable-line\n *\n * The rule id is optional; without one the whole line is suppressed. This\n * exists because the highest-volume false positive in practice is a scanner's\n * own test fixtures — a file of deliberately-malformed credentials is\n * indistinguishable from a file of leaked ones, and only the author knows\n * which. Suppressions are counted and reported: a quiet scan full of\n * suppressions is not a clean one.\n */\nconst SUPPRESS_NEXT = /threatcrush-disable-next-line(?:\\s+([\\w-]+))?/;\nconst SUPPRESS_LINE = /threatcrush-disable-line(?:\\s+([\\w-]+))?/;\n\nexport interface Suppressions {\n /** line index → set of rule ids, or `*` for every rule. */\n byLine: Map<number, Set<string>>;\n count: number;\n}\n\nexport function collectSuppressions(lines: readonly string[]): Suppressions {\n const byLine = new Map<number, Set<string>>();\n let count = 0;\n\n const add = (index: number, ruleId: string | undefined): void => {\n const existing = byLine.get(index) ?? new Set<string>();\n existing.add(ruleId ?? '*');\n byLine.set(index, existing);\n count += 1;\n };\n\n lines.forEach((line, index) => {\n const next = SUPPRESS_NEXT.exec(line);\n if (next) add(index + 1, next[1]);\n const same = SUPPRESS_LINE.exec(line);\n // `disable-next-line` also matches the `disable-line` substring, so only\n // treat it as a same-line directive when the longer form did not match.\n if (same && !next) add(index, same[1]);\n });\n\n return { byLine, count };\n}\n\nfunction isSuppressed(suppressions: Suppressions, index: number, ruleId: string): boolean {\n const rules = suppressions.byLine.get(index);\n if (!rules) return false;\n return rules.has('*') || rules.has(ruleId);\n}\n\n/**\n * Does this path hold tests or fixtures?\n *\n * Used to soften credential findings, never to hide them. A secret in a test\n * is nearly always a fixture — often a deliberately real-looking one, because\n * the test exists to prove the real path is guarded — but \"nearly always\" is\n * not \"always\", and a genuine key does get pasted into a test. So these are\n * still reported, at a severity that does not block a merge, rather than\n * dropped where nobody would ever see them.\n */\nexport function isTestPath(relativePath: string): boolean {\n const p = relativePath.replace(/\\\\/g, '/');\n return (\n /(?:^|\\/)(?:tests?|__tests__|__mocks__|spec|specs|fixtures?|mocks?|e2e|testdata)\\//i.test(p) ||\n /(?:^|\\/)(?:test|conftest)_[^/]+$/i.test(p) ||\n /[._-](?:test|spec)\\.[a-z]+$/i.test(p) ||\n /_test\\.[a-z]+$/i.test(p)\n );\n}\n\n/** Scan a single file's text. Exposed for tests and for single-file callers. */\nexport function scanText(\n relativePath: string,\n text: string,\n language: ScanLanguage = languageOf(relativePath),\n): ScanFinding[] {\n const findings: ScanFinding[] = [];\n const lines = text.split('\\n');\n const suppressions = collectSuppressions(lines);\n const inTests = isTestPath(relativePath);\n\n // ── Credentials ────────────────────────────────────────────────────────\n lines.forEach((line, index) => {\n for (const rule of SECRET_RULES) {\n const match = rule.pattern.exec(line);\n if (!match) continue;\n if (isKnownPlaceholder(match[0])) continue;\n if (isSuppressed(suppressions, index, rule.id)) continue;\n\n findings.push({\n ruleId: rule.id,\n title: rule.name,\n file: relativePath,\n line: index + 1,\n // Reported but not blocking in tests — see isTestPath.\n severity: inTests ? 'low' : rule.severity,\n // A matched credential format is the finding, not a proxy for one.\n confidence: 'evidence',\n message: inTests\n ? `Possible ${rule.name} detected in a test file — usually a fixture, still worth confirming it is not a live credential`\n : `Possible ${rule.name} detected`,\n consequence: rule.consequence,\n cwe: rule.cwe,\n excerpt: redactSecret(line.trim()).slice(0, 200),\n sensitive: true,\n category: 'secret',\n });\n }\n });\n\n // ── Code-level constructs ──────────────────────────────────────────────\n const prose = proseLines(lines);\n lines.forEach((_line, index) => {\n for (const rule of CODE_RULES) {\n if (isSuppressed(suppressions, index, rule.id)) continue;\n const match = evaluateRule(rule, { lines, index, language, prose });\n if (!match) continue;\n\n findings.push({\n ruleId: rule.id,\n title: rule.title,\n file: relativePath,\n line: index + 1,\n severity: match.severity,\n confidence: match.confidence,\n message: `${rule.title} (${rule.cwe})`,\n consequence: rule.consequence,\n cwe: rule.cwe,\n excerpt: (lines[index] ?? '').trim().slice(0, 200),\n category: 'code',\n });\n }\n });\n\n return findings;\n}\n\nexport function scanManifest(relativePath: string, filename: string, text: string): ScanFinding[] {\n const manifestFindings =\n filename === 'package.json'\n ? scanPackageJson(text)\n : filename === 'requirements.txt'\n ? scanRequirementsTxt(text)\n : [];\n\n return manifestFindings.map((finding) => ({\n ruleId: finding.ruleId,\n title: finding.title,\n file: relativePath,\n line: finding.line,\n severity: finding.severity,\n confidence: 'evidence' as const,\n message: finding.message,\n consequence: finding.consequence,\n cwe: finding.cwe,\n excerpt: finding.excerpt.slice(0, 200),\n category: 'manifest' as const,\n }));\n}\n\n\n\n/** Highest severity present, or null for a clean scan. */\nexport function peakSeverity(findings: readonly ScanFinding[]): Severity | null {\n let peak: Severity | null = null;\n for (const finding of findings) {\n if (!peak || severityRank(finding.severity) > severityRank(peak)) peak = finding.severity;\n }\n return peak;\n}\n\n/** True when any finding is at or above `threshold`. Drives `--fail-on`. */\nexport function meetsFailThreshold(\n findings: readonly ScanFinding[],\n threshold: readonly Severity[],\n): boolean {\n if (threshold.length === 0) return false;\n const floor = Math.min(...threshold.map(severityRank));\n return findings.some((finding) => severityRank(finding.severity) >= floor);\n}\n","/**\n * The filesystem half of the scan engine: walk a tree, read what is scannable,\n * hand the text to the rules.\n *\n * Split from `../text.ts` because this file imports `node:fs` and that one must\n * not. The package's default entry point is consumed by browser bundles, and a\n * single filesystem import anywhere in its graph breaks all of them. Everything\n * that needs a disk lives behind the `./node` entry point instead.\n */\n\nimport {\n closeSync, fstatSync, openSync, readdirSync, readFileSync, readSync, statSync,\n} from 'node:fs';\nimport { basename, dirname, extname, join, relative, sep } from 'node:path';\nimport { SENSITIVE_FILES } from '../secret-rules';\nimport {\n collectSuppressions,\n languageOf,\n languageOfShebang,\n SCAN_EXTENSIONS,\n scanManifest,\n scanText,\n SKIP_DIRS,\n} from '../text';\nimport type { ScanFinding, ScanLanguage } from '../types';\nimport { severityRank } from '../types';\n\nexport interface ScanOptions {\n /** Skip files larger than this. Defaults to 1 MiB. */\n maxFileBytes?: number;\n /** Called once per file actually read, for progress reporting. */\n onFile?: (path: string) => void;\n /** Restrict to these rule categories. Defaults to all. */\n categories?: readonly ScanFinding['category'][];\n}\n\nexport interface ScanReport {\n findings: ScanFinding[];\n filesScanned: number;\n /**\n * How many inline suppressions were honoured. Reported, never hidden: a\n * scan that came back quiet because someone silenced forty rules is a\n * different result from a scan that came back quiet.\n */\n suppressed: number;\n /**\n * Directory that finding paths are relative to. Equal to the target for a\n * directory scan, its parent for a single-file scan. SARIF URI resolution\n * needs this — guessing it from the target is what produces file URIs that\n * resolve to nothing.\n */\n root: string;\n /**\n * Files matched by extension but unreadable. Reported rather than swallowed:\n * a scan that could not read a file has not cleared it, and \"0 findings\"\n * over an unread tree is the failure this scanner exists to avoid.\n */\n unreadable: string[];\n}\n\nexport function scanPath(targetPath: string, options: ScanOptions = {}): ScanReport {\n const maxFileBytes = options.maxFileBytes ?? 1024 * 1024;\n const allowed = options.categories ? new Set(options.categories) : null;\n const findings: ScanFinding[] = [];\n const unreadable: string[] = [];\n let filesScanned = 0;\n let suppressed = 0;\n\n // A file target is not a degenerate directory target. `readdirSync` on a\n // file throws ENOTDIR, which the walker below treats as an unreadable\n // directory — so `threatcrush scan app.js` reported a clean scan of a file\n // it never opened. Resolve the shape first, and walk only what is walkable.\n const rootIsDirectory = (() => {\n try {\n return statSync(targetPath).isDirectory();\n } catch {\n return true;\n }\n })();\n const walkRoot = rootIsDirectory ? targetPath : dirname(targetPath);\n\n const scanFile = (fullPath: string, filename: string): void => {\n const relativePath = toRelative(walkRoot, fullPath);\n const extension = extname(filename).toLowerCase();\n const isManifest = filename === 'package.json' || filename === 'requirements.txt';\n const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith('.env');\n\n // A file with no extension gets one question asked of it before being\n // dismissed: does it start with a shebang? Executables are habitually named\n // for what they do rather than what they are written in, and skipping them\n // silently is how a repository whose only source file is `debtap` scans\n // clean. Files that carry an unrecognised extension are still skipped —\n // `.png` is not a script, and sniffing every one of them would mean reading\n // the whole tree.\n const mayDeclareInterpreter = !scannable && !isManifest && extension === '';\n\n if (!scannable && !isManifest && !mayDeclareInterpreter) {\n recordSensitiveFile(filename, relativePath, findings, []);\n return;\n }\n\n // Size-check and read through one descriptor.\n //\n // `statSync(path)` followed by `readFileSync(path)` is check-then-use: the\n // path can be replaced between the two calls, so the size that was checked\n // is not necessarily the size that gets read. Opening once and calling\n // `fstatSync` on the descriptor removes the window — the descriptor refers\n // to the same inode for both operations, whatever happens to the name.\n //\n // A scanner walking directories it does not control is exactly where this\n // matters, and CWE-362 is a class this tool reports on. Worth getting\n // right in its own walker.\n let text: string;\n let handle: number;\n let declared: ScanLanguage | null = null;\n try {\n handle = openSync(fullPath, 'r');\n } catch {\n unreadable.push(relativePath);\n return;\n }\n\n try {\n if (fstatSync(handle).size > maxFileBytes) return;\n\n // Sniff the shebang from a short prefix rather than the whole file, so an\n // extensionless blob — a checked-in binary, a data file — costs one small\n // read instead of a megabyte decoded as UTF-8 and thrown away.\n if (mayDeclareInterpreter) {\n const prefix = Buffer.alloc(128);\n const read = readSync(handle, prefix, 0, prefix.length, 0);\n declared = languageOfShebang(prefix.subarray(0, read).toString('utf-8').split('\\n', 1)[0] ?? '');\n if (!declared) return;\n }\n\n text = readFileSync(handle, 'utf-8');\n } catch {\n unreadable.push(relativePath);\n return;\n } finally {\n try {\n closeSync(handle);\n } catch {\n /* the descriptor is going away regardless */\n }\n }\n\n filesScanned += 1;\n options.onFile?.(relativePath);\n suppressed += collectSuppressions(text.split('\\n')).count;\n\n const fileFindings = [\n ...scanText(relativePath, text, declared ?? languageOf(filename)),\n ...(isManifest ? scanManifest(relativePath, filename, text) : []),\n ];\n\n findings.push(...fileFindings);\n recordSensitiveFile(filename, relativePath, findings, fileFindings);\n };\n\n const walk = (currentPath: string): void => {\n let entries;\n try {\n entries = readdirSync(currentPath, { withFileTypes: true });\n } catch {\n unreadable.push(toRelative(walkRoot, currentPath));\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue;\n walk(fullPath);\n continue;\n }\n if (!entry.isFile()) continue;\n\n scanFile(fullPath, entry.name);\n }\n };\n\n if (rootIsDirectory) {\n walk(targetPath);\n } else {\n scanFile(targetPath, basename(targetPath));\n }\n\n const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;\n filtered.sort(\n (a, b) =>\n severityRank(b.severity) - severityRank(a.severity) ||\n a.file.localeCompare(b.file) ||\n a.line - b.line,\n );\n\n return { findings: filtered, filesScanned, unreadable, suppressed, root: walkRoot };\n}\n\n/**\n * Report a file whose *name* is the finding — but only when its contents\n * produced nothing.\n *\n * A `.env` full of detected credentials does not also need \"this is a .env\n * file\" stapled to line 1. The filename finding exists for the case the\n * content rules cannot cover: an env file whose values are shapes no vendor\n * rule matches, which is still an env file that should not be committed.\n */\nfunction recordSensitiveFile(\n filename: string,\n relativePath: string,\n sink: ScanFinding[],\n fileFindings: readonly ScanFinding[],\n): void {\n if (fileFindings.length > 0) return;\n\n for (const sensitive of SENSITIVE_FILES) {\n const matches = filename === sensitive.pattern || filename.endsWith(sensitive.pattern);\n if (!matches) continue;\n sink.push({\n ruleId: 'sensitive-file-committed',\n title: 'Sensitive file',\n file: relativePath,\n line: 1,\n severity: sensitive.severity,\n confidence: 'evidence',\n message: sensitive.message,\n consequence: 'Anything in this file is in every clone, fork and CI cache of the repository.',\n cwe: 'CWE-538',\n excerpt: '',\n sensitive: true,\n category: 'file',\n });\n return;\n }\n}\n\nfunction toRelative(base: string, target: string): string {\n const rel = relative(base, target);\n return (rel === '' ? target : rel).split(sep).join('/');\n}\n","/**\n * Dependency advisory lookup against OSV.dev (PRD 06).\n *\n * Split out of `commands/scan.ts` unchanged in behaviour. It is the only part\n * of a scan that makes network calls, and that difference is worth a module\n * boundary: the pattern rules are deterministic and fast, this is neither, and\n * CI wants to choose. `runScan` keeps calling it (the daemon has always\n * included advisories); the CLI asks for it with `--deps`.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { ScanFinding, Severity } from '../types';\n\ninterface OsvVulnerability {\n id: string;\n summary?: string;\n details?: string;\n severity?: Array<{ type: string; score: string }>;\n}\n\nconst LOCKFILES: readonly { file: string; ecosystem: string }[] = [\n { file: 'package-lock.json', ecosystem: 'npm' },\n { file: 'pnpm-lock.yaml', ecosystem: 'npm' },\n { file: 'yarn.lock', ecosystem: 'npm' },\n { file: 'requirements.txt', ecosystem: 'PyPI' },\n { file: 'Pipfile.lock', ecosystem: 'PyPI' },\n];\n\n/** Cap per lockfile, so a first run on a neglected tree summarises rather than floods OSV. */\nconst MAX_DEPS_PER_LOCKFILE = 50;\n\nexport async function scanDependencies(targetPath: string): Promise<ScanFinding[]> {\n const findings: ScanFinding[] = [];\n\n for (const { file, ecosystem } of LOCKFILES) {\n const lockPath = join(targetPath, file);\n if (!existsSync(lockPath)) continue;\n\n let deps: Array<{ name: string; version: string }>;\n try {\n deps = parseDependencies(lockPath, file);\n } catch {\n continue;\n }\n\n for (const dep of deps.slice(0, MAX_DEPS_PER_LOCKFILE)) {\n let vulns: OsvVulnerability[];\n try {\n vulns = await queryOsv(dep.name, dep.version, ecosystem);\n } catch {\n continue;\n }\n\n for (const vuln of vulns) {\n const cvss = vuln.severity?.find((entry) => entry.type === 'CVSS_V3')?.score;\n findings.push({\n ruleId: 'dependency-known-vulnerability',\n title: 'Dependency CVE',\n file,\n line: 1,\n severity: severityFromCvss(cvss),\n confidence: 'evidence',\n message: `${dep.name}@${dep.version}: ${vuln.summary ?? vuln.id}`,\n consequence: 'A published advisory exists for the exact version resolved in this lockfile.',\n excerpt: `${vuln.id}${cvss ? ` (CVSS: ${cvss})` : ''}`,\n category: 'dependency',\n });\n }\n }\n }\n\n return findings;\n}\n\nfunction severityFromCvss(score: string | undefined): Severity {\n if (!score) return 'medium';\n const value = Number.parseFloat(score);\n if (Number.isNaN(value)) return 'medium';\n if (value >= 9) return 'critical';\n if (value >= 7) return 'high';\n if (value >= 4) return 'medium';\n return 'low';\n}\n\nfunction parseDependencies(lockPath: string, filename: string): Array<{ name: string; version: string }> {\n const deps: Array<{ name: string; version: string }> = [];\n\n if (filename === 'package-lock.json') {\n const lock = JSON.parse(readFileSync(lockPath, 'utf-8')) as {\n packages?: Record<string, { version?: string }>;\n dependencies?: Record<string, { version?: string }>;\n };\n const packages = lock.packages ?? lock.dependencies ?? {};\n for (const [key, value] of Object.entries(packages)) {\n const name = key.replace(/^node_modules\\//, '');\n const version = value?.version;\n if (name && version && !name.startsWith('.')) deps.push({ name, version });\n }\n return deps;\n }\n\n if (filename === 'requirements.txt') {\n for (const line of readFileSync(lockPath, 'utf-8').split('\\n')) {\n const match = /^([a-zA-Z0-9_.-]+)==([0-9.]+)/.exec(line);\n if (match?.[1] && match[2]) deps.push({ name: match[1], version: match[2] });\n }\n }\n\n return deps;\n}\n\n/** Package names and versions are validated before they reach the query body. */\nfunction isValidPackageName(name: string): boolean {\n return /^[@a-zA-Z0-9_.\\-/]{1,214}$/.test(name);\n}\n\nfunction isValidVersion(version: string): boolean {\n return /^[0-9a-zA-Z._\\-+]{1,50}$/.test(version);\n}\n\nasync function queryOsv(name: string, version: string, ecosystem: string): Promise<OsvVulnerability[]> {\n if (!isValidPackageName(name) || !isValidVersion(version)) return [];\n\n try {\n const response = await fetch('https://api.osv.dev/v1/query', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ package: { name, ecosystem }, version }),\n signal: AbortSignal.timeout(5000),\n });\n if (!response.ok) return [];\n const data = (await response.json()) as { vulns?: OsvVulnerability[] };\n return data.vulns ?? [];\n } catch {\n return [];\n }\n}\n","/**\n * SARIF 2.1.0 output.\n *\n * Why native, rather than converting the CLI's terminal output: a text parser\n * sitting between a scanner and its consumer fails in the one way that matters\n * — silently. `profullstack/malware-test-prs` documents three separate bugs its\n * `threatcrush-to-sarif.py` hit, and one of them (paths relative to the scan\n * root, unprefixed) made a working scan report a 0% true-positive rate. The\n * scan was fine. The pipe was lying.\n *\n * Emitting SARIF from the process that found the finding removes that class of\n * failure. It also makes the output portable: GitHub's Security tab, the\n * testbed's coverage validator, and any other SARIF consumer read the same\n * bytes, and none of them has to know what a ThreatCrush terminal line looks\n * like.\n *\n * Two details the spec is strict about and consumers are not forgiving about:\n *\n * - `startLine` must be >= 1. Whole-file findings carry no line, so they are\n * clamped rather than emitted as 0, which fails schema validation.\n * - `artifactLocation.uri` must be relative to something the consumer can\n * resolve. Absolute paths from a CI runner (`/home/runner/work/…`) match\n * nothing in the repository view, so every finding lands \"outside\" whatever\n * the consumer was scoping to.\n */\n\nimport { createHash } from 'node:crypto';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport type { ScanFinding, Severity } from '../types';\n\n/**\n * The key our fingerprint is published under.\n *\n * Deliberately *not* `primaryLocationLineHash`. That name is reserved: the\n * CodeQL upload action computes its own value for it and logs\n *\n * Calculated fingerprint of 13bfd14c5cc763c:1 for file debtap line 104,\n * but found existing inconsistent fingerprint value <ours>\n *\n * for every finding whose value differs from what it derived — which is any\n * value we supply, whatever it contains. The first attempt at this replaced\n * the old `ruleId:file:line` with a content hash and still logged the warning,\n * because the collision is over the *key*, not the format.\n *\n * Namespacing it leaves GitHub to compute the fingerprint it wants while other\n * SARIF consumers keep a stable identity from us. The version suffix is there\n * so the hash input can change later without silently redefining what an\n * existing value meant.\n */\nconst FINGERPRINT_KEY = 'threatcrush/contentHash/v1';\n\n/**\n * A stable identity for a finding, for `partialFingerprints`.\n *\n * The line number is deliberately not part of it. It used to be — the value\n * was `ruleId:file:line` — which meant adding an import at the top of a file\n * re-fingerprinted every finding below it. A consumer that tracks findings by\n * fingerprint then treats them as new: previously dismissed ones come back,\n * and review comments detach from the code they were written about. Hashing\n * the rule, the file and the matched text instead keeps one finding identified\n * as one finding while it moves around the file.\n *\n * Whitespace is normalised so reindentation does not count as a new finding.\n * Two identical lines in one file collide onto one fingerprint, which is the\n * right trade: they are the same defect, and SARIF locations still tell them\n * apart.\n */\nexport function fingerprintOf(finding: ScanFinding): string {\n const content = finding.excerpt.replace(/\\s+/g, ' ').trim();\n return createHash('sha256')\n .update(`${finding.ruleId}\\n${finding.file}\\n${content}`)\n .digest('hex')\n .slice(0, 32);\n}\n\nexport const SARIF_VERSION = '2.1.0';\nexport const SARIF_SCHEMA =\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json';\n\nexport type SarifLevel = 'error' | 'warning' | 'note' | 'none';\n\n/**\n * SARIF has three levels; ThreatCrush has five severities. The mapping is\n * lossy in the direction that matters least — the exact severity survives in\n * `properties.severity` and in `security-severity`, which is what GitHub's\n * Security tab actually sorts on.\n */\nexport function sarifLevel(severity: Severity): SarifLevel {\n switch (severity) {\n case 'critical':\n case 'high':\n return 'error';\n case 'medium':\n return 'warning';\n case 'low':\n return 'note';\n default:\n return 'none';\n }\n}\n\n/** GitHub reads this to place a finding on its own severity scale. */\nexport function securitySeverity(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return '9.0';\n case 'high':\n return '7.0';\n case 'medium':\n return '5.0';\n case 'low':\n return '3.0';\n default:\n return '1.0';\n }\n}\n\n/**\n * Turn a finding's path into a SARIF artifact URI.\n *\n * Findings carry paths relative to the *scan root*; consumers resolve URIs\n * against the *repository root*. Those are the same directory only when the\n * scan target is `.`, and the difference is silent — `secrets/x.env` matches\n * nothing in a repository that holds `vulns/secrets/x.env`, so a working scan\n * reports every finding as out-of-scope. `root` closes that gap by\n * reconstructing the absolute path before making it relative to `base`.\n *\n * Files outside `base` keep an absolute POSIX path rather than acquiring a run\n * of `../` segments no consumer resolves usefully.\n */\nexport function toArtifactUri(\n filePath: string,\n base: string,\n prefix = '',\n root = base,\n): string {\n const absolute = isAbsolute(filePath) ? filePath : resolve(root, filePath);\n const relativePath = relative(base, absolute);\n const escapedOut = relativePath.startsWith('..') || relativePath === '';\n const chosen = escapedOut ? absolute : relativePath;\n const posix = chosen.split(sep).join('/').replace(/^\\.\\//, '');\n if (!prefix || escapedOut) return posix;\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '');\n return trimmed ? `${trimmed}/${posix}` : posix;\n}\n\nexport interface SarifOptions {\n /** Version string reported as the tool's. */\n toolVersion: string;\n /**\n * Prepended to every relative URI. Covers the one case `root` cannot: a\n * scan run from *inside* the directory it is scanning, where the repository\n * root is not an ancestor of the working directory in any way the process\n * can observe.\n */\n pathPrefix?: string;\n /** Absolute path the URIs are made relative to. Defaults to `process.cwd()`. */\n base?: string;\n /** Absolute scan root that finding paths are relative to. Defaults to `base`. */\n root?: string;\n}\n\ninterface SarifRule {\n id: string;\n name: string;\n shortDescription: { text: string };\n fullDescription: { text: string };\n help: { text: string; markdown: string };\n defaultConfiguration: { level: SarifLevel };\n properties: {\n tags: string[];\n 'security-severity': string;\n precision: string;\n };\n}\n\n/**\n * Build a complete SARIF log.\n *\n * Always returns a valid run, including for zero findings — an empty `results`\n * array is a meaningful statement (\"looked, found nothing\") and consumers\n * distinguish it from a missing file.\n */\nexport function buildSarif(findings: readonly ScanFinding[], options: SarifOptions): unknown {\n const rules = new Map<string, SarifRule>();\n\n for (const finding of findings) {\n if (rules.has(finding.ruleId)) continue;\n const tags = ['security'];\n if (finding.cwe) tags.push(`external/cwe/${finding.cwe.toLowerCase()}`);\n tags.push(`threatcrush/${finding.category}`);\n\n const description = finding.consequence\n ? `${finding.title}. ${finding.consequence}`\n : finding.title;\n\n rules.set(finding.ruleId, {\n id: finding.ruleId,\n name: finding.ruleId,\n shortDescription: { text: finding.title },\n fullDescription: { text: description },\n help: {\n text: description,\n markdown: finding.consequence\n ? `**${finding.title}**\\n\\n${finding.consequence}`\n : `**${finding.title}**`,\n },\n defaultConfiguration: { level: sarifLevel(finding.severity) },\n properties: {\n tags,\n 'security-severity': securitySeverity(finding.severity),\n // SARIF's vocabulary for how much the rule is claiming. It lines up\n // with the confidence model: a bare construct match is `medium`, a\n // match with visible untrusted input is `high`.\n precision: finding.confidence === 'pattern' ? 'medium' : 'high',\n },\n });\n }\n\n const base = options.base ?? process.cwd();\n const root = options.root ?? base;\n\n const results = findings.map((finding) => ({\n ruleId: finding.ruleId,\n level: sarifLevel(finding.severity),\n message: { text: finding.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: toArtifactUri(finding.file, base, options.pathPrefix, root),\n uriBaseId: '%SRCROOT%',\n },\n region: {\n // Clamped, never 0. A whole-file finding has no line; SARIF has no\n // way to say that, and 0 fails validation outright.\n startLine: Math.max(1, finding.line),\n snippet: { text: finding.excerpt },\n },\n },\n },\n ],\n partialFingerprints: {\n [FINGERPRINT_KEY]: fingerprintOf(finding),\n },\n properties: {\n severity: finding.severity,\n confidence: finding.confidence,\n category: finding.category,\n ...(finding.cwe ? { cwe: finding.cwe } : {}),\n },\n }));\n\n return {\n $schema: SARIF_SCHEMA,\n version: SARIF_VERSION,\n runs: [\n {\n tool: {\n driver: {\n name: 'ThreatCrush',\n version: options.toolVersion,\n informationUri: 'https://threatcrush.com',\n rules: [...rules.values()],\n },\n },\n results,\n columnKind: 'utf16CodeUnits',\n },\n ],\n };\n}\n","import { execSync } from 'node:child_process';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { banner, logger } from '../core/logger.js';\nimport type { RunResult, StructuredFinding } from '../core/run-result.js';\nimport { summarize } from '../core/run-result.js';\n\ninterface PentestResult {\n url: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n message: string;\n details?: string;\n}\n\n// Basic vulnerability tests\nconst PENTEST_CHECKS = [\n {\n name: 'XSS Reflected',\n test: (html: string) => /<script>alert\\(1\\)<\\/script>|<img\\s+src=x\\s+onerror=alert/i.test(html),\n severity: 'critical' as const,\n message: 'Reflected XSS payload rendered in response',\n },\n {\n name: 'Open Redirect',\n test: (url: string, body: string) => body.includes('location.href') || body.includes('window.location'),\n severity: 'medium' as const,\n message: 'Potential open redirect detected',\n },\n {\n name: 'Missing Security Headers',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const required = ['x-content-type-options', 'x-frame-options', 'strict-transport-security'];\n const missing = required.filter(h => !headers[h.toLowerCase()]);\n return missing.length > 2;\n },\n severity: 'low' as const,\n message: 'Missing critical security headers (X-Content-Type-Options, X-Frame-Options, HSTS)',\n },\n {\n name: 'Server Version Disclosure',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n return !!(headers['server'] && /apache|nginx|iis|tomcat/i.test(headers['server']));\n },\n severity: 'low' as const,\n message: 'Server version disclosed in response header',\n },\n {\n name: 'Directory Listing',\n test: (html: string) => /Index of\\s*\\/|<title>Directory Listing/i.test(html),\n severity: 'medium' as const,\n message: 'Directory listing enabled',\n },\n {\n name: 'Error Page Information Disclosure',\n test: (html: string) => /stack trace|traceback|exception|at\\s+\\w+\\.\\w+\\(/i.test(html),\n severity: 'medium' as const,\n message: 'Error page reveals internal information',\n },\n // PRD 07: Additional checks\n {\n name: 'CORS Misconfiguration',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const acao = headers['access-control-allow-origin'];\n return acao === '*' || acao === 'null';\n },\n severity: 'medium' as const,\n message: 'CORS allows any origin (Access-Control-Allow-Origin: *)',\n },\n {\n name: 'Cookie Security',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n const setCookie = headers['set-cookie'] || '';\n return setCookie.length > 0 && (!setCookie.includes('HttpOnly') || !setCookie.includes('Secure'));\n },\n severity: 'medium' as const,\n message: 'Cookies missing HttpOnly or Secure flags',\n },\n {\n name: 'Content Security Policy',\n test: (_url: string, _body: string, headers: Record<string, string>) => {\n return !headers['content-security-policy'];\n },\n severity: 'low' as const,\n message: 'No Content-Security-Policy header set',\n },\n {\n name: 'Sensitive Path Exposure',\n test: (html: string) => /\\.env|wp-admin|phpinfo|\\.git\\/config|server-status/i.test(html),\n severity: 'high' as const,\n message: 'Response references sensitive paths or admin endpoints',\n },\n];\n\nexport async function runPentest(rawUrl: string): Promise<RunResult> {\n const targetUrl = rawUrl.startsWith('http') ? rawUrl : `https://${rawUrl}`;\n const results = await collectPentestResults(targetUrl);\n const structured: StructuredFinding[] = results.map((r) => ({\n type: r.type,\n severity: r.severity === 'low' ? 'low' : (r.severity as StructuredFinding['severity']),\n message: r.message,\n location: r.url,\n details: r.details ? { detail: r.details } : undefined,\n }));\n const counts = summarize(structured);\n return {\n type: 'pentest',\n target: targetUrl,\n findings: structured,\n severity_summary: counts,\n summary: structured.length === 0\n ? 'No vulnerabilities detected'\n : `${structured.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`,\n };\n}\n\nasync function collectPentestResults(targetUrl: string): Promise<PentestResult[]> {\n const results: PentestResult[] = [];\n try {\n const resp = await fetch(targetUrl, { redirect: 'manual' });\n const headers: Record<string, string> = {};\n resp.headers.forEach((v, k) => { headers[k] = v; });\n const body = await resp.text();\n for (const check of PENTEST_CHECKS) {\n try {\n if (check.test(body, body, headers)) {\n results.push({ url: targetUrl, type: check.name, severity: check.severity, message: check.message });\n }\n } catch { /* skip */ }\n }\n } catch {\n return results;\n }\n\n const sqliPayloads = [\"' OR 1=1--\", \"1' UNION SELECT NULL--\", \"' AND '1'='1\"];\n for (const payload of sqliPayloads) {\n try {\n const testUrl = `${targetUrl}?id=${encodeURIComponent(payload)}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/sql\\s+(syntax|error|exception)|mysql|postgres|ORA-\\d+/i.test(body)) {\n results.push({ url: testUrl, type: 'SQL Injection', severity: 'critical', message: `SQL error with payload: ${payload}` });\n }\n } catch { /* skip */ }\n }\n\n const traversalPaths = ['../../etc/passwd', '..%2F..%2Fetc%2Fpasswd', '....//....//etc/passwd'];\n for (const path of traversalPaths) {\n try {\n const testUrl = `${targetUrl}/${path}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/root:.*:0:0:|daemon:.*:1:1:|nobody:.*:65534/i.test(body)) {\n results.push({ url: testUrl, type: 'Path Traversal', severity: 'critical', message: `Possible /etc/passwd disclosure: ${path}` });\n }\n } catch { /* skip */ }\n }\n\n const methods = ['OPTIONS', 'TRACE', 'DELETE', 'PUT'];\n for (const method of methods) {\n try {\n const resp = await fetch(targetUrl, { method, signal: AbortSignal.timeout(5000) });\n if (resp.status < 400 && method !== 'OPTIONS') {\n results.push({ url: targetUrl, type: `Unsafe HTTP Method: ${method}`, severity: 'medium', message: `${method} allowed (status ${resp.status})` });\n }\n if (method === 'OPTIONS') {\n const allow = resp.headers.get('allow');\n if (allow && /DELETE|PUT|TRACE/i.test(allow)) {\n results.push({ url: targetUrl, type: 'HTTP Methods', severity: 'low', message: `Allowed methods: ${allow}` });\n }\n }\n } catch { /* skip */ }\n }\n\n return results;\n}\n\nexport async function pentestCommand(targetUrl: string): Promise<RunResult> {\n banner();\n\n // Ensure URL has protocol\n if (!targetUrl.startsWith('http')) {\n targetUrl = `https://${targetUrl}`;\n }\n\n logger.info(`Penetration testing ${chalk.white(targetUrl)}...\\n`);\n\n const results: PentestResult[] = [];\n\n // Test 1: Basic response analysis\n const spinner = ora({ text: 'Fetching target...', color: 'green' }).start();\n try {\n const resp = await fetch(targetUrl, { redirect: 'manual' });\n const headers: Record<string, string> = {};\n resp.headers.forEach((v, k) => { headers[k] = v; });\n const body = await resp.text();\n\n spinner.succeed(`Got ${resp.status} response\\n`);\n\n // Run all checks\n for (const check of PENTEST_CHECKS) {\n try {\n if (check.test(body, body, headers)) {\n results.push({\n url: targetUrl,\n type: check.name,\n severity: check.severity,\n message: check.message,\n });\n }\n } catch {\n // Skip check on error\n }\n }\n } catch (err) {\n spinner.fail(`Failed to reach target: ${(err as Error).message}`);\n console.log(chalk.gray(' Check the URL and try again.\\n'));\n return {\n type: 'pentest',\n target: targetUrl,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `Failed to reach target: ${(err as Error).message}`,\n error: (err as Error).message,\n };\n }\n\n // Test 2: SQL injection probe\n const sqliSpinner = ora({ text: 'Testing SQL injection vectors...', color: 'green' }).start();\n const sqliPayloads = [\"' OR 1=1--\", \"1' UNION SELECT NULL--\", \"' AND '1'='1\"];\n for (const payload of sqliPayloads) {\n try {\n const testUrl = `${targetUrl}?id=${encodeURIComponent(payload)}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/sql\\s+(syntax|error|exception)|mysql|postgres|ORA-\\d+/i.test(body)) {\n results.push({\n url: testUrl,\n type: 'SQL Injection',\n severity: 'critical',\n message: `SQL error response detected with payload: ${payload}`,\n });\n }\n } catch {\n // Skip on timeout/network error\n }\n }\n sqliSpinner.succeed('SQL injection tests complete\\n');\n\n // Test 3: Path traversal probe\n const pathSpinner = ora({ text: 'Testing path traversal...', color: 'green' }).start();\n const traversalPaths = ['../../etc/passwd', '..%2F..%2Fetc%2Fpasswd', '....//....//etc/passwd'];\n for (const path of traversalPaths) {\n try {\n const testUrl = `${targetUrl}/${path}`;\n const resp = await fetch(testUrl, { redirect: 'manual', signal: AbortSignal.timeout(5000) });\n const body = await resp.text();\n if (/root:.*:0:0:|daemon:.*:1:1:|nobody:.*:65534/i.test(body)) {\n results.push({\n url: testUrl,\n type: 'Path Traversal',\n severity: 'critical',\n message: `Possible /etc/passwd disclosure via: ${path}`,\n });\n }\n } catch {\n // Skip on timeout/network error\n }\n }\n pathSpinner.succeed('Path traversal tests complete\\n');\n\n // Test 4: HTTP methods\n const methodSpinner = ora({ text: 'Testing HTTP methods...', color: 'green' }).start();\n const methods = ['OPTIONS', 'TRACE', 'DELETE', 'PUT'];\n for (const method of methods) {\n try {\n const resp = await fetch(targetUrl, { method, signal: AbortSignal.timeout(5000) });\n if (resp.status < 400 && method !== 'OPTIONS') {\n results.push({\n url: targetUrl,\n type: `Unsafe HTTP Method: ${method}`,\n severity: 'medium',\n message: `${method} method is allowed (status ${resp.status})`,\n });\n }\n if (method === 'OPTIONS') {\n const allow = resp.headers.get('allow');\n if (allow && /DELETE|PUT|TRACE/i.test(allow)) {\n results.push({\n url: targetUrl,\n type: 'HTTP Methods',\n severity: 'low',\n message: `Allowed methods: ${allow}`,\n });\n }\n }\n } catch {\n // Skip on error\n }\n }\n methodSpinner.succeed('HTTP method tests complete\\n');\n\n const structured: StructuredFinding[] = results.map((r) => ({\n type: r.type,\n severity: r.severity as StructuredFinding['severity'],\n message: r.message,\n location: r.url,\n details: r.details ? { detail: r.details } : undefined,\n }));\n const sevCounts = summarize(structured);\n\n // Print results\n if (results.length === 0) {\n console.log(chalk.green.bold(' ✓ No vulnerabilities detected in basic scan!'));\n console.log(chalk.dim(' Note: This is a basic scan. Full pentest requires manual review.\\n'));\n return {\n type: 'pentest',\n target: targetUrl,\n findings: [],\n severity_summary: sevCounts,\n summary: 'No vulnerabilities detected',\n };\n }\n\n const critical = results.filter(r => r.severity === 'critical');\n const high = results.filter(r => r.severity === 'high');\n const medium = results.filter(r => r.severity === 'medium');\n const low = results.filter(r => r.severity === 'low');\n\n console.log(chalk.white.bold(' Penetration Test Results'));\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(\n ` ${chalk.red.bold(critical.length + ' critical')} ` +\n `${chalk.red(high.length + ' high')} ` +\n `${chalk.yellow(medium.length + ' medium')} ` +\n `${chalk.gray(low.length + ' low')}`,\n );\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log();\n\n const sorted = [...critical, ...high, ...medium, ...low];\n for (const r of sorted) {\n const sev =\n r.severity === 'critical' ? chalk.bgRed.white.bold(` ${r.severity.toUpperCase()} `) :\n r.severity === 'high' ? chalk.red(`[${r.severity.toUpperCase()}]`) :\n r.severity === 'medium' ? chalk.yellow(`[${r.severity.toUpperCase()}]`) :\n chalk.gray(`[${r.severity.toUpperCase()}]`);\n\n console.log(` ${sev} ${chalk.white.bold(r.type)}`);\n console.log(` ${chalk.gray('URL:')} ${chalk.cyan(r.url)}`);\n console.log(` ${chalk.gray('Info:')} ${r.message}`);\n if (r.details) console.log(` ${chalk.gray('Details:')} ${r.details}`);\n console.log();\n }\n\n console.log(chalk.gray(' ' + '─'.repeat(70)));\n console.log(` ${chalk.white.bold(`${results.length} issue(s) found`)}`);\n console.log(chalk.dim(' Note: This is an automated basic scan. Manual review recommended.\\n'));\n\n return {\n type: 'pentest',\n target: targetUrl,\n findings: structured,\n severity_summary: sevCounts,\n summary: `${results.length} issue(s): ${sevCounts.critical}C ${sevCounts.high}H ${sevCounts.medium}M ${sevCounts.low}L`,\n };\n}\n","import type { EventBus } from '../event-bus.js';\nimport { readCliConfig, authHeaders, isLoggedIn } from '../../core/cli-config.js';\nimport { runScan } from '../../commands/scan.js';\nimport { runPentest } from '../../commands/pentest.js';\nimport { workerId, type RunResult } from '../../core/run-result.js';\n\nconst API_URL = process.env.THREATCRUSH_API_URL || 'https://threatcrush.com';\nconst POLL_INTERVAL_MS = 30_000;\nconst SCHEDULE_INTERVAL_MS = 120_000;\n\ninterface ClaimedRun {\n id: string;\n org_id: string;\n property_id: string;\n type: 'scan' | 'pentest';\n property: { id: string; name: string; kind: string; target: string } | null;\n}\n\n/**\n * Polls the server for queued property runs belonging to orgs the logged-in\n * user is a member of, claims them atomically, executes them locally, and\n * posts the result back.\n *\n * No-op unless `~/.threatcrush/config.json` contains a valid bearer token.\n */\nexport class RunsWorker {\n private pollTimer: NodeJS.Timeout | null = null;\n private scheduleTimer: NodeJS.Timeout | null = null;\n private running = false;\n private orgIds: string[] = [];\n\n constructor(private bus: EventBus) {}\n\n async start(): Promise<void> {\n if (!isLoggedIn()) return;\n\n try {\n await this.refreshOrgs();\n } catch {\n // First fetch may fail if the network is down; the tick loop will retry.\n }\n\n this.bus.announceModule('runs-worker', 'running', `poll ${POLL_INTERVAL_MS / 1000}s`);\n this.tick();\n this.scheduleTick();\n this.pollTimer = setInterval(() => this.tick(), POLL_INTERVAL_MS);\n this.scheduleTimer = setInterval(() => this.scheduleTick(), SCHEDULE_INTERVAL_MS);\n }\n\n stop(): void {\n if (this.pollTimer) clearInterval(this.pollTimer);\n if (this.scheduleTimer) clearInterval(this.scheduleTimer);\n this.pollTimer = null;\n this.scheduleTimer = null;\n this.bus.announceModule('runs-worker', 'stopped');\n }\n\n private async scheduleTick(): Promise<void> {\n if (!isLoggedIn()) return;\n try {\n if (this.orgIds.length === 0) await this.refreshOrgs();\n for (const orgId of this.orgIds) {\n try {\n await fetch(`${API_URL}/api/orgs/${orgId}/schedules/tick`, {\n method: 'POST',\n headers: authHeaders(),\n });\n } catch {\n // ignore transient network errors\n }\n }\n } catch {\n // swallow — retry next interval\n }\n }\n\n private async tick(): Promise<void> {\n if (this.running) return;\n if (!isLoggedIn()) return;\n\n this.running = true;\n try {\n if (this.orgIds.length === 0) await this.refreshOrgs();\n for (const orgId of this.orgIds) {\n const claimed = await this.claimOne(orgId);\n if (!claimed) continue;\n\n const result = await this.execute(claimed);\n await this.finalize(orgId, claimed, result);\n }\n } catch {\n // swallow — we'll try again on the next tick\n } finally {\n this.running = false;\n }\n }\n\n private async refreshOrgs(): Promise<void> {\n const res = await fetch(`${API_URL}/api/orgs`, { headers: authHeaders() });\n if (!res.ok) return;\n const data = await res.json() as { organizations?: Array<{ id: string }> };\n this.orgIds = (data.organizations || []).map((o) => o.id);\n }\n\n private async claimOne(orgId: string): Promise<ClaimedRun | null> {\n try {\n const res = await fetch(`${API_URL}/api/orgs/${orgId}/runs/pending`, {\n method: 'POST',\n headers: authHeaders(),\n body: JSON.stringify({ worker_id: workerId() }),\n });\n if (!res.ok) return null;\n const data = await res.json() as { run?: ClaimedRun | null };\n return data.run ?? null;\n } catch {\n return null;\n }\n }\n\n private async execute(run: ClaimedRun): Promise<RunResult> {\n const target = run.property?.target;\n if (!target) {\n return {\n type: run.type,\n target: '',\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: 'property target missing',\n error: 'property target missing',\n };\n }\n\n this.bus.announceModule('runs-worker', 'running', `${run.type} ${run.property?.name || target}`);\n\n try {\n if (run.type === 'scan') return await runScan(target);\n return await runPentest(target);\n } catch (err) {\n return {\n type: run.type,\n target,\n findings: [],\n severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },\n summary: `failed: ${(err as Error).message}`,\n error: (err as Error).message,\n };\n }\n }\n\n private async finalize(orgId: string, claimed: ClaimedRun, result: RunResult): Promise<void> {\n try {\n await fetch(\n `${API_URL}/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,\n {\n method: 'PATCH',\n headers: authHeaders(),\n body: JSON.stringify({\n status: result.error ? 'failed' : 'succeeded',\n findings_count: result.findings.length,\n severity_summary: result.severity_summary,\n summary: result.summary,\n findings: result.findings,\n error: result.error,\n source: 'daemon',\n worker_id: workerId(),\n }),\n },\n );\n } catch {\n // best-effort\n } finally {\n this.bus.announceModule('runs-worker', 'idle');\n }\n }\n}\n","import type { ThreatEvent, EventSeverity } from '../../types/events.js';\n\nexport interface DetectionRule {\n id: string;\n title: string;\n description: string;\n version: string;\n category: string;\n severity: EventSeverity;\n source_types: string[];\n match: RuleMatch;\n threshold: number;\n window_seconds: number;\n cooldown_seconds: number;\n tags: string[];\n remediation?: {\n action?: string;\n ttl_seconds?: number;\n description?: string;\n };\n enabled: boolean;\n}\n\nexport interface RuleMatch {\n field: string;\n operator: 'contains' | 'regex' | 'equals' | 'starts_with' | 'ends_with';\n value: string;\n and?: RuleMatch[];\n or?: RuleMatch[];\n}\n\ninterface EventWindow {\n events: Array<{ timestamp: number; event: ThreatEvent }>;\n lastAlert: number;\n}\n\nexport class RuleEngine {\n private rules: DetectionRule[] = [];\n private windows = new Map<string, EventWindow>();\n\n constructor(private onDetection: (detection: {\n rule_id: string;\n severity: EventSeverity;\n title: string;\n description: string;\n source_ip?: string;\n username?: string;\n raw_metadata?: Record<string, unknown>;\n }) => void) {}\n\n loadRules(rules: DetectionRule[]): void {\n this.rules = rules.filter(r => r.enabled !== false);\n }\n\n getRules(): DetectionRule[] {\n return [...this.rules];\n }\n\n evaluate(event: ThreatEvent): void {\n const now = Date.now();\n\n for (const rule of this.rules) {\n // Check source type match\n if (rule.source_types.length > 0 && !rule.source_types.includes(event.module) && !rule.source_types.includes(event.category)) {\n continue;\n }\n\n // Check match conditions\n if (!this.matchesCondition(event, rule.match)) continue;\n\n // Window key: rule_id + source_ip (or 'global')\n const windowKey = `${rule.id}:${event.source_ip || 'global'}`;\n let window = this.windows.get(windowKey);\n if (!window) {\n window = { events: [], lastAlert: 0 };\n this.windows.set(windowKey, window);\n }\n\n // Add event to window\n window.events.push({ timestamp: now, event });\n\n // Prune old events outside window\n const cutoff = now - (rule.window_seconds * 1000);\n window.events = window.events.filter(e => e.timestamp >= cutoff);\n\n // Check threshold\n if (window.events.length < rule.threshold) continue;\n\n // Check cooldown\n if (window.lastAlert > 0 && (now - window.lastAlert) < (rule.cooldown_seconds * 1000)) continue;\n\n // Fire detection\n window.lastAlert = now;\n window.events = []; // Reset window after detection\n\n this.onDetection({\n rule_id: rule.id,\n severity: rule.severity,\n title: rule.title,\n description: `${rule.description} (${rule.threshold} events in ${rule.window_seconds}s)`,\n source_ip: event.source_ip,\n username: event.details?.user as string || undefined,\n raw_metadata: {\n rule_version: rule.version,\n tags: rule.tags,\n category: rule.category,\n remediation: rule.remediation,\n },\n });\n }\n }\n\n private matchesCondition(event: ThreatEvent, match: RuleMatch): boolean {\n const fieldValue = this.getFieldValue(event, match.field);\n if (fieldValue === undefined) return false;\n\n const strValue = String(fieldValue);\n let result = false;\n\n switch (match.operator) {\n case 'contains':\n result = strValue.toLowerCase().includes(String(match.value).toLowerCase());\n break;\n case 'regex':\n try { result = new RegExp(String(match.value), 'i').test(strValue); } catch { result = false; }\n break;\n case 'equals':\n result = strValue === String(match.value);\n break;\n case 'starts_with':\n result = strValue.startsWith(String(match.value));\n break;\n case 'ends_with':\n result = strValue.endsWith(String(match.value));\n break;\n }\n\n // AND conditions\n if (result && match.and) {\n result = match.and.every(m => this.matchesCondition(event, m));\n }\n\n // OR conditions\n if (!result && match.or) {\n result = match.or.some(m => this.matchesCondition(event, m));\n }\n\n return result;\n }\n\n private getFieldValue(event: ThreatEvent, field: string): unknown {\n switch (field) {\n case 'message': return event.message;\n case 'severity': return event.severity;\n case 'module': return event.module;\n case 'category': return event.category;\n case 'source_ip': return event.source_ip;\n default:\n return event.details?.[field];\n }\n }\n\n // Periodic cleanup of stale windows\n cleanup(): void {\n const now = Date.now();\n for (const [key, window] of this.windows.entries()) {\n if (window.events.length === 0 && (now - window.lastAlert) > 3600_000) {\n this.windows.delete(key);\n }\n }\n }\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { DetectionRule } from './engine.js';\nimport { DEFAULT_RULES } from './default-rules.js';\n\nconst RULES_DIR = '/etc/threatcrush/rules.d';\n\nexport function loadAllRules(customDir?: string): DetectionRule[] {\n const rules = [...DEFAULT_RULES];\n const dir = customDir || RULES_DIR;\n\n if (existsSync(dir)) {\n const files = readdirSync(dir).filter(f => f.endsWith('.json'));\n for (const file of files) {\n try {\n const raw = readFileSync(join(dir, file), 'utf-8');\n const parsed = JSON.parse(raw);\n const customRules: DetectionRule[] = Array.isArray(parsed) ? parsed : [parsed];\n for (const rule of customRules) {\n if (!rule.id || !rule.title || !rule.match) {\n console.warn(`[rules] skipping invalid rule in ${file}: missing required fields`);\n continue;\n }\n const existingIdx = rules.findIndex(r => r.id === rule.id);\n if (existingIdx >= 0) {\n rules[existingIdx] = { ...rules[existingIdx], ...rule };\n } else {\n rules.push(rule);\n }\n }\n } catch (err) {\n console.warn(`[rules] failed to load ${file}: ${(err as Error).message}`);\n }\n }\n }\n\n return rules;\n}\n","import type { DetectionRule } from './engine.js';\n\nexport const DEFAULT_RULES: DetectionRule[] = [\n {\n id: 'ssh-brute-force',\n title: 'SSH Brute Force Detected',\n description: 'Multiple failed SSH login attempts from the same source',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'failed ssh login|invalid ssh user',\n },\n threshold: 5,\n window_seconds: 300,\n cooldown_seconds: 600,\n tags: ['ssh', 'brute-force', 'credential-stuffing'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP for 1 hour',\n },\n enabled: true,\n },\n {\n id: 'ssh-success-after-failures',\n title: 'SSH Login After Failed Attempts',\n description: 'Successful SSH login from an IP that had recent failures',\n version: '1.0.0',\n category: 'auth',\n severity: 'critical',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'SSH login accepted',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['ssh', 'compromise-indicator'],\n enabled: true,\n },\n {\n id: 'ssh-root-login',\n title: 'Root SSH Login Attempt',\n description: 'Direct root login via SSH detected',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'regex',\n value: '(failed|accepted).*\\\\broot\\\\b',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['ssh', 'root-access'],\n remediation: {\n action: 'block',\n ttl_seconds: 7200,\n description: 'Block source IP attempting root login',\n },\n enabled: true,\n },\n {\n id: 'ssh-user-enumeration',\n title: 'SSH User Enumeration',\n description: 'Multiple SSH attempts with different usernames from same source',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['ssh-guard', 'auth'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Invalid SSH user',\n },\n threshold: 3,\n window_seconds: 120,\n cooldown_seconds: 600,\n tags: ['ssh', 'enumeration', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing user enumeration',\n },\n enabled: true,\n },\n {\n id: 'sudo-abuse',\n title: 'Sudo Authentication Failure',\n description: 'Repeated sudo authentication failures',\n version: '1.0.0',\n category: 'auth',\n severity: 'high',\n source_types: ['user-journal', 'system'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'sudo.*authentication failure|sudo.*incorrect password|sudo.*FAILED',\n },\n threshold: 3,\n window_seconds: 300,\n cooldown_seconds: 600,\n tags: ['sudo', 'privilege-escalation'],\n enabled: true,\n },\n {\n id: 'web-sqli-attack',\n title: 'SQL Injection Attack Detected',\n description: 'HTTP request with SQL injection patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'critical',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Attack detected [SQLI]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'sqli', 'injection'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing SQL injection',\n },\n enabled: true,\n },\n {\n id: 'web-path-traversal',\n title: 'Path Traversal Attack Detected',\n description: 'HTTP request with path traversal patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'critical',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'Attack detected [PATH_TRAVERSAL]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'path-traversal', 'lfi'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing path traversal',\n },\n enabled: true,\n },\n {\n id: 'web-xss-attack',\n title: 'XSS Attack Detected',\n description: 'HTTP request with cross-site scripting patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'high',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Attack detected \\\\[XSS\\\\]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'xss', 'injection'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block source IP performing XSS attack',\n },\n enabled: true,\n },\n {\n id: 'web-scanner-detection',\n title: 'Web Vulnerability Scanner Detected',\n description: 'High volume of 4xx errors suggesting automated scanning',\n version: '1.0.0',\n category: 'web',\n severity: 'medium',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Client error 4\\\\d{2}:',\n },\n threshold: 20,\n window_seconds: 60,\n cooldown_seconds: 600,\n tags: ['web', 'scanner', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 1800,\n description: 'Block automated scanner',\n },\n enabled: true,\n },\n {\n id: 'port-scan-indicator',\n title: 'Port Scan Indicators',\n description: 'Connection attempts to many ports from a single source',\n version: '1.0.0',\n category: 'network',\n severity: 'medium',\n source_types: ['network-monitor', 'network'],\n match: {\n field: 'message',\n operator: 'contains',\n value: 'port scan',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['network', 'port-scan', 'reconnaissance'],\n remediation: {\n action: 'block',\n ttl_seconds: 3600,\n description: 'Block port scanner',\n },\n enabled: true,\n },\n {\n id: 'system-critical-error',\n title: 'Critical System Error',\n description: 'Critical or emergency level system log message',\n version: '1.0.0',\n category: 'system',\n severity: 'critical',\n source_types: ['user-journal', 'system'],\n match: {\n field: 'severity',\n operator: 'equals',\n value: 'critical',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['system', 'critical'],\n enabled: true,\n },\n {\n id: 'exploit-probe-pattern',\n title: 'Exploit Probe Pattern',\n description: 'HTTP requests matching common exploit probe patterns',\n version: '1.0.0',\n category: 'web',\n severity: 'high',\n source_types: ['log-watcher', 'web'],\n match: {\n field: 'message',\n operator: 'regex',\n value: 'Attack detected \\\\[(CMD_INJECTION|RCE|SSRF|XXE)\\\\]',\n },\n threshold: 1,\n window_seconds: 60,\n cooldown_seconds: 300,\n tags: ['web', 'exploit', 'probe'],\n remediation: {\n action: 'block',\n ttl_seconds: 7200,\n description: 'Block source IP performing exploit probes',\n },\n enabled: true,\n },\n];\n","import { execSync, spawnSync } from 'node:child_process';\nimport { isIP } from 'node:net';\n\nexport interface FirewallAdapter {\n name: string;\n isAvailable(): boolean;\n block(ip: string): Promise<void>;\n unblock(ip: string): Promise<void>;\n isBlocked(ip: string): Promise<boolean>;\n listBlocked(): Promise<string[]>;\n}\n\nfunction assertValidFirewallIp(ip: string): void {\n if (isIP(ip) !== 4) {\n throw new Error(`Invalid IPv4 address: ${ip}`);\n }\n}\n\nexport class NftablesAdapter implements FirewallAdapter {\n name = 'nftables';\n private table = 'threatcrush';\n private set = 'blocklist';\n\n isAvailable(): boolean {\n const result = spawnSync('nft', ['--version'], { stdio: 'pipe' });\n return result.status === 0;\n }\n\n private ensureSetup(): void {\n try {\n execSync(`nft list table inet ${this.table} 2>/dev/null`, { stdio: 'pipe' });\n } catch {\n execSync(`nft add table inet ${this.table}`);\n execSync(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);\n execSync(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);\n execSync(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);\n }\n }\n\n async block(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n this.ensureSetup();\n execSync(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);\n }\n\n async unblock(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n try {\n execSync(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);\n } catch { /* element may not exist */ }\n }\n\n async isBlocked(ip: string): Promise<boolean> {\n assertValidFirewallIp(ip);\n try {\n const output = execSync(`nft list set inet ${this.table} ${this.set}`, { encoding: 'utf-8' });\n return output.includes(ip);\n } catch { return false; }\n }\n\n async listBlocked(): Promise<string[]> {\n try {\n const output = execSync(`nft list set inet ${this.table} ${this.set}`, { encoding: 'utf-8' });\n const match = output.match(/elements\\s*=\\s*\\{([^}]*)\\}/);\n if (!match) return [];\n return match[1].split(',').map(s => s.trim().split(/\\s/)[0]).filter(Boolean);\n } catch { return []; }\n }\n}\n\nexport class IptablesAdapter implements FirewallAdapter {\n name = 'iptables';\n private chain = 'THREATCRUSH';\n\n isAvailable(): boolean {\n const result = spawnSync('iptables', ['--version'], { stdio: 'pipe' });\n return result.status === 0;\n }\n\n private ensureChain(): void {\n try {\n execSync(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: 'pipe' });\n } catch {\n execSync(`iptables -N ${this.chain}`);\n execSync(`iptables -I INPUT 1 -j ${this.chain}`);\n }\n }\n\n async block(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n this.ensureChain();\n if (await this.isBlocked(ip)) return;\n execSync(`iptables -A ${this.chain} -s ${ip} -j DROP`);\n }\n\n async unblock(ip: string): Promise<void> {\n assertValidFirewallIp(ip);\n try { execSync(`iptables -D ${this.chain} -s ${ip} -j DROP`); }\n catch { /* rule may not exist */ }\n }\n\n async isBlocked(ip: string): Promise<boolean> {\n assertValidFirewallIp(ip);\n try {\n const output = execSync(`iptables -n -L ${this.chain}`, { encoding: 'utf-8' });\n return output.includes(ip);\n } catch { return false; }\n }\n\n async listBlocked(): Promise<string[]> {\n try {\n const output = execSync(`iptables -n -L ${this.chain}`, { encoding: 'utf-8' });\n const ips: string[] = [];\n for (const line of output.split('\\n')) {\n const match = line.match(/DROP\\s+all\\s+--\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)/);\n if (match) ips.push(match[1]);\n }\n return ips;\n } catch { return []; }\n }\n}\n\nexport class DryRunAdapter implements FirewallAdapter {\n name = 'dry-run';\n private blocked = new Set<string>();\n\n isAvailable(): boolean { return true; }\n async block(ip: string): Promise<void> { assertValidFirewallIp(ip); this.blocked.add(ip); }\n async unblock(ip: string): Promise<void> { assertValidFirewallIp(ip); this.blocked.delete(ip); }\n async isBlocked(ip: string): Promise<boolean> { assertValidFirewallIp(ip); return this.blocked.has(ip); }\n async listBlocked(): Promise<string[]> { return [...this.blocked]; }\n}\n\nexport function detectFirewallAdapter(): FirewallAdapter {\n const nft = new NftablesAdapter();\n if (nft.isAvailable()) return nft;\n const ipt = new IptablesAdapter();\n if (ipt.isAvailable()) return ipt;\n return new DryRunAdapter();\n}\n","import { appendFileSync } from 'node:fs';\nimport type { FirewallAdapter } from './adapters.js';\nimport type { EventBus } from '../event-bus.js';\nimport { getModuleState, setModuleState } from '../../core/state.js';\nimport { PATHS } from '../paths.js';\nimport type { ThreatEvent } from '../../types/events.js';\n\ninterface BlockEntry {\n ip: string;\n reason: string;\n rule_id?: string;\n blocked_at: number;\n expires_at?: number;\n dry_run: boolean;\n}\n\ninterface RemediationConfig {\n enabled: boolean;\n dry_run: boolean;\n default_ttl_seconds: number;\n min_severity: string;\n allowlist: string[];\n}\n\nconst DEFAULT_CONFIG: RemediationConfig = {\n enabled: true,\n dry_run: true,\n default_ttl_seconds: 3600,\n min_severity: 'high',\n allowlist: ['127.0.0.1', '::1'],\n};\n\nconst SEVERITY_RANK: Record<string, number> = {\n info: 0, low: 1, medium: 2, high: 3, critical: 4,\n};\n\nexport class RemediationManager {\n private config: RemediationConfig;\n private blocklist: BlockEntry[] = [];\n private expiryTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private adapter: FirewallAdapter,\n private bus: EventBus,\n config?: Partial<RemediationConfig>,\n ) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.loadState();\n this.startExpiryWorker();\n }\n\n async handleDetection(event: ThreatEvent): Promise<void> {\n if (!this.config.enabled) return;\n\n const eventRank = SEVERITY_RANK[event.severity] ?? 0;\n const minRank = SEVERITY_RANK[this.config.min_severity] ?? 3;\n if (eventRank < minRank) return;\n\n const ip = event.source_ip;\n if (!ip) return;\n if (this.isAllowlisted(ip)) return;\n if (this.blocklist.some(b => b.ip === ip)) return;\n\n const ruleRemediation = event.details?.remediation as Record<string, unknown> | undefined;\n const ttl = (ruleRemediation?.ttl_seconds as number) || this.config.default_ttl_seconds;\n const ruleId = event.details?.rule_id as string | undefined;\n\n await this.blockIp(ip, event.message, ruleId, ttl);\n }\n\n async blockIp(ip: string, reason: string, ruleId?: string, ttlSeconds?: number): Promise<boolean> {\n if (this.isAllowlisted(ip)) return false;\n\n const entry: BlockEntry = {\n ip,\n reason,\n rule_id: ruleId,\n blocked_at: Date.now(),\n expires_at: ttlSeconds ? Date.now() + (ttlSeconds * 1000) : undefined,\n dry_run: this.config.dry_run,\n };\n\n if (!this.config.dry_run) {\n try {\n await this.adapter.block(ip);\n } catch (err) {\n this.logLine(`[firewall] EACCES or error blocking ${ip}: ${(err as Error).message}`);\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'medium',\n message: `Failed to block ${ip}: ${(err as Error).message}. Ensure daemon has CAP_NET_ADMIN.`,\n });\n return false;\n }\n }\n\n this.blocklist.push(entry);\n this.saveState();\n\n const mode = this.config.dry_run ? '[DRY-RUN] ' : '';\n const expiryMsg = ttlSeconds ? ` (expires in ${ttlSeconds}s)` : ' (permanent)';\n this.logLine(`[firewall] ${mode}Blocked ${ip}: ${reason}${expiryMsg}`);\n\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'info',\n message: `${mode}Blocked ${ip}: ${reason}${expiryMsg}`,\n source_ip: ip,\n details: { action: 'block', rule_id: ruleId, dry_run: this.config.dry_run, ttl_seconds: ttlSeconds },\n });\n\n return true;\n }\n\n async unblockIp(ip: string): Promise<boolean> {\n const idx = this.blocklist.findIndex(b => b.ip === ip);\n if (idx < 0) return false;\n\n const entry = this.blocklist[idx];\n if (!entry.dry_run) {\n try {\n await this.adapter.unblock(ip);\n } catch (err) {\n this.logLine(`[firewall] Error unblocking ${ip}: ${(err as Error).message}`);\n return false;\n }\n }\n\n this.blocklist.splice(idx, 1);\n this.saveState();\n\n this.logLine(`[firewall] Unblocked ${ip}`);\n this.bus.publish({\n timestamp: new Date(),\n module: 'firewall-rules',\n category: 'system',\n severity: 'info',\n message: `Unblocked ${ip}`,\n source_ip: ip,\n details: { action: 'unblock' },\n });\n\n return true;\n }\n\n isAllowlisted(ip: string): boolean {\n return this.config.allowlist.includes(ip);\n }\n\n addToAllowlist(ip: string): void {\n if (!this.config.allowlist.includes(ip)) {\n this.config.allowlist.push(ip);\n }\n }\n\n removeFromAllowlist(ip: string): void {\n this.config.allowlist = this.config.allowlist.filter(a => a !== ip);\n }\n\n getBlocklist(): BlockEntry[] { return [...this.blocklist]; }\n getAllowlist(): string[] { return [...this.config.allowlist]; }\n\n stop(): void {\n if (this.expiryTimer) clearInterval(this.expiryTimer);\n this.expiryTimer = null;\n }\n\n private startExpiryWorker(): void {\n this.expiryTimer = setInterval(() => void this.processExpiries(), 30_000);\n }\n\n private async processExpiries(): Promise<void> {\n const now = Date.now();\n const expired = this.blocklist.filter(b => b.expires_at && b.expires_at <= now);\n for (const entry of expired) {\n await this.unblockIp(entry.ip);\n }\n }\n\n private loadState(): void {\n try {\n const saved = getModuleState('firewall-rules', 'blocklist') as BlockEntry[] | undefined;\n if (Array.isArray(saved)) this.blocklist = saved;\n } catch { /* State DB may not be available */ }\n }\n\n private saveState(): void {\n try { setModuleState('firewall-rules', 'blocklist', this.blocklist); }\n catch { /* State DB may not be available */ }\n }\n\n private logLine(line: string): void {\n try { appendFileSync(PATHS.logFile, `${new Date().toISOString()} ${line}\\n`); }\n catch { /* best-effort */ }\n }\n}\n","/**\n * Opt-in error reporting for the CLI + daemon.\n *\n * Enabled only when `SENTRY_DSN` is set in the environment. Safe to call\n * from both short-lived CLI invocations and the long-running daemon.\n */\n\nlet ready = false;\n// Keep the import lazy so the CLI doesn't pay the Sentry bundle cost when\n// reporting is disabled.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet sentry: any = null;\n\nasync function loadSentry(): Promise<void> {\n if (sentry) return;\n try {\n sentry = await import('@sentry/node');\n } catch {\n sentry = null;\n }\n}\n\nexport async function initTelemetry(context: 'cli' | 'daemon'): Promise<void> {\n if (ready) return;\n const dsn = process.env.SENTRY_DSN;\n if (!dsn) return;\n\n await loadSentry();\n if (!sentry) return;\n\n sentry.init({\n dsn,\n environment: process.env.NODE_ENV || 'production',\n release: process.env.SENTRY_RELEASE,\n serverName: context,\n tracesSampleRate: 0,\n beforeSend(event: Record<string, unknown>) {\n const req = (event as { request?: { headers?: Record<string, string> } }).request;\n if (req?.headers) {\n delete req.headers.authorization;\n delete req.headers.cookie;\n }\n return event;\n },\n });\n\n ready = true;\n}\n\nexport function captureException(err: unknown): void {\n if (!ready || !sentry) return;\n sentry.captureException(err);\n}\n\nexport async function flushTelemetry(timeoutMs = 2000): Promise<void> {\n if (!ready || !sentry) return;\n try { await sentry.flush(timeoutMs); } catch { /* ignore */ }\n}\n","#!/usr/bin/env node\nimport { runDaemon } from './daemon/index.js';\n\nrunDaemon().catch((err) => {\n console.error('threatcrushd failed to start:', err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,sFAAAA,UAAAC,SAAA;AAAA;AACA,QAAM,YAAY;AAClB,QAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA,MAE9B,YAAa,KAAK,UAAU,YAAY;AACtC,cAAM,mBAAmB,KAAK,UAAU,UAAU;AAClD,aAAK,OAAO;AACZ,aAAK,OAAO;AACZ,YAAI,MAAM,kBAAmB,OAAM,kBAAkB,MAAM,YAAW;AAAA,MACxE;AAAA,IACF;AACA,QAAM,QAAN,MAAY;AAAA,MACV,YAAa,QAAQ;AACnB,aAAK,SAAS;AACd,aAAK,MAAM;AACX,aAAK,WAAW;AAChB,aAAK,SAAS;AACd,aAAK,cAAc;AACnB,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AACA,QAAM,SAAN,MAAa;AAAA,MACX,cAAe;AACb,aAAK,MAAM;AACX,aAAK,MAAM;AACX,aAAK,OAAO;AACZ,aAAK,MAAM,CAAC;AACZ,aAAK,MAAM,KAAK;AAChB,aAAK,QAAQ,CAAC;AACd,aA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,kBAAc;AACd,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,MAAM;AAAE,SAAK,SAAS,QAAQ;AAAA,EAAG,CAAC;AACvD,UAAQ,GAAG,WAAW,MAAM;AAAE,SAAK,SAAS,SAAS;AAAA,EAAG,CAAC;AACzD,UAAQ,GAAG,UAAU,MAAM;AAAE,SAAK,SAAS,QAAQ;AAAA,EAAG,CAAC;AAGvD,cAAY,MAAM;AAAA,EAAC,GAAG,KAAK,EAAE;AAC/B;;;AyCtIA,UAAU,EAAE,MAAM,CAAC,QAAQ;AACzB,UAAQ,MAAM,iCAAiC,GAAG;AAClD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["exports","module","exports","module","exports","module","exports","module","exports","module","Date","exports","module","exports","module","exports","module","exports","module","resolve","index","blocksize","exports","module","resolve","exports","module","exports","module","tomlType","str","exports","import_node_fs","import_node_path","import_node_fs","import_node_fs","Database","module","resolve","isRoot","import_node_fs","import_node_path","import_toml","import_node_fs","bus","bus","isRoot","import_node_child_process","import_node_fs","bus","import_node_fs","import_node_readline","bus","import_node_fs","import_node_path","TOML","bus","TOML","SEVERITY_RANK","SEVERITY_RANK","bus","import_node_fs","import_node_path","import_node_os","import_node_fs","import_node_path","import_node_os","process","os","tty","styles","chalk","styles","SEVERITY_COLORS","import_node_os","os","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_path","bus","import_node_fs","import_node_path","import_node_child_process","import_node_net","import_node_fs","DEFAULT_CONFIG","SEVERITY_RANK","bus","readVersion"]}
|