Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: cmliu/CF-Workers-TEXT2KV
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: main
Choose a base ref
...
head repository: Icemans007/CF-Workers-TEXT2KV
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: main
Choose a head ref
Can’t automatically merge. Don’t worry, you can still create the pull request.
  • 14 commits
  • 1 file changed
  • 2 contributors

Commits on Dec 11, 2024

  1. Update _worker.js

    优化功能,使数据不再受url 65条数据限制
    Icemans007 authored Dec 11, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    c78d46b View commit details
  2. Update _worker.js

    优化
    Icemans007 authored Dec 11, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    4d3c100 View commit details

Commits on Dec 16, 2024

  1. 加入对post文件上传格式的支持

    John Feng committed Dec 16, 2024
    Copy the full SHA
    013854f View commit details
  2. bug fixed

    John Feng committed Dec 16, 2024
    Copy the full SHA
    11c828f View commit details
  3. test

    John Feng committed Dec 16, 2024
    Copy the full SHA
    e12e1fe View commit details
  4. test

    John Feng committed Dec 16, 2024
    Copy the full SHA
    f02d7f4 View commit details
  5. test

    John Feng committed Dec 16, 2024
    Copy the full SHA
    ef35aa2 View commit details
  6. test

    John Feng committed Dec 16, 2024
    Copy the full SHA
    964fcad View commit details

Commits on Dec 17, 2024

  1. test

    John Feng committed Dec 17, 2024
    Copy the full SHA
    5bf0eb8 View commit details
  2. test

    John Feng committed Dec 17, 2024
    Copy the full SHA
    5a5412d View commit details
  3. bug fix

    John Feng committed Dec 17, 2024
    Copy the full SHA
    37e540f View commit details
  4. 优化

    John Feng committed Dec 17, 2024
    Copy the full SHA
    9f55816 View commit details
  5. fix bug

    John Feng committed Dec 17, 2024
    Copy the full SHA
    39a8a88 View commit details
  6. 修复bug

    John Feng committed Dec 17, 2024
    Copy the full SHA
    3410a3c View commit details
Showing with 177 additions and 60 deletions.
  1. +177 −60 _worker.js
237 changes: 177 additions & 60 deletions _worker.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
let mytoken = 'passwd';
let mytoken = '';

