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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions npm/secfoo-sensor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,20 @@ const {
sanitizeRouteTemplate,
} = require("./lib/context");
const { expressMiddleware, fastifyPlugin } = require("./lib/middleware");
const { SensorProbe, startFromEnv } = require("./lib/probe");

// Inert unless SECFOO_SENSOR=1; safe to load via `node --require @rakfortltd/secfoo-sensor`.
startFromEnv();

module.exports = {
NodeHitCollector,
SensorProbe,
detectAuthState,
expressMiddleware,
fastifyPlugin,
getContext,
runWithJob,
runWithRequest,
sanitizeRouteTemplate,
startFromEnv,
};
86 changes: 86 additions & 0 deletions npm/secfoo-sensor/lib/coverage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"use strict";

const inspector = require("node:inspector");
const path = require("node:path");
const { fileURLToPath } = require("node:url");

/**
* Optional low-overhead V8 coverage tracker using `inspector`
* (`callCount: false, detailed: false`) to populate `app_functions` /
* `functions_executed` in #53 `session` events (#56).
*/
class V8CoverageTracker {
constructor(appRoot = process.cwd(), sensorDir = path.resolve(__dirname)) {
this.appRoot = path.resolve(appRoot);
this.sensorDir = path.resolve(sensorDir);
this._session = null;
this._enabled = false;
}

start() {
if (this._enabled) return;
try {
const s = new inspector.Session();
s.connect();
s.post("Profiler.enable");
s.post("Profiler.startPreciseCoverage", { callCount: false, detailed: false });
this._session = s;
this._enabled = true;
} catch {
this.stop();
}
}

_isAppUrl(rawUrl) {
if (!rawUrl || !rawUrl.startsWith("file://")) return false;
let filePath;
try {
filePath = path.resolve(fileURLToPath(rawUrl));
} catch {
return false;
}
if (filePath.includes(`${path.sep}node_modules${path.sep}`)) return false;
if (filePath.startsWith(this.sensorDir)) return false;
return filePath.startsWith(this.appRoot);
}

collect() {
if (!this._enabled || !this._session) return { app_functions: null, functions_executed: null };
let totalFuncs = 0;
let executedFuncs = 0;
try {
this._session.post("Profiler.takePreciseCoverage", (err, res) => {
if (err || !res || !Array.isArray(res.result)) return;
for (const script of res.result) {
if (!this._isAppUrl(script.url) || !Array.isArray(script.functions)) continue;
for (const fn of script.functions) {
totalFuncs += 1;
if (Array.isArray(fn.ranges) && fn.ranges.some((r) => r.count > 0)) {
executedFuncs += 1;
}
}
}
});
} catch {
return { app_functions: null, functions_executed: null };
}
if (totalFuncs === 0) return { app_functions: null, functions_executed: null };
return { app_functions: totalFuncs, functions_executed: executedFuncs };
}

stop() {
if (this._session) {
try {
this._session.post("Profiler.stopPreciseCoverage");
this._session.post("Profiler.disable");
this._session.disconnect();
} catch {
// Ignore teardown failures
}
}
this._session = null;
this._enabled = false;
}
}

module.exports = { V8CoverageTracker };
140 changes: 140 additions & 0 deletions npm/secfoo-sensor/lib/esm_loader.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const SELF_DIR = path.dirname(fileURLToPath(import.meta.url));
const PROBE_URL = pathToFileURL(path.join(SELF_DIR, "probe.js")).href;

let watchedPackages = null;

function loadWatchedPackages() {
if (process.env.SECFOO_SENSOR !== "1") return new Map();
if (watchedPackages !== null) return watchedPackages;
const map = new Map();
const wlPath = process.env.SECFOO_WATCHLIST;
if (!wlPath) {
watchedPackages = map;
return map;
}
try {
const doc = JSON.parse(fs.readFileSync(wlPath, "utf-8"));
for (const entry of doc.entries || []) {
if (entry.ecosystem && entry.ecosystem !== "npm") continue;
for (const sym of entry.symbols || []) {
const idx = String(sym).indexOf("#");
if (idx > 0) {
const pkg = sym.slice(0, idx);
const mem = sym.slice(idx + 1);
const set = map.get(pkg) || new Set();
set.add(mem);
map.set(pkg, set);
}
}
}
} catch {
// Watchlist unreadable; stay passive
}
watchedPackages = map;
return map;
}

