背景与价值依赖混淆与包名劫持利用名称相似与源混乱。通过Scoped Registry与命名规范可阻断恶意包引入。统一规范Scoped强制:`@org/*` 仅允许企业私有注册表。名称规范:禁止相似或含有混淆前后缀的包名。.npmrc策略:强制作用域至私有源,禁止默认公共源覆盖。核心实现作用域与注册表映射校验type Npmrc = { registry?: string; scopes: Record<string, string> }
function validScopeName(s: string): boolean { return /^@[a-z0-9-]+$/.test(s) }
function scopeMapped(npmrc: Npmrc, scope: string, expected: string): boolean {
if (!validScopeName(scope)) return false
const url = npmrc.scopes[scope]
return url === expected
}
function pkgNameAllowed(name: string): boolean {
if (!/^[a-z0-9-]{1,64}$/.test(name)) return false
if (/^.*(0|o|O){2}.*$/.test(name)) return false
if (/^.*(l|1){2}.*$/.test(name)) return false
return true
}
依赖项来源校验type Dep = { name: string; version: string; resolved: string }
type DepSet = Dep[]
function originAllowed(url: string, allow: Set<string>): boolean { try { const u = new URL(url); return allow.has(u.origin) } catch { return false } }
function validateDeps(deps: DepSet, allow: Set<string>): Dep[] {
const bad: Dep[] = []
for (const d of deps) {
if (!pkgNameAllowed(d.name)) bad.push(d)
if (!originAllowed(d.resolved, allow)) bad.push(d)
}
return bad
}
落地建议在 `.npmrc` 中为企业作用域配置私有注册表并强制覆盖,公共源仅用于非企业作用域。在依赖审计中校验包名规范与来源域白名单,拒绝相似混淆命名。与锁文件完整性与签名门禁协同,确保端到端可信供应链。验证清单`.npmrc` 是否为 `@org` 作用域配置私有注册表。包名是否命中规范并无混淆字符组合。依赖 `resolved` 域是否命中白名单。

发表评论 取消回复