This commit is contained in:
2025-02-27 00:38:36 +08:00
commit 5e29dd2a0d
42 changed files with 8517 additions and 0 deletions

14
app/.gitignore vendored Normal file
View File

@@ -0,0 +1,14 @@
node_modules
dist
app.config.json5
apps.config.json
deploy.tar.gz
cache-file
/apps
logs

2
app/.npmrc Normal file
View File

@@ -0,0 +1,2 @@
//npm.xiongxiao.me/:_authToken=${ME_NPM_TOKEN}
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

View File

@@ -0,0 +1,3 @@
{
port: 3000,
}

68
app/package.json Normal file
View File

@@ -0,0 +1,68 @@
{
"name": "demo-app",
"version": "0.0.1",
"description": "",
"main": "index.js",
"app": {
"key": "demo-app",
"entry": "dist/app.mjs",
"type": "system-app",
"files": [
"dist"
]
},
"scripts": {
"watch": "rollup -c rollup.config.mjs -w",
"dev": "cross-env NODE_ENV=development nodemon --delay 2.5 -e js,cjs,mjs --exec node dist/app.mjs",
"test": "tsx test/**/*.ts",
"dev:watch": "cross-env NODE_ENV=development concurrently -n \"Watch,Dev\" -c \"green,blue\" \"npm run watch\" \"sleep 1 && npm run dev\" ",
"clean": "rm -rf dist",
"prepub": "envision switch root",
"pub": "npm run build && envision pack -p -u"
},
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me>",
"license": "MIT",
"type": "module",
"types": "types/index.d.ts",
"files": [
"types",
"dist",
"src"
],
"dependencies": {
"@kevisual/router": "^0.0.7",
"dayjs": "^1.11.13",
"formidable": "^3.5.2",
"json5": "^2.2.3",
"lodash-es": "^4.17.21",
"nanoid": "^5.1.2"
},
"devDependencies": {
"@kevisual/types": "^0.0.6",
"@kevisual/use-config": "^1.0.8",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^28.0.2",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.0",
"@rollup/plugin-replace": "^6.0.2",
"@rollup/plugin-typescript": "^12.1.2",
"@types/crypto-js": "^4.2.2",
"@types/formidable": "^3.4.5",
"@types/lodash-es": "^4.17.12",
"@types/node": "^22.13.5",
"concurrently": "^9.1.2",
"cross-env": "^7.0.3",
"nodemon": "^3.1.9",
"pm2": "^5.4.3",
"rimraf": "^6.0.1",
"rollup": "^4.34.8",
"rollup-plugin-copy": "^3.5.0",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-esbuild": "^6.2.0",
"tape": "^5.9.0",
"tsx": "^4.19.3",
"typescript": "^5.7.3"
},
"pnpm": {}
}

3788
app/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

75
app/rollup.config.mjs Normal file
View File

@@ -0,0 +1,75 @@
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import path from 'path';
import esbuild from 'rollup-plugin-esbuild';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import pkgs from './package.json' with {type: 'json'};
const isDev = process.env.NODE_ENV === 'development';
const input = isDev ? './src/dev.ts' : './src/index.ts';
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
input,
output: {
dir: './dist',
entryFileNames: 'app.mjs',
chunkFileNames: '[name]-[hash].mjs',
format: 'esm',
},
plugins: [
replace({
preventAssignment: true, // 防止意外赋值
DEV_SERVER: JSON.stringify(isDev), // 替换 process.env.NODE_ENV
VERSION: JSON.stringify(pkgs.version),
}),
alias({
// only esbuild needs to be configured
entries: [
{ find: '@', replacement: path.resolve('src') }, // 配置 @ 为 src 目录
{ find: 'http', replacement: 'node:http' },
{ find: 'https', replacement: 'node:https' },
{ find: 'fs', replacement: 'node:fs' },
{ find: 'path', replacement: 'node:path' },
{ find: 'crypto', replacement: 'node:crypto' },
{ find: 'zlib', replacement: 'node:zlib' },
{ find: 'stream', replacement: 'node:stream' },
{ find: 'net', replacement: 'node:net' },
{ find: 'tty', replacement: 'node:tty' },
{ find: 'tls', replacement: 'node:tls' },
{ find: 'buffer', replacement: 'node:buffer' },
{ find: 'timers', replacement: 'node:timers' },
// { find: 'string_decoder', replacement: 'node:string_decoder' },
{ find: 'dns', replacement: 'node:dns' },
{ find: 'domain', replacement: 'node:domain' },
{ find: 'os', replacement: 'node:os' },
{ find: 'events', replacement: 'node:events' },
{ find: 'url', replacement: 'node:url' },
{ find: 'assert', replacement: 'node:assert' },
{ find: 'util', replacement: 'node:util' },
],
}),
resolve({
preferBuiltins: true, // 强制优先使用内置模块
}),
commonjs(),
esbuild({
target: 'node22', //
minify: false, // 启用代码压缩
tsconfig: 'tsconfig.json',
}),
json(),
],
external: [
/@kevisual\/router(\/.*)?/, //, // 路由
/@kevisual\/use-config(\/.*)?/, //
// 'sequelize', // 数据库 orm
// 'ioredis', // redis
// 'pg', // pg
],
};
export default config;