function findMatchingPkg(urlStr) {
if (!urlStr.startsWith("file://")) return null;
const map = loadWatchedPackages();
if (map.size === 0) return null;
let fsPath;
try {
fsPath = fileURLToPath(urlStr);
} catch {
return null;
}
let dir = path.dirname(fsPath);
for (let i = 0; i < 6; i += 1) {
const pj = path.join(dir, "package.json");
if (fs.existsSync(pj)) {
try {
const meta = JSON.parse(fs.readFileSync(pj, "utf-8"));
if (meta && meta.name && map.has(meta.name)) return meta.name;
} catch {
break;
}
break;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
const stem = path.basename(fsPath, path.extname(fsPath));
if (map.has(stem)) return stem;
return null;
}

function extractNamedExports(src) {
const names = new Set();
let hasDefault = false;
// Strip single-line and block comments cleanly enough for ESM export declarations.
const clean = src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
for (const m of clean.matchAll(/^\s*export\s+(?:async\s+)?function\s*\*?\s+([A-Za-z_$][\w$]*)/gm)) {
names.add(m[1]);
}
for (const m of clean.matchAll(/^\s*export\s+class\s+([A-Za-z_$][\w$]*)/gm)) {
names.add(m[1]);
}
for (const m of clean.matchAll(/^\s*export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/gm)) {
names.add(m[1]);
}
for (const m of clean.matchAll(/^\s*export\s*\{([^}]+)\}/gm)) {
for (const part of m[1].split(",")) {
const asMatch = part.trim().split(/\s+as\s+/);
const exported = (asMatch[1] || asMatch[0] || "").trim();
if (exported === "default") hasDefault = true;
else if (exported) names.add(exported);
}
}
if (/^\s*export\s+default\b/m.test(clean)) hasDefault = true;
return { names: Array.from(names), hasDefault };
}

export async function load(url, context, nextLoad) {
if (process.env.SECFOO_SENSOR !== "1") return nextLoad(url, context);
const parsed = new URL(url);
if (parsed.searchParams.get("__secfoo_raw") === "1") {
parsed.searchParams.delete("__secfoo_raw");
return nextLoad(parsed.href, context);
}
const pkgName = findMatchingPkg(url);
if (!pkgName || url === PROBE_URL || url.startsWith(pathToFileURL(SELF_DIR).href)) {
return nextLoad(url, context);
}
const result = await nextLoad(url, context);
if (result.format !== "module" || !result.source) return result;
const srcText = typeof result.source === "string" ? result.source : Buffer.from(result.source).toString("utf-8");
const { names, hasDefault } = extractNamedExports(srcText);
if (names.length === 0 && !hasDefault) return result;

const rawUrl = new URL(url);
rawUrl.searchParams.set("__secfoo_raw", "1");

const lines = [
`import * as _raw from ${JSON.stringify(rawUrl.href)};`,
`import { createRequire } from "node:module";`,
`const _req = createRequire(import.meta.url);`,
`const { wrapNamespaceExport } = _req(${JSON.stringify(path.join(SELF_DIR, "probe.js"))});`,
];
for (const name of names) {
lines.push(
`export const ${name} = wrapNamespaceExport(${JSON.stringify(pkgName)}, ${JSON.stringify(name)}, _raw[${JSON.stringify(name)}], ${JSON.stringify(url)});`,
);
}
if (hasDefault) {
lines.push(
`const _def = wrapNamespaceExport(${JSON.stringify(pkgName)}, "default", _raw.default, ${JSON.stringify(url)});`,
`export default _def;`,
);
}
return {
format: "module",
shortCircuit: true,
source: lines.join("\n") + "\n",
};
}
150 changes: 150 additions & 0 deletions npm/secfoo-sensor/lib/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"use strict";

const Module = require("node:module");
const path = require("node:path");
const { packageNameFromRequest } = require("./inventory");

const wrappedTargets = new WeakSet();
const moduleCacheRecords = []; // { pkgName, resolvedFile, exportsObj, getContainer? }
let installed = false;
let originalLoad = null;

/**
* Wrap `fn` with a transparent Proxy so `this`, arguments, return values,
* thrown errors, `new` construction (`instanceof`), and static properties stay
* completely intact (#56).
*/
function createFunctionWrapper(fn, target, onHit) {
if (typeof fn !== "function" || wrappedTargets.has(fn)) return fn;
const wrapped = new Proxy(fn, {
apply(inner, thisArg, args) {
try {
onHit(target);
} catch {
// Observe-only, fail-open
}
return Reflect.apply(inner, thisArg, args);
},
construct(inner, args, newTarget) {
try {
onHit(target);
} catch {
// Observe-only, fail-open
}
return Reflect.construct(inner, args, newTarget);
},
});
wrappedTargets.add(fn);
wrappedTargets.add(wrapped);
return wrapped;
}

function applyTargetsToExports(exportsObj, targets, onHit) {
if (!exportsObj || (typeof exportsObj !== "object" && typeof exportsObj !== "function")) {
return exportsObj;
}
for (const target of targets) {
if (target.granularity !== "symbol" || !Array.isArray(target.memberPath) || target.memberPath.length === 0) {
continue;
}
let owner = exportsObj;
const parts = target.memberPath;
for (let i = 0; i < parts.length - 1; i += 1) {
const next = owner ? owner[parts[i]] : undefined;
if (!next || (typeof next !== "object" && typeof next !== "function")) {
owner = null;
break;
}
owner = next;
}
if (!owner) continue;
const leaf = parts[parts.length - 1];
let current;
try {
current = owner[leaf];
} catch {
continue;
}
if (typeof current !== "function" || wrappedTargets.has(current)) continue;
const desc = Object.getOwnPropertyDescriptor(owner, leaf);
if (desc && !desc.configurable && !desc.writable) continue;
const wrapped = createFunctionWrapper(current, target, onHit);
try {
owner[leaf] = wrapped;
} catch {
// Ignore frozen / non-writable exports
}
}
return exportsObj;
}

function resolveFileQuiet(request, parent) {
try {
return Module._resolveFilename(request, parent, false);
} catch {
return null;
}
}

function installCjsHook({ watchlist, inventory, onHit }) {
if (installed) return;
installed = true;
originalLoad = Module._load;

Module._load = function secfooWrappedLoad(request, parent, isMain) {
const loaded = originalLoad.apply(this, arguments);
try {
if (typeof request === "string" && !request.startsWith("node:") && !Module.builtinModules.includes(request)) {
const resolved = resolveFileQuiet(request, parent);
const inv = inventory.recordModule(resolved || request, request);
const pkgName = (inv && inv.package) || packageNameFromRequest(request);
const candidates = [];
if (pkgName) candidates.push(pkgName);
if (resolved) {
// Allow matching base filename when watched package name equals local sample file stem.
const stem = path.basename(resolved, path.extname(resolved));
if (stem && !candidates.includes(stem)) candidates.push(stem);
}
for (const cand of candidates) {
const targets = watchlist.targetsForPackage(cand);
if (targets.length > 0) {
applyTargetsToExports(loaded, targets, onHit);
}
}
if (loaded && (typeof loaded === "object" || typeof loaded === "function") && candidates.length > 0) {
moduleCacheRecords.push({ candidates, exportsObj: loaded });
}
}
} catch {
// Never interfere with app module loading
}
return loaded;
};
}

function applyWatchlistReload({ watchlist, onHit }) {
for (const rec of moduleCacheRecords) {
for (const cand of rec.candidates) {
const targets = watchlist.targetsForPackage(cand);
if (targets.length > 0) {
applyTargetsToExports(rec.exportsObj, targets, onHit);
}
}
}
}

function uninstallCjsHook() {
if (installed && originalLoad) {
Module._load = originalLoad;
originalLoad = null;
installed = false;
}
}

module.exports = {
applyTargetsToExports,
applyWatchlistReload,
createFunctionWrapper,
installCjsHook,
uninstallCjsHook,
};
Loading
Loading