miniai/test_path.ts

45 lines
1.9 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 路径æ<E2809E>ƒé™<C3A9>å<EFBFBD>•å…ƒæµè¯•:白å<C2BD><C3A5>å<EFBFBD>• + é»å<E28098><C3A5>å<EFBFBD>•(é»å<E28098><C3A5>å<EFBFBD>•优先)
import { resolve, normalize } from "path";
function isWithin(base: string, target: string): boolean {
const b = normalize(base).replace(/\\/g, "/").replace(/\/+$/, "");
const t = normalize(target).replace(/\\/g, "/").replace(/\/+$/, "");
return t === b || t.startsWith(b + "/");
}
function makeAllowed(whitelist: string[], blacklist: string[], workspace: string) {
return (p: string): boolean => {
const abs = resolve(workspace, normalize(p));
for (const b of blacklist) if (isWithin(b, abs)) return false;
const allowed = [...whitelist, workspace];
for (const w of allowed) if (isWithin(w, abs)) return true;
return false;
};
}
const WS = "D:\\workbench\\miniai";
let pass = 0, fail = 0;
function check(name: string, got: boolean, want: boolean) {
const ok = got === want;
console.log(`${ok ? "âœ? : "â<EFBFBD>?} ${name}: got=${got} want=${want}`);
ok ? pass++ : fail++;
}
// 默认白å<C2BD><C3A5>å<EFBFBD>?= [d:\],无é»å<E28098><C3A5>å<EFBFBD>?const a1 = makeAllowed(["d:\\"], [], WS);
check("白å<C2BD><C3A5>å<EFBFBD>?d:\\ æ ¹ç®å½•å…<C3A5>è®?, a1("d:\\"), true);
check("ç½å<EFBFBD><EFBFBD>å<EFBFBD>?d:\\ å­<EFBFBD>ç®å½å<EFBFBD>è®?, a1("d:\\foo\\bar"), true);
check(<>žç™½å<C2BD><C3A5>å<EFBFBD>• c:\\ æç»<C3A7>", a1("c:\\windows"), false);
check("工作区ç¸å¯¹è·¯å¾„å…<C3A5>è®?, a1("data.xlsx"), true);
check("ç¸å¯¹è·¯å¾èŠæ<EFBFBD>ƒæç»<EFBFBD>", a1("../../etc/passwd"), false);
// é»å<E28098><C3A5>å<EFBFBD>•优å…?const a2 = makeAllowed(["d:\\"], ["c:\\"], WS);
check("é»å<EFBFBD><EFBFBD>å<EFBFBD>?c:\\ æç»<EFBFBD>", a2("c:\\windows"), false);
check("é»å<EFBFBD><EFBFBD>å<EFBFBD>ä¸<EFBFBD>å½±å<EFBFBD>ç½å<EFBFBD><EFBFBD>å<EFBFBD>?d:\\", a2("d:\\foo"), true);
// é»å<E28098><C3A5>å<EFBFBD>•å½ä¸­å…¶ä¸çš„å­<C3A5>ç®å½•,å<C592>³ä½¿çˆ¶ç®å½•在白å<C2BD><C3A5>å<EFBFBD>?const a3 = makeAllowed(["d:\\"], ["d:\\secret"], WS);
check("é»å<EFBFBD><EFBFBD>å<EFBFBD>å­<EFBFBD>ç®å½æç»<EFBFBD>(优åˆäºŽç½å<EFBFBD><EFBFBD>å<EFBFBD>)", a3("d:\\secret\\x"), false);
check("ç½å<EFBFBD><EFBFBD>å<EFBFBD>åä½éƒ¨åˆä»<EFBFBD>å<EFBFBD>许", a3("d:\\pub"), true);
console.log(`\n结果: ${pass} 通过, ${fail} 失败`);
if (fail > 0) process.exit(1);