8
app/src/app.ts Normal file
View File

@@ -0,0 +1,8 @@
import { App } from '@kevisual/router';
import { useContextKey, useContext } from '@kevisual/use-config/context';
const init = () => {
return new App();
};
export const app = useContextKey('app', init);

16
app/src/demo-route.ts Normal file
View File

@@ -0,0 +1,16 @@
import { app } from './app.ts';
import { useConfig } from '@kevisual/use-config';
app
.route({
path: 'demo',
key: 'demo',
})
.define(async (ctx) => {
ctx.body = '123';
})
.addTo(app);
const config = useConfig();
console.log('run demo: http://localhost:' + config.port + '/api/router?path=demo&key=demo');

8
app/src/dev.ts Normal file
View File

@@ -0,0 +1,8 @@
import { useConfig } from '@kevisual/use-config';
import { app } from './index.ts';
const config = useConfig();
app.listen(config.port, () => {
console.log(`server is running at http://localhost:${config.port}`);
});

4
app/src/index.ts Normal file
View File

@@ -0,0 +1,4 @@
import { app } from './app.ts';
import './demo-route.ts';
export { app };

108
app/src/modules/wx.ts Normal file
View File

@@ -0,0 +1,108 @@
import { useConfig } from '@kevisual/use-config';
type WxConfig = {
appId: string;
appSecret: string;
};
const config = useConfig<{ wx: WxConfig }>();
export type WxTokenResponse = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
unionid: string;
};
export type WxToken = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
unionid: string;
};
export const fetchToken = async (code: string): Promise<WxToken> => {
const { appId, appSecret } = config.wx;
const wxUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`;
const res = await fetch(wxUrl);
const data = await res.json();
// console.log(data)
return data;
};
type UserInfo = {
openid: string;
nickname: string;
sex: number;
language: string;
province: string;
country: string;
headimgurl: string;
privilege: string[];
unionid: string;
};
/**
* 获取用户信息
* @param token
* @param openid
* @returns
*/
export const getUserInfo = async (token: string, openid: string): Promise<UserInfo> => {
const phoneUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openid}`;
const res = await fetch(phoneUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data = await res.json();
console.log(data);
return data;
};
// getUserInfo(token.access_token, token.openid)
type AuthRes = {
errcode: number;
errmsg: string;
};
/**
* errorcode 0: 正常
* @param token
* @param openid
* @returns
*/
export const getAuth = async (token: string, openid: string): Promise<AuthRes> => {
const authUrl = `https://api.weixin.qq.com/sns/auth?access_token=${token}&openid=${openid}`;
const res = await fetch(authUrl);
const data = await res.json();
// console.log(data)
return data;
};
// getAuth(token.access_token, token.openid)
type RefreshToken = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
};
export const refreshToken = async (refreshToken: string): Promise<RefreshToken> => {
const { appId } = config.wx;
const refreshUrl = `https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${appId}&grant_type=refresh_token&refresh_token=${refreshToken}`;
const res = await fetch(refreshUrl);
const data = await res.json();
console.log(data);
return data;
};
// refreshToken(token.refresh_token)

