本帖最后由 jarmoku 于 2022-5-22 12:07 编辑
代码如下,具有防跨站和网址加密功能。你问我用这个有什么意义,主要是可以套国内的CDN呀! 具体使用使用方式参阅我的个人博客:https://www.430074.xyz/posts/workers-jsdeliver.html
- // 允许的 CORS 来源
- const ALLOWED_REFERER = [
- /^https?://localhost(:d*)?/.*$/,
- /^https?://([w-]+.)*w3schools.com(:d*)?/.*$/
- ];
- // 是否允许所有无 Referer 请求
- const ALLOW_NO_ORIGIN = true;
- //输入你的密码,密码加在path后面做SHA-1运算
- const MYSECRET = "123456";
-
-
- function validateReferer(req) {
- const referer = req.headers.get(‘Referer’);
- if (referer) {
- for (const el of ALLOWED_REFERER) {
- if (el.exec(referer)) {
- return true;
- }
- }
- return false;
- }
- return ALLOW_NO_ORIGIN; // 是否拒绝所有无 Referer 请求
- }
-
-
- async function handle(request) {
- let url = new URL(request.url);
- const acceptType = request.headers.get(‘Accept’);
- const hash_request = url.pathname.split("/")[1];
- const path_real = url.pathname.substring(hash_request.length + 1, url.pathname.length);
- url.hostname = "cdn.jsdelivr.net";
- url.pathname = path_real;
-
- if (!(await validatePath(hash_request, path_real))) {
- return new Response(‘Error Hash’, {
- status: 403
- });
- }
-
- if (!(validateReferer(request))) {
- return new Response(‘Blocked Host’, {
- status: 403
- });
- }
-
- return await fetch(url);
- }
-
- async function validatePath(hash_request, path_real) {
- const message = new TextEncoder().encode(path_real + MYSECRET);
- const myDigest = await crypto.subtle.digest(‘SHA-1’, message);
- const hashArray = Array.from(new Uint8Array(myDigest));
- const hashHex = hashArray.map(b => b.toString(16).padStart(2, ‘0’)).join(”);
- return (hashHex == hash_request);
- }
-
-
- addEventListener(‘fetch’, event => {
- event.respondWith(handle(event.request));
- })
复制代码
|