任务
逐条解析依赖:缺失 integrity 记为一条违规,resolved 使用 http 协议再记一条,按依赖名与规则排序输出。
契约
- 输入:JSON 对象:{ lockfile: [{ name, resolved, integrity? }], policy: { requireIntegrity, allowHttp } }
- 输出:JSON 字符串数组:违规描述,已排序
样例
- 输入
{"lockfile":[{"name":"left-pad","resolved":"https://registry.example.com/left-pad.tgz","integrity":"sha512-abc"}],"policy":{"requireIntegrity":true,"allowHttp":false}}-> 期望[]。单个 HTTPS 固定地址且带 integrity 哈希的依赖是合规的。 - 输入
{"lockfile":[{"name":"ok","resolved":"https://registry.example.com/ok.tgz","integrity":"sha512-abc"},{"name":"loose","resolved":"http://mirror.example.com/loose.tgz"},{"name":"nohash","resolved":"https://registry.example.com/nohash.tgz"}],"policy":{"requireIntegrity":true,"allowHttp":false}}-> 期望["loose:insecure-protocol","loose:missing-integrity","nohash:missing-integrity"]。明文镜像同时违反两条规则(不安全协议与缺少哈希),而 nohash 只违反完整性规则。
参考实现
function solve({ lockfile, policy }) {
const violations = [];
for (const entry of lockfile) {
if (policy.requireIntegrity && !entry.integrity) violations.push(entry.name + ':missing-integrity');
if (policy.allowHttp === false && String(entry.resolved).startsWith('http://')) {
violations.push(entry.name + ':insecure-protocol');
}
}
return violations.sort();
}
为什么有效
lockfile 是评审内容与最终产物之间的契约。未固定地址与缺失完整性,会让被攻破的仓库下发与被评审版本不同的字节。
每条依赖的每条规则各报一次,并以依赖名作键,让失败直接指向具体包。