diff --git a/API.md b/API.md new file mode 100644 index 00000000..1f53eecf --- /dev/null +++ b/API.md @@ -0,0 +1,43 @@ + + +# API documentation + +[简体中文](API_zh-hans.md) + +Short links can be generated in a programmable way by calling the API interface + +### API call address + +Self-deployed CloudFlare Worker address, for example: https://url.dem0.workers.dev or a self-bound domain name + +### Calling method: HTTP POST Request format: JSON +Example: +```` +{ + "url": "https://example.com" +} +```` + +### Request parameters: + +|Parameter name|Type|Description|Required|Example| +| :----:| :----: | :----: | :----: | :----: | +| url | string | URL (must include http:// or https://) | must | https://example.com| + +### Example response (JSON): + +```` +{ + "status": 200, + "key": "/demo" +} +```` + +### Response parameters: +|Parameter name|Type|Description|Example| +| :----:| :----: | :----: | :----: | +|status|int| Status code: 200 is a successful call |200| +|key|string| Short link suffix: you need to add the domain name prefix|/xxxxxx| + +Note: The interface will only return the key value corresponding to the short link. In actual use, the corresponding domain name prefix needs to be added. For example, if the key parameter returned in the example is "/demo", we need to add "https://url.dem0.workers.dev" as a prefix, it can be used by completing it as a complete url, namely: https://url.dem0.workers.dev/demo + diff --git a/API_zh-hans.md b/API_zh-hans.md new file mode 100644 index 00000000..8986743a --- /dev/null +++ b/API_zh-hans.md @@ -0,0 +1,40 @@ +# API接口文档 + +[English](API.md) + +可以通过调用API接口,使用可编程的方式生成短链接 + +### 接口调用地址 + +自行部署的CloudFlare Worker地址,例如:https://url.dem0.workers.dev 或是自行绑定的域名 + +### 调用方式:HTTP POST 请求格式: JSON +示例: +``` +{ + "url": "https://example.com" +} +``` + +### 请求参数: + +| 参数名 | 类型 | 说明 |是否必须|示例| +| :----:| :----: | :----: | :----: | :----: | +| url | string | 网址(需包括http://或https://) |必须|https://example.com| + +### 响应示例 (JSON): + +``` +{ + "status": 200, + "key": "/demo" +} +``` + +### 响应参数: +| 参数名 | 类型 | 说明 |示例| +| :----:| :----: | :----: | :----: | +|status|int| 状态码:200为调用成功|200| +|key|string| 短链接后缀:需要自行添加域名前缀|/xxxxxx| + +注:接口只会返回短链接对应的key值,实际使用中需要添加对应的域名前缀,如:示例中返回的key参数是 "/demo" ,则我们需要添加 "https://url.dem0.workers.dev" 作为前缀,将其补全成完整的url即可使用,即:https://url.dem0.workers.dev/demo diff --git a/README.md b/README.md index 34d3d835..c99d6fe2 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,30 @@ -# Url-Shorten-Worker -A URL Shortener created using Cloudflare worker +# 演示 +https://1way.eu.org/zEKz23 + +# 完整的部署教程 +https://zelikk.blogspot.com/2022/07/url-shorten-worker-hide-tutorial.html + +# 在原版基础上的修改说明 +直接访问域名返回404。在KV中设置一个entry,保存秘密path,只有访问这个path才显示使用页面。 + +https://zelikk.blogspot.com/2022/07/url-shorten-worker-hide-tutorial.html + +支持自定义短链 + +https://zelikk.blogspot.com/2022/07/url-shorten-worker-custom.html + +API 不公开服务 + +https://zelikk.blogspot.com/2022/07/url-shorten-worker-api-password.html + +页面缓存设置过的短链 + +https://zelikk.blogspot.com/2022/08/url-shorten-worker-localstorage.html + +长链接文本框预搜索localStorage + +https://zelikk.blogspot.com/2022/08/url-shorten-worker-bootstrap-list-group-oninput.html + +增加删除某条短链的按钮 + +https://zelikk.blogspot.com/2022/08/url-shorten-worker-delete-kv-localstorage.html diff --git a/index.js b/index.js new file mode 100644 index 00000000..96ce506e --- /dev/null +++ b/index.js @@ -0,0 +1,234 @@ +const config = { +no_ref: "off", //Control the HTTP referrer header, if you want to create an anonymous link that will hide the HTTP Referer header, please set to "on" . +theme:"",//Homepage theme, use the empty value for default theme. To use urlcool theme, please fill with "theme/urlcool" . +cors: "on",//Allow Cross-origin resource sharing for API requests. +unique_link:false,//If it is true, the same long url will be shorten into the same short url +custom_link:true,//Allow users to customize the short url. +} + +const html404 = ` + + +

404 Not Found.

+

The url you visit is not found.

+

Fork me on GitHub

