refactor(security): unify hook rate-limit and hook module loading

This commit is contained in:
Peter Steinberger
2026-02-22 08:56:24 +01:00
parent 7cf280805c
commit 9f97555b5e
6 changed files with 152 additions and 82 deletions

View File

@@ -1,6 +1,6 @@
import path from "node:path";
import { pathToFileURL } from "node:url";
import { CONFIG_PATH, type HookMappingConfig, type HooksConfig } from "../config/config.js";
import { importFileModule, resolveFunctionModuleExport } from "../hooks/module-loader.js";
import type { HookMessageChannel } from "./hooks.js";
export type HookMappingResolved = {
@@ -330,19 +330,22 @@ async function loadTransform(transform: HookMappingTransformResolved): Promise<H
if (cached) {
return cached;
}
const url = pathToFileURL(transform.modulePath).href;
const mod = (await import(url)) as Record<string, unknown>;
const mod = await importFileModule({ modulePath: transform.modulePath });
const fn = resolveTransformFn(mod, transform.exportName);
transformCache.set(cacheKey, fn);
return fn;
}
function resolveTransformFn(mod: Record<string, unknown>, exportName?: string): HookTransformFn {
const candidate = exportName ? mod[exportName] : (mod.default ?? mod.transform);
if (typeof candidate !== "function") {
const candidate = resolveFunctionModuleExport<HookTransformFn>({
mod,
exportName,
fallbackExportNames: ["default", "transform"],
});
if (!candidate) {
throw new Error("hook transform module must export a function");
}
return candidate as HookTransformFn;
return candidate;
}
function resolvePath(baseDir: string, target: string): string {