first commit

This commit is contained in:
我若为王
2024-08-30 08:43:19 +08:00
commit d0765eb7ff
11 changed files with 3763 additions and 0 deletions

12
.editorconfig Normal file
View File

@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space

172
.gitignore vendored Normal file
View File

@ -0,0 +1,172 @@
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
# wrangler project
.dev.vars
.wrangler/

6
.prettierrc Normal file
View File

@ -0,0 +1,6 @@
{
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": true
}

2933
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "alipan-tv-token",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev",
"test": "vitest"
},
"dependencies": {
"crypto-js": "^4.2.0",
"js-md5": "^0.8.3"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "^0.4.5",
"wrangler": "^3.60.3",
"vitest": "1.5.0"
}
}

65
src/decode.js Normal file
View File

@ -0,0 +1,65 @@
const md5 = require('js-md5');
const crypto = require("crypto-js");
const decrypt = function (ciphertext, iv, t) {
try {
const key = generateKey(t);
const decrypted = crypto.AES.decrypt(ciphertext, crypto.enc.Utf8.parse(key), {
iv: crypto.enc.Hex.parse(iv),
mode: crypto.mode.CBC,
padding: crypto.pad.Pkcs7
});
var dec = crypto.enc.Utf8.stringify(decrypted).toString();
console.log(dec);
return dec;
} catch (error) {
console.error("Decryption failed", error);
throw error;
}
};
function h(charArray, modifier) {
const uniqueChars = Array.from(new Set(charArray));
const numericModifier = Number(modifier.toString().slice(7));
const transformedString = uniqueChars.map(char => {
const charCode = char.charCodeAt(0);
let newCharCode = Math.abs(charCode - (numericModifier % 127) - 1);
if (newCharCode < 33) {
newCharCode += 33;
}
return String.fromCharCode(newCharCode);
}).join("");
return transformedString;
}
function getParams(t) {
return {
'akv': '2.8.1496', // apk_version_name 版本号
'apv': '1.3.6', // 内部版本号
'b': 'XiaoMi', // 手机品牌
'd': 'e87a4d5f4f28d7a17d73c524eaa8ac37', // 设备id 可随机生成
'm': '23046RP50C', // 手机型号
'mac': '', // mac地址
'n': '23046RP50C', // 手机型号
't': t, // 时间戳
'wifiMac': '020000000000', // wifiMac地址
};
}
const generateKey = function (t) {
const params = getParams();
const sortedKeys = Object.keys(params).sort();
let concatenatedParams = "";
sortedKeys.forEach(key => {
if (key !== "t") {
concatenatedParams += params[key];
}
});
const keyArray = concatenatedParams.split("");
const hashedKey = h(keyArray, t);
console.log(md5(hashedKey));
return md5(hashedKey);
};
module.exports = { decrypt,getParams };

126
src/index.html Normal file
View File