View File

@@ -0,0 +1,36 @@
import { SimpleRouter } from '@kevisual/router/simple'
import { IncomingMessage, OutgoingMessage } from 'http'
export const simple = new SimpleRouter()
// gmt_create=2025-02-12+14%3A57%3A18&charset=utf-8&gmt_payment=2025-02-12+14%3A57%3A26&notify_time=2025-02-12+14%3A57%3A27&subject=test&sign=IcqgLJn6HzUpd6so2lPCWm%2FOn%2BEHa8pPLrQVfiOszWB1BjR0MkPommx5esva6nIktJGFU3d2s8%2B1Q%2FfKH8dQcdkjVOI63szQCYnvhFP0AVUKfRTDj8xlRo5rjBg5I3b5aOAOgA4ZgVJanJAIq98qK5CVfKSwdTQTpKHXVpV15%2Fu1EJyE14Ptj3H83J6hpeK9EFWKbZsEkZIb2pR3calk3HIeLkPo4FvWo6q38gUjk3wrLBTh%2B0RhxItCKF3%2B58R9rmzk4WX4S71cBb6w9kBuyA29flawzb6d4qqHzRzqlhid7I0QFgRKRHTnyajlahFCe3kOeWgYfQRpKLabaznQqA%3D%3D&buyer_id=2088722055631717&invoice_amount=1.00&version=1.0&notify_id=2025021201222145726131710505339992&fund_bill_list=%5B%7B%22amount%22%3A%221.00%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&out_trade_no=1739343435250&total_amount=1.00&trade_status=TRADE_SUCCESS&trade_no=2025021222001431710505292165&auth_app_id=9021000143661256&receipt_amount=1.00&point_amount=0.00&buyer_pay_amount=1.00&app_id=9021000143661256&sign_type=RSA2&seller_id=2088721055593715
export const getJsonUseFrom = (str: string) => {
const urlParams = new URLSearchParams(str)
const entries = urlParams.entries()
const result = {}
for (const [key, value] of entries) {
result[key] = value
}
return result
}
export const parseBody = async (req: IncomingMessage, res: OutgoingMessage) => {
let body = ''
req.on('data', (chunk: any) => {
body += chunk
})
return new Promise<any>((resolve, reject) => {
req.on('end', () => {
const contentType = req.headers['content-type']
try {
if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
resolve(getJsonUseFrom(body))
} else if (contentType && contentType.includes('application/json')) {
resolve(JSON.parse(body))
} else {
reject(new Error('Unsupported content type'))
}
} catch (error) {
reject(error)
}
})
})
}

View File

