---
title: Node脚本生命周期钩子治理(preinstall-postinstall-安全门禁)最佳实践
keywords:
- preinstall
- postinstall
- 生命周期钩子
- 安全门禁
- 脚本校验
description: 通过对包生命周期钩子脚本进行白名单与特征校验,阻断高风险安装脚本,降低供应链攻击面。
categories:
- 文章资讯
- 技术教程
---
核心要点
- 钩子白名单与禁用列表;默认禁止
preinstall/postinstall,仅允许受控prepare。 - 检测危险特征:网络下载、代码注入、进程执行与敏感环境访问。
- 审计输出命中规则与证据,支持例外审批与到期。
实现示例
type Scripts = { [k: string]: string }
const allowHooks = new Set<string>(['prepare'])
const denyHooks = new Set<string>(['preinstall','postinstall'])
function suspicious(cmd: string): boolean {
const r = [
/(curl|wget)\s+https?:\/\//i,
/powershell\s+(Invoke-WebRequest|iwr)\s+/i,
/node\s+-e\s+/i,
/eval\(/i,
/Function\(/i,
/child_process/i,
/require\(['"]child_process['"]\)/i,
/process\.env\.[A-Z_]+/,
]
return r.some(rx => rx.test(cmd))
}
function validateScripts(scripts: Scripts, exceptions: Map<string, number>, now: number): { ok: boolean; errors: string[] } {
const errors: string[] = []
for (const [k, v] of Object.entries(scripts)) {
const key = `hook:${k}`
const until = exceptions.get(key) || 0
if (denyHooks.has(k) && until < now) errors.push(`denied:${k}`)
if (!allowHooks.has(k) && !denyHooks.has(k) && suspicious(v) && until < now) errors.push(`suspicious:${k}`)
}
return { ok: errors.length === 0, errors }
}
审计与CI门禁
- 构建前解析
scripts字段;命中禁用或可疑规则即阻断并输出详情。 - 对必要钩子启用例外审批与到期时间;产线默认拒绝未审批项。

发表评论 取消回复