@ -0,0 +1,126 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>二维码登录</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
h1 {
color: #333;
}
#qrCodeContainer {
margin: 20px 0;
}
#tokens {
display: none;
margin-top: 20px;
}
.token-container {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.token-container label {
margin-right: 10px;
font-weight: bold;
}
.token-container input {
width: 300px;
padding: 5px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.token-container button {
padding: 5px 10px;
border: none;
background-color: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
}
.token-container button:hover {
background-color: #0056b3;
}
</style>
<script>
async function generateQR() {
const response = await fetch("/generate_qr", {
method: "POST",
});
const data = await response.json();
const qrCode = document.getElementById("qrCode");
qrCode.src = data.qr_link;
qrCode.style.display = "block";
checkStatus(data.sid);
}
async function checkStatus(sid) {
const interval = setInterval(async () => {
const response = await fetch(`/check_status/${sid}`);
const data = await response.json();
if (data.status === "LoginSuccess") {
clearInterval(interval);
document.querySelector("h1").innerText = "获取成功";
document.getElementById("accessToken").value = data.access_token;
document.getElementById("refreshToken").value = data.refresh_token;
document.getElementById("tokens").style.display = "block";
document.getElementById("copyAccessTokenButton").style.display =
"inline-block";
document.getElementById("copyRefreshTokenButton").style.display =
"inline-block";
document.getElementById("qrCodeContainer").style.display = "none";
} else {
if (data.status === "ScanSuccess") {
document.querySelector("h1").innerText =
"扫码成功,等待手机端授权";
}
if (data.status === "LoginFailed") {
document.querySelector("h1").innerText =
"登录失败,请刷新页面重试";
clearInterval(interval);
alert("登录失败,请刷新页面重试");
location.reload();
}
}
}, 2000);
}
function copyToClipboard(elementId) {
const copyText = document.getElementById(elementId);
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
alert("已复制: " + copyText.value);
}
</script>
</head>
<body onload="generateQR()">
<h1>扫描二维码登录</h1>
<div id="qrCodeContainer">
<img id="qrCode" alt="二维码加载中..." />
</div>
<div id="tokens">
<div class="token-container">
<label for="accessToken">访问令牌:</label>
<input type="text" id="accessToken" readonly />
<button id="copyAccessTokenButton" onclick="copyToClipboard('accessToken')">复制</button>
</div>
<div class="token-container">
<label for="refreshToken">刷新令牌:</label>
<input type="text" id="refreshToken" readonly />
<button id="copyRefreshTokenButton" onclick="copyToClipboard('refreshToken')">复制</button>
</div>
</div>
</body>
</html>

290
src/index.js Normal file
View File

@ -0,0 +1,290 @@
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
import { decrypt, getParams } from './decode.js';
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>二维码登录</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
h1 {
color: #333;
}
#qrCodeContainer {
margin: 20px 0;
}
#tokens {
display: none;
margin-top: 20px;
}
.token-container {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.token-container label {
margin-right: 10px;
font-weight: bold;
}
.token-container input {
width: 300px;
padding: 5px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.token-container button {
padding: 5px 10px;
border: none;
background-color: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
}
.token-container button:hover {
background-color: #0056b3;
}
</style>
<script>
async function generateQR() {
const response = await fetch("/generate_qr", {
method: "POST",
});
const data = await response.json();
const qrCode = document.getElementById("qrCode");
qrCode.src = data.qr_link;
qrCode.style.display = "block";
checkStatus(data.sid);
}
async function checkStatus(sid) {
const interval = setInterval(async () => {
const response = await fetch("/check_status/" + sid);
const data = await response.json();
if (data.status === "LoginSuccess") {
clearInterval(interval);
document.querySelector("h1").innerText = "获取成功";
document.getElementById("accessToken").value = data.access_token;
document.getElementById("refreshToken").value = data.refresh_token;
document.getElementById("tokens").style.display = "block";
document.getElementById("copyAccessTokenButton").style.display =
"inline-block";
document.getElementById("copyRefreshTokenButton").style.display =
"inline-block";
document.getElementById("qrCodeContainer").style.display = "none";
} else {
if (data.status === "ScanSuccess") {
document.querySelector("h1").innerText =
"扫码成功,等待手机端授权";
}
if (data.status === "LoginFailed") {
document.querySelector("h1").innerText =
"登录失败,请刷新页面重试";
clearInterval(interval);
alert("登录失败,请刷新页面重试");
location.reload();
}
}
}, 2000);
}
function copyToClipboard(elementId) {
const copyText = document.getElementById(elementId);
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
alert("已复制: " + copyText.value);
}
</script>
</head>
<body onload="generateQR()">
<h1>扫描二维码登录</h1>
<div id="qrCodeContainer">
<img id="qrCode" alt="二维码加载中..." />
</div>
<div id="tokens">
<div class="token-container">
<label for="accessToken">访问令牌:</label>
<input type="text" id="accessToken" readonly />
<button id="copyAccessTokenButton" onclick="copyToClipboard('accessToken')">复制</button>
</div>
<div class="token-container">
<label for="refreshToken">刷新令牌:</label>
<input type="text" id="refreshToken" readonly />
<button id="copyRefreshTokenButton" onclick="copyToClipboard('refreshToken')">复制</button>
</div>
</div>
</body>
</html>`
async function handleRequest(request) {
const url = new URL(request.url);
if (request.method === 'POST' && url.pathname === '/generate_qr') {
return await generateQR(request);
} else if (request.method === 'GET' && url.pathname.startsWith('/check_status/')) {
const sid = url.pathname.split('/').pop();
return await checkStatus(sid);
} else if (request.method === 'POST' && url.pathname === '/refresh') {
return await refreshToken(request);
} else {
return new Response(html, {
headers: {
"content-type": "text/html;charset=UTF-8",
},
});
}
}
async function generateQR(request) {
try {
const response = await fetch('http://api.extscreen.com/aliyundrive/qrcode', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
scopes: ["user:base", "file:all:read", "file:all:write"].join(','),
width: 500,
height: 500,
})
});
const data = await gatherResponse(response);
return new Response(JSON.stringify({ qr_link: data.data.qrCodeUrl, sid: data.data.sid }), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
async function checkStatus(sid) {
try {
const response = await fetch(`https://openapi.alipan.com/oauth/qrcode/${sid}/status`);
const statusData = await response.json();
const status = statusData.status;
if (status === 'LoginSuccess') {
try {
console.log(statusData);
const authCode = statusData.authCode;
const t = Math.floor(Date.now() / 1000);
const sendData = { ...getParams(t), code: authCode, "Content-Type": "application/json"};
console.log(sendData);
const headers = Object.fromEntries(Object.entries(sendData).map(([k, v]) => [k, String(v)]));
const tokenResponse = await fetch('http://api.extscreen.com/aliyundrive/v3/token', {
method: 'POST',
headers: headers,
body: JSON.stringify(sendData)
});
const tokenData = await gatherResponse(tokenResponse);
console.log(tokenData);
const jsonp = tokenData.data;
console.log(jsonp);
const plainData = decrypt(jsonp.ciphertext, jsonp.iv, t);
console.log(plainData);
const tokenInfo = JSON.parse(plainData);
const refreshToken = tokenInfo.refresh_token;
const accessToken = tokenInfo.access_token;
return new Response(JSON.stringify({ status: 'LoginSuccess', refresh_token: refreshToken, access_token: accessToken }), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error(error);
return new Response(JSON.stringify({ status: 'LoginFailed' }), {
headers: { 'Content-Type': 'application/json' }
});
}
} else {
return new Response(JSON.stringify({ status: statusData.status }), {
headers: { 'Content-Type': 'application/json' }
});
}
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
async function readRequestBody(request) {
const contentType = request.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return await request.json();
} else {
return null;
}
}
/**
* gatherResponse processes the response from the origin
* @param {Response} response the response from the origin
*/
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return await response.json();
}
return await response.text();
}
async function refreshToken(request) {
try {
const { refresh_token } = await readRequestBody(request);
console.log(refresh_token);
const t = Math.floor(Date.now() / 1000);
const sendData = { ...getParams(t), refresh_token: refresh_token,"Content-Type": "application/json" };
const headers = Object.fromEntries(Object.entries(sendData).map(([k, v]) => [k, String(v)]));
const response = await fetch('http://api.extscreen.com/aliyundrive/v3/token', {
method: 'POST',
headers: headers,
body: JSON.stringify(sendData)
});
const tokenData = await gatherResponse(response);
console.log(tokenData);
const jsonp = tokenData.data;
console.log(jsonp);
const plainData = decrypt(jsonp.ciphertext, jsonp.iv, t);
console.log(plainData);
const tokenInfo = JSON.parse(plainData);
console.log(tokenInfo);
return new Response(JSON.stringify({
token_type: 'Bearer',
access_token: tokenInfo.access_token,
refresh_token: tokenInfo.refresh_token,
expires_in: tokenInfo.expires_in
}), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error(error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
export default {
async fetch(request, env, ctx) {
return handleRequest(request);
},
};

20
test/index.spec.js Normal file
View File

@ -0,0 +1,20 @@
import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloudflare:test';
import { describe, it, expect } from 'vitest';
import worker from '../src';
describe('Hello World worker', () => {
it('responds with Hello World! (unit style)', async () => {
const request = new Request('http://example.com');
// Create an empty context to pass to `worker.fetch()`.
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
await waitOnExecutionContext(ctx);
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
});
it('responds with Hello World! (integration style)', async () => {
const response = await SELF.fetch(request, env, ctx);
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
});
});

11
vitest.config.js Normal file
View File

@ -0,0 +1,11 @@
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
export default defineWorkersConfig({
test: {
poolOptions: {
workers: {
wrangler: { configPath: './wrangler.toml' },
},
},
},
});

108
wrangler.toml Normal file
View File

@ -0,0 +1,108 @@
#:schema node_modules/wrangler/config-schema.json
name = "alipan-tv-token"
main = "src/index.js"
compatibility_date = "2023-05-18"
compatibility_flags = ["nodejs_compat"]
# Automatically place your workloads in an optimal location to minimize latency.
# If you are running back-end logic in a Worker, running it closer to your back-end infrastructure
# rather than the end user may result in better performance.
# Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
# [placement]
# mode = "smart"
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
# Docs:
# - https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
# Note: Use secrets to store sensitive data.
# - https://developers.cloudflare.com/workers/configuration/secrets/
# [vars]
# MY_VARIABLE = "production_value"
# Bind the Workers AI model catalog. Run machine learning models, powered by serverless GPUs, on Cloudflares global network
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#workers-ai
# [ai]
# binding = "AI"
# Bind an Analytics Engine dataset. Use Analytics Engine to write analytics within your Pages Function.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-engine-datasets
# [[analytics_engine_datasets]]
# binding = "MY_DATASET"
# Bind a headless browser instance running on Cloudflare's global network.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#browser-rendering
# [browser]
# binding = "MY_BROWSER"
# Bind a D1 database. D1 is Cloudflares native serverless SQL database.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases
# [[d1_databases]]
# binding = "MY_DB"
# database_name = "my-database"
# database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Bind a dispatch namespace. Use Workers for Platforms to deploy serverless functions programmatically on behalf of your customers.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#dispatch-namespace-bindings-workers-for-platforms
# [[dispatch_namespaces]]
# binding = "MY_DISPATCHER"
# namespace = "my-namespace"
# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model.
# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects
# [[durable_objects.bindings]]
# name = "MY_DURABLE_OBJECT"
# class_name = "MyDurableObject"
# Durable Object migrations.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#migrations
# [[migrations]]
# tag = "v1"
# new_classes = ["MyDurableObject"]
# Bind a Hyperdrive configuration. Use to accelerate access to your existing databases from Cloudflare Workers.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#hyperdrive
# [[hyperdrive]]
# binding = "MY_HYPERDRIVE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Bind an mTLS certificate. Use to present a client certificate when communicating with another service.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#mtls-certificates
# [[mtls_certificates]]
# binding = "MY_CERTIFICATE"
# certificate_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#queues
# [[queues.producers]]
# binding = "MY_QUEUE"
# queue = "my-queue"
# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#queues
# [[queues.consumers]]
# queue = "my-queue"
# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets
# [[r2_buckets]]
# binding = "MY_BUCKET"
# bucket_name = "my-bucket"
# Bind another Worker service. Use this binding to call another Worker without network overhead.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
# [[services]]
# binding = "MY_SERVICE"
# service = "my-service"
# Bind a Vectorize index. Use to store and query vector embeddings for semantic search, classification and other vector search use-cases.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#vectorize-indexes
# [[vectorize]]
# binding = "MY_INDEX"
# index_name = "my-index"