Skip to content

Commit

Permalink
避免公开 根路径 / 导致被其它人滥用 (#38)
Browse files Browse the repository at this point in the history
* Create index.js

* Update README.md

* Update README.md

* Fix Bug: Add check for duplicate Random_Key

添加对Random_Key 是否重复的检查,防止恰好生成了相同的6位随机字符串,之前的 URL 就被替换的情况发生
完善对URL合法性的检查

* fix: small error (#1)

* Update index.js (#4)

if 嵌套的等效写法

* Update 404 page

* Add CORS support (#6)

* Add CORS support #6

* Update index.js (#9)

* Update README.md

* Update README.md

* Update README.md

* Add API document (#13)

* Add API document

This is the API document for Url-Shorten-Worker.

* Update README.md

* Update README.md

* Add custom theme, hide Referer header and cors setting #16

Add a config which allow you to customize some behaviour of the Url-Shorten-Worker. You can set custom theme by modify the config.theme. There are two theme you can choose default and urlcool. Set config.theme to "theme/urlcool" to use the urlcool theme. Leave the config.theme to be blank to use the default theme. Also you can use config to control the CORS behaviour and HTTP Referer header.

* Update README.md

* Update index.js

Fix some issues

* Update API.md (#27)

* Update README.md

* Create API_zh-hans.md

* Update API.md

* Check URL before submit if exist #20

* Added params variable and added params to redirect location if available. (#30)

Co-authored-by: David <davvido51gmail.com>

* 修改为自用

直接访问域名返回404。在KV中设置一个entry,保存秘密path,只有访问这个path才显示使用页面。

* Update README.md

* Update index.js

* Update README.md

* 不检查url格式

* Revert "不检查url格式"

This reverts commit 60f2d7e.

* Update index.js

* main.js 搬回github

* custom_link:true

* Update README.md

* Update index.js

* Update index.js

* Update index.js

* Update index.js

* Update index.js

* Update README.md

* Update README.md

* Update README.md

* localStorage

* Update README.md

* cmd-del

* 1

* Update README.md

* zelikk 302

* Update README.md

* Update README.md

* Update README.md

* Update README.md

---------

Co-authored-by: xyTom <[email protected]>
Co-authored-by: 0xflotus <[email protected]>
Co-authored-by: 管子工具箱 <[email protected]>
Co-authored-by: Cetacea <[email protected]>
Co-authored-by: cloudtom <[email protected]>
Co-authored-by: Casperteam <[email protected]>
Co-authored-by: dras51 <[email protected]>
  • Loading branch information
8 people authored Aug 12, 2023
1 parent dbe604a commit 9cf4d92
Show file tree
Hide file tree
Showing 4 changed files with 347 additions and 2 deletions.
43 changes: 43 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
@@ -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

40 changes: 40 additions & 0 deletions API_zh-hans.md
Original file line number Diff line number Diff line change
@@ -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
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
234 changes: 234 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -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 = `<!DOCTYPE html>
<html>
<body>
<h1>404 Not Found.</h1>
<p>The url you visit is not found.</p>
<p> <a href="https://github.com/crazypeace/Url-Shorten-Worker/" target="_self">Fork me on GitHub</a> </p>
</body>
</html>`

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))
})

0 comments on commit 9cf4d92

Please sign in to comment.