export default {
async fetch(request, env) {
@@ -10,25 +10,24 @@ export default {
}

const url = new URL(request.url);
const token = url.pathname === `/${mytoken}` ? mytoken : (url.searchParams.get('token') || "null");
const token = url.searchParams.get('token');

if (token !== mytoken) {
if (!mytoken || token !== mytoken) {
return createResponse('token 有误', 403);
}

let fileName = url.pathname.startsWith('/') ? url.pathname.substring(1) : url.pathname;
fileName = fileName.toLowerCase(); // 将文件名转换为小写

switch (fileName) {
case "config":
case mytoken:
switch (url.pathname) {
case "/config":
case "/":
return createResponse(configHTML(url.hostname, token), 200, { 'Content-Type': 'text/html; charset=UTF-8' });
case "config/update.bat":
case "/config/update.bat":
return createResponse(generateBatScript(url.hostname, token), 200, { "Content-Disposition": 'attachment; filename=update.bat', "Content-Type": "text/plain; charset=utf-8" });
case "config/update.sh":
case "/config/update.sh":
return createResponse(generateShScript(url.hostname, token), 200, { "Content-Disposition": 'attachment; filename=update.sh', "Content-Type": "text/plain; charset=utf-8" });
default:
return await handleFileOperation(env.KV, fileName, url, token);
let fileName = url.pathname.substring(1).toLowerCase(); // 将文件名转换为小写

return await handleFileOperation(env.KV, fileName, url, request, token);
}
} catch (error) {
console.error("Error:", error);
@@ -41,24 +40,48 @@ export default {
* 处理文件操作
* @param {Object} KV - KV 命名空间实例
* @param {String} fileName - 文件名
* @param {Object} url - URL 实例
* @param {Object} request - request - The incoming request object
* @param {String} token - 认证 token
*/
async function handleFileOperation(KV, fileName, url, token) {
const text = url.searchParams.get('text') || null;
const b64 = url.searchParams.get('b64') || null;
async function handleFileOperation(KV, fileName, url, request, token) {

const text = url.searchParams.get('text') ?? null;
const b64 = url.searchParams.get('b64') ?? null;
const contentType = request.headers.get("content-type");

// 如果没有传递 text 或 b64 参数,尝试从 KV 存储中获取文件内容
if (!text && !b64) {
// 如果没有传递数据过来,尝试从 KV 存储中获取文件内容
if (text === null && b64 === null && !contentType?.includes("form")) {
const value = await KV.get(fileName, { cacheTtl: 60 });
if (value === null) {
return createResponse('File not found', 404);
}
return createResponse(value);
}

let content = "";

if (contentType?.includes("form")) {
try {
// 从请求中获取表单数据
const formData = await request.formData();
const file = formData.get('file');

if (file) {
// 读取文件内容
const arrayBuffer = await file.arrayBuffer();
content = base64Decode(replaceSpacesWithPlus(new TextDecoder().decode(arrayBuffer)));
} else {
throw new Error('File not found in the request');
}
} catch (error) {
throw new Error(`Error processing the request: ${error.message}`);
}
}
// 如果传递了 text 或 b64 参数,将内容写入 KV 存储
let content = text || base64Decode(replaceSpacesWithPlus(b64));
else {
content = text ?? base64Decode(replaceSpacesWithPlus(b64));
}

await KV.put(fileName, content);
const verifiedContent = await KV.get(fileName, { cacheTtl: 60 });

@@ -116,27 +139,68 @@ function replaceSpacesWithPlus(str) {
* @param {String} token - 认证 token
*/
function generateBatScript(domain, token) {
return [
'@echo off',
'chcp 65001',
'setlocal',
'',
`set "DOMAIN=${domain}"`,
`set "TOKEN=${token}"`,
'',
'set "FILENAME=%~nx1"',
'',
'for /f "delims=" %%i in (\'powershell -command "$content = ((Get-Content -Path \'%cd%/%FILENAME%\' -Encoding UTF8) | Select-Object -First 65) -join [Environment]::NewLine; [convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($content))"\') do set "BASE64_TEXT=%%i"',
'',
'set "URL=https://%DOMAIN%/%FILENAME%?token=%TOKEN%^&b64=%BASE64_TEXT%"',
'',
'start %URL%',
'endlocal',
'',
'echo 更新数据完成,倒数5秒后自动关闭窗口...',
'timeout /t 5 >nul',
'exit'
].join('\r\n');
return `@echo off
setlocal enabledelayedexpansion
:: Set variables
set DOMAIN=${domain}
set TOKEN=${token}
set FILEPATH=%~1
set FILENAME=%~nx1
:: Check if the file exists
if not exist "%FILEPATH%" (
echo File "%FILEPATH%" does not exist.
pause
exit /b 1
)
:: Construct the request URL
set URL=https://%DOMAIN%/%FILENAME%?token=%TOKEN%
:: Upload the file and handle errors with detailed logging
powershell -Command ^
"$path = '%FILEPATH%';" ^
"$url = '%URL%';" ^
"$fileContent = Get-Content -Path $path -Encoding Byte -Raw; $boundary = [System.Guid]::NewGuid().ToString();" ^
"$contentType = 'multipart/form-data; boundary=' + $boundary;" ^
"$isUtf8 = $true;" ^
"try {" ^
" [System.Text.Encoding]::UTF8.GetString($fileContent) | Out-Null;" ^
"} catch {" ^
" $isUtf8 = $false;" ^
"}" ^
"if ($isUtf8) {" ^
" Write-Host 'The file is already UTF-8 encoded';" ^
"} else {" ^
" Write-Host 'Converting file encoding to UTF-8';" ^
" $fileContent = [System.Text.Encoding]::UTF8.GetBytes([System.IO.File]::ReadAllText($path, [System.Text.Encoding]::Default));" ^
"}" ^
"$body = " ^
" '--' + $boundary + [System.Environment]::NewLine +" ^
" 'Content-Disposition: form-data; name=\"file\"; filename=\"%FILENAME%\"' + [System.Environment]::NewLine +" ^
" 'Content-Type: application/octet-stream' + [System.Environment]::NewLine + [System.Environment]::NewLine +" ^
" [Convert]::ToBase64String($fileContent) + [System.Environment]::NewLine +" ^
" '--' + $boundary + '--' + [System.Environment]::NewLine;" ^
"try {" ^
" $response = Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType $contentType -ErrorAction Stop;" ^
" Write-Host 'Upload is successful and will be closed after 3 seconds ...';" ^
" Start-Sleep -Seconds 3;" ^
"} catch {" ^
" Write-Host 'Upload failed: ' + $_.Exception.Message;" ^
" pause;" ^
" exit 1;" ^
"}"
:: Check upload result and pause if there was an error
if %errorlevel% neq 0 (
echo Upload failed, please check the error message above.
pause
exit /b 1
)
endlocal
`;
}

/**
@@ -146,18 +210,70 @@ function generateBatScript(domain, token) {
*/
function generateShScript(domain, token) {
return `#!/bin/bash
export LANG=zh_CN.UTF-8
# Set variables
DOMAIN="${domain}"
TOKEN="${token}"
if [ -n "$1" ]; then
FILENAME="$1"
FILEPATH="$1"
FILENAME=$(basename "$FILEPATH")
# Check if the file exists
if [ ! -f "$FILEPATH" ]; then
echo "File \"$FILEPATH\" does not exist."
read -p "Press any key to continue..."
exit 1
fi
# Construct the request URL
URL="https://$DOMAIN/$FILENAME?token=$TOKEN"
# Generate a UUID
if command -v openssl &> /dev/null; then
BOUNDARY=$(openssl rand -hex 16)
else
echo "无文件名"
exit 1
echo "openssl not found, please install openssl"
exit 1
fi
# Check if the file is UTF-8 encoded and convert if necessary
if [[ $(file -bi "$FILEPATH" | sed -n 's/.*charset=//p') == "utf-8" ]]; then
echo "The file is already UTF-8 encoded"
FILE_CONTENT=$(< "$FILEPATH")
else
echo "Converting file encoding to UTF-8"
FILE_CONTENT=$(iconv -f "$(file -bi "$FILEPATH" | sed -n 's/.*charset=//p')" -t UTF-8 "$FILEPATH")
fi
# Encode file content to base64
ENCODED_CONTENT=$(echo -n "$FILE_CONTENT" | base64 -w 0)
# Prepare the body directly in curl command
RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X POST "$URL" \
-H "Content-Type: multipart/form-data; boundary=$BOUNDARY" \
--data-binary @- << EOF
--$BOUNDARY
Content-Disposition: form-data; name="file"; filename="$FILENAME"
Content-Type: application/octet-stream
$ENCODED_CONTENT
--$BOUNDARY--
EOF
)
# Extract HTTP code and response body
HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE" | awk -F: '{print $2}')
RESPONSE_BODY=$(echo "$RESPONSE" | sed -e 's/HTTP_CODE:.*//g')
if [ "$HTTP_CODE" -ne 200 ]; then
echo "Upload failed. HTTP Code: $HTTP_CODE"
echo "Response Body:"
echo "$RESPONSE_BODY"
read -p "Press any key to continue..."
exit 1
else
echo "Upload is successful! and will be closed after 3 seconds ..."
sleep 3
fi
BASE64_TEXT=$(head -n 65 $FILENAME | base64 -w 0)
curl -k "https://${domain}/${FILENAME}?token=${token}&b64=${BASE64_TEXT}"
echo "更新数据完成"
`;
}

@@ -265,26 +381,28 @@ function configHTML(domain, token) {
</script>
</head>
<body>
<h1>TEXT2KV 配置信息</h1>
<h1>TEXT2KV 配置信息</h1>
<div class="container">
<p>
<strong>服务域名:</strong> ${domain}<br>
<strong>TOKEN:</strong> ${token}<br>
</p>
<p class="tips"><strong>注意!</strong> 因URL长度内容所限,脚本更新方式一次最多更新65行内容</p>
<div class="flex-row">
<h2>Windows 脚本:</h2>
<button class="download-button" onclick="window.open('https://${domain}/config/update.bat?token=${token}&t=' + Date.now(), '_blank')">点击下载</button>
</div>
<p class="tips"><strong>注意!</strong> 请保管自己的TOKEN,泄漏了域名和TOKEN,他人可以直接获取您的数据。</p>
<div class="flex-row">
<h2>Windows 脚本:</h2>
<button class="download-button" onclick="window.open('https://${domain}/config/update.bat?token=${token}&t=' + Date.now(), '_blank')">点击下载</button>
</div>
<pre><code>update.bat ip.txt</code></pre>
<h2>Linux 脚本:</h2>
<div class="flex-row">
<h2>Linux 脚本:</h2>
<button class="download-button" onclick="navigator.clipboard.writeText(document.getElementsByClassName('language-bash')[0].textContent).then(() => alert('脚本已复制到剪贴板'))">点击复制</button>
</div>
<pre><code class="language-bash">curl "https://${domain}/config/update.sh?token=${token}&t=$(date +%s%N)" -o update.sh && chmod +x update.sh</code></pre>
<h2>在线文档查询:</h2>
<div class="input-button-container">
<input type="text" id="keyword" placeholder="请输入要查询的文档">
<button onclick="viewDocument()">查看文档内容</button>
<button onclick="copyDocumentURL()">复制文档地址</button>
<input type="text" id="keyword" placeholder="请输入要查询的文档">
<button onclick="viewDocument()">查看文档内容</button>
<button onclick="copyDocumentURL()">复制文档地址</button>
</div>
</div>
<script>
@@ -309,4 +427,3 @@ function configHTML(domain, token) {
</html>
`;
}