核心要点启用 `always-auth` 与严格来源白名单;屏蔽明文令牌与弱权限。作用域到注册表映射一致性校验;仅允许只读拉取权限。实现示例type Npmrc = { registry?: string; alwaysAuth?: boolean; token?: string; scopeRegistry?: { [scope: string]: string } }
const allowRegistries = new Set<string>(['https://registry.npmjs.org','https://registry.example.com'])
function validRegistry(u?: string): boolean {
if (!u) return false
try {
const url = new URL(u)
return url.protocol === 'https:' && allowRegistries.has(url.origin)
} catch {
return false
}
}
function tokenSafe(t?: string): boolean {
if (!t) return false
return !/[\s"']/.test(t)
}
function policy(n: Npmrc): { ok: boolean; errors: string[] } {
const errors: string[] = []
if (!validRegistry(n.registry)) errors.push('registry')
if (n.alwaysAuth !== true) errors.push('always-auth')
if (!tokenSafe(n.token)) errors.push('token')
if (n.scopeRegistry) {
for (const [scope, reg] of Object.entries(n.scopeRegistry)) {
if (!validRegistry(reg)) errors.push(`scope:${scope}`)
}
}
return { ok: errors.length === 0, errors }
}
审计与运行治理配置变更需审批与审计;生产环境仅加载受控机器配置。禁止明文令牌输出与日志;令牌权限仅限 `read:packages`。

发表评论 取消回复