@@ -0,0 +1,74 @@
import { WxServices } from '@/routes/wx/services.ts'
import { simple } from './simple.ts'
export const createLoginHtml = (wxService: WxServices) => {
const redirectUrl = wxService.isNew ? '/user/info' : '/'
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wx Login</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#loading {
font-size: 1.2rem;
color: #555;
}
</style>
</head>
<body>
<div>Login Success</div>
<div id="loading">Redirecting, please wait...</div>
<script>
(function() {
// Save the token to localStorage
localStorage.setItem('token', '${wxService.webToken}');
// Redirect after 2 seconds
setTimeout(() => {
window.location.href = '${redirectUrl}';
}, 2000);
})();
</script>
</body>
</html>
`
}
simple.get('/api/wx/login', async (req, res) => {
try {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
if (!code) {
res.end('code is required')
return
}
const wxService = new WxServices()
await wxService.login(code)
if (wxService.isNew) {
await wxService.getUserInfo()
}
res.setHeader('Content-Type', 'text/html')
res.end(createLoginHtml(wxService))
} catch (e) {
console.error(e)
res.end('error')
}
})
simple.get('/api/wx/on-ai/login', async (req, res) => {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
const onAIBaseUrl = 'https://note.on-ai.ai'
const newUrl = `${onAIBaseUrl}/api/wx/login?code=${code}&state=${state}`
res.setHeader('Content-Type', 'text/html')
res.end(`<script>window.location.href='${newUrl}'</script>`)
})

View File

@@ -0,0 +1,81 @@
import { WxTokenResponse, fetchToken, getUserInfo } from '@/modules/wx.ts';
import { useContextKey } from '@kevisual/use-config/context';
import { Buffer } from 'buffer';
const User = useContextKey<typeof User>('user');
export class WxServices {
token: WxTokenResponse;
// 创建一个webToken用户登录
webToken: string;
isNew: boolean;
user: User;
constructor() {
//
}
async login(code: string) {
const token = await fetchToken(code);
this.token = token;
if (!token.unionid) {
throw new Error('unionid is required');
}
const unionid = token.unionid;
let user = await User.findOne({ where: { username: unionid } });
if (!user) {
user = await User.createUser(unionid, unionid.slice(0, 8));
this.isNew = true;
}
const tokenInfo = await user.createToken();
this.webToken = tokenInfo.token;
this.user = user;
}
async checkHasUser() {}
async getUserInfo() {
const userInfo = await getUserInfo(this.token.access_token, this.token.openid);
const { nickname, headimgurl } = userInfo;
this.user.nickname = nickname;
try {
const downloadImgUrl = await this.downloadImg(headimgurl);
this.user.avatar = downloadImgUrl;
} catch (error) {
console.error('Error downloading or converting image:', error);
}
await this.user.save();
}
/**
* 转成base64
* @param url
*/
async downloadImg(url: string): Promise<string> {
try {
return await downloadImag(url);
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
}
}
// https://thirdwx.qlogo.cn/mmopen/vi_32/WvOPpbDwUKEVJvSst8Z91Y68m7CsBeecMqRGlqey5HejByePD89boYGaVCM8vESsYmokk1jABUDsK08IrfI6JEkibZkDIC2zsb96DGBTEF7E/132
export const downloadImag = async (url: string) => {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
const arrayBufferToBase64 = (buffer: ArrayBuffer): string => {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return Buffer.from(binary, 'binary').toString('base64');
};
const buffer = await res.arrayBuffer();
return `data:image/jpeg;base64,${arrayBufferToBase64(buffer)}`;
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
};

View File

@@ -0,0 +1,15 @@
const testLink = 'http://note.silkyai.cn/user/login?code=011YxX000j1OhT1J1B100Ko9W82YxX0h&state=162';
const link = new URL(testLink);
const code = link.searchParams.get('code');
const state = link.searchParams.get('state');
const token = {
access_token: '87_QgDzd_v3uB0a-DWsZ3Ns_yN6AEpW3A5yIoXYuukJJwFEWnPtqHASUPFRvr5yqZlY9qzIM8YuXzeOamtOxmHAyptaZAYvsqLvzOxEitLx9GM',
expires_in: 7200, // 2 hours
refresh_token: '87_nXrgfcZwiOJRC_u27O00qJDBdGWrTgalpLqG0t8ccSuuaFyDmN1j2maSwk3bB4SgNN8QCPoH55JGcG5f9a1daTIV3ulvqLKnNiBTg-aB4fo',
openid: 'oKiTl6uB0UWw85NPj6rqc-m8cUEo',
scope: 'snsapi_login',
unionid: 'oMFgb6ZoIr7psVy39pYOOybDcyoM',
};
// fetchToken(code)

33
app/tsconfig.json Normal file
View File

@@ -0,0 +1,33 @@
{
"compilerOptions": {
"module": "nodenext",
"target": "esnext",
"noImplicitAny": false,
"outDir": "./dist",
"sourceMap": false,
"allowJs": true,
"newLine": "LF",
"baseUrl": "./",
"typeRoots": [
"node_modules/@types",
"node_modules/@kevisual/types"
],
"declaration": true,
"noEmit": false,
"allowImportingTsExtensions": true,
"emitDeclarationOnly": true,
"moduleResolution": "NodeNext",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
],
"exclude": [],
}