+ +` + +let response_header={ + "content-type": "text/html;charset=UTF-8", +} + +if (config.cors=="on"){ + response_header={ + "content-type": "text/html;charset=UTF-8", + "Access-Control-Allow-Origin":"*", + "Access-Control-Allow-Methods": "POST", + } +} + +async function randomString(len) { + len = len || 6; + let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ + let maxPos = $chars.length; + let result = ''; + for (i = 0; i < len; i++) { + result += $chars.charAt(Math.floor(Math.random() * maxPos)); + } + return result; +} + +async function sha512(url){ + url = new TextEncoder().encode(url) + + const url_digest = await crypto.subtle.digest( + { + name: "SHA-512", + }, + url, // The data you want to hash as an ArrayBuffer + ) + const hashArray = Array.from(new Uint8Array(url_digest)); // convert buffer to byte array + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + //console.log(hashHex) + return hashHex +} +async function checkURL(URL){ + let str=URL; + let Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/; + let objExp=new RegExp(Expression); + if(objExp.test(str)==true){ + if (str[0] == 'h') + return true; + else + return false; + }else{ + return false; + } +} +async function save_url(URL){ + let random_key=await randomString() + let is_exist=await LINKS.get(random_key) + console.log(is_exist) + if (is_exist == null) + return await LINKS.put(random_key, URL),random_key + else + save_url(URL) +} +async function is_url_exist(url_sha512){ + let is_exist = await LINKS.get(url_sha512) + console.log(is_exist) + if (is_exist == null) { + return false + }else{ + return is_exist + } +} +async function handleRequest(request) { + console.log(request) + + // 查KV中的password对应的值 + const password_value = await LINKS.get("password"); + + if (request.method === "POST") { + let req=await request.json() + let req_cmd=req["cmd"] + if (req_cmd == "add") { + let req_url=req["url"] + let req_keyPhrase=req["keyPhrase"] + let req_password=req["password"] + + console.log(req_url) + console.log(req_keyPhrase) + console.log(req_password) + if(!await checkURL(req_url)){ + return new Response(`{"status":500,"key": "", "error":": Error: Url illegal."}`, { + headers: response_header, + }) + } + + if (req_password != password_value) { + return new Response(`{"status":500,"key": "", "error":": Error: Invalid password."}`, { + headers: response_header, + }) + } + + let stat,random_key + if (config.custom_link && (req_keyPhrase != "")){ + let is_exist=await LINKS.get(req_keyPhrase) + if (is_exist != null) { + return new Response(`{"status":500,"key": "", "error":": Error: Custom shortURL existed."}`, { + headers: response_header, + }) + }else{ + random_key = req_keyPhrase + stat, await LINKS.put(req_keyPhrase, req_url) + } + } else if (config.unique_link){ + let url_sha512 = await sha512(req_url) + let url_key = await is_url_exist(url_sha512) + if(url_key){ + random_key = url_key + }else{ + stat,random_key=await save_url(req_url) + if (typeof(stat) == "undefined"){ + console.log(await LINKS.put(url_sha512,random_key)) + } + } + }else{ + stat,random_key=await save_url(req_url) + } + console.log(stat) + if (typeof(stat) == "undefined"){ + return new Response(`{"status":200, "key":"`+random_key+`", "error": ""}`, { + headers: response_header, + }) + }else{ + return new Response(`{"status":500, "key": "", "error":": Error:Reach the KV write limitation."}`, { + headers: response_header, + }) + } + } else if (req_cmd == "del") { + let req_keyPhrase=req["keyPhrase"] + let req_password=req["password"] + + if (req_password != password_value) { + return new Response(`{"status":500,"key": "", "error":": Error: Invalid password."}`, { + headers: response_header, + }) + } + + await LINKS.delete(req_keyPhrase) + return new Response(`{"status":200}`, { + headers: response_header, + }) + } + + }else if(request.method === "OPTIONS"){ + return new Response(``, { + headers: response_header, + }) + } + + const requestURL = new URL(request.url) + const path = requestURL.pathname.split("/")[1] + const params = requestURL.search; + + console.log(path) + if(!path){ + return Response.redirect("https://zelikk.blogspot.com/search/label/Url-Shorten-Worker", 302) + /* new Response(html404, { + headers: { + "content-type": "text/html;charset=UTF-8", + }, + status: 404 + }) */ + } + + // 如果path符合password 显示应用界面 + if (path==password_value){ + let index= await fetch("https://crazypeace.github.io/Url-Shorten-Worker/"+config.theme+"/index.html") + index=await index.text() + index=index.replace(/__PASSWORD__/gm, password_value) + return new Response(index, { + headers: { + "content-type": "text/html;charset=UTF-8", + }, + }) + } + + const value = await LINKS.get(path); + let location ; + + if(params) { + location = value + params + } else { + location = value + } + console.log(value) + + if (location) { + if (config.no_ref=="on"){ + let no_ref= await fetch("https://crazypeace.github.io/Url-Shorten-Worker/no-ref.html") + no_ref=await no_ref.text() + no_ref=no_ref.replace(/{Replace}/gm, location) + return new Response(no_ref, { + headers: { + "content-type": "text/html;charset=UTF-8", + }, + }) + }else{ + return Response.redirect(location, 302) + } + } + // If request not in kv, return 404 + return new Response(html404, { + headers: { + "content-type": "text/html;charset=UTF-8", + }, + status: 404 + }) +} + +addEventListener("fetch", async event => { + event.respondWith(handleRequest(event.request)) +})