Skip to content

Commit

Permalink
fix: kritor 鉴权
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Jul 8, 2024
1 parent 6bb38cf commit ad4e8e8
Show file tree
Hide file tree
Showing 57 changed files with 1,508 additions and 215 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ test/data/
/**/kritor/src/generated/
/pnpm-lock.yaml
/test/zhin.db/
/test/zhin.config.yml
/test/config/zhin.config.yml
4 changes: 3 additions & 1 deletion core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@
"directory": "core"
},
"dependencies": {
"axios": "^1.6.1",
"jiti": "^1.21.0",
"log4js": "^6.9.1",
"tsconfig-paths": "^4.2.0",
"yaml": "^2.4.5"
},
"peerDependencies": {
"@zhinjs/shared": "workspace:^"
},
"devDependencies": {
"dtsc": "^2.3.0"
}
Expand Down
3 changes: 1 addition & 2 deletions core/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { EventEmitter } from 'events';
import { Message } from './message';
import path from 'path';
import { getLogger, Logger } from 'log4js';
import { Dict } from './types';
import { Dict } from '@zhinjs/shared';
import { WORK_DIR } from './constans';
import { Prompt } from './prompt';
import { Schema } from './schema';

export type AdapterBot<A extends Adapter> = A extends Adapter<infer B> ? B : unknown;
Expand Down
20 changes: 12 additions & 8 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { Logger, getLogger } from 'log4js';
import { Middleware } from './middleware';
import { Plugin, PluginMap } from './plugin';
import { Bot, LogLevel } from './types';
import { loadModule, remove } from './utils';
import { APP_KEY, REQUIRED_KEY, WORK_DIR } from './constans';
import { loadModule } from './utils';
import { remove } from '@zhinjs/shared';
import { APP_KEY, CONFIG_DIR, REQUIRED_KEY, WORK_DIR } from './constans';
import path from 'path';
import { Adapter, AdapterBot, AdapterReceive } from './adapter';
import { Message } from './message';
import process from 'process';
import { Config } from './config';
import * as fs from 'fs';

export function defineConfig(config: Partial<App.Config>): Partial<App.Config>;
export function defineConfig(
Expand All @@ -28,11 +30,12 @@ export class App extends EventEmitter {
middlewares: Middleware[] = [];
plugins: PluginMap = new PluginMap();
renders: Message.Render[] = [];
constructor(key?: string) {
constructor() {
super();
this.handleMessage = this.handleMessage.bind(this);
if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR);
this.on('message', this.handleMessage);
this.config = new Config(process.env.ZHIN_CONFIG || 'zhin.config', App.defaultConfig);
this.config = new Config<App.Config>(process.env.ZHIN_CONFIG || 'zhin.config', App.defaultConfig);
this.logger.level = this.config.log_level;
return new Proxy(this, {
get(target: App, key) {
Expand All @@ -41,8 +44,9 @@ export class App extends EventEmitter {
},
});
}
registerRender(render: Message.Render) {
this.renders.push(render);
registerRender(render: Message.Render, insertBefore?: boolean) {
if (insertBefore) this.renders.unshift(render);
else this.renders.push(render);
return () => remove(this.renders, render);
}
getAdapterSchema(name: string) {
Expand Down Expand Up @@ -400,8 +404,8 @@ export interface App extends App.Services {
removeAllListeners<S extends string | symbol>(event: S & Exclude<string | symbol, keyof App.EventMap>): this;
}

export function createApp(key?: string) {
return new App(key);
export function createApp() {
return new App();
}

export namespace App {
Expand Down
5 changes: 3 additions & 2 deletions core/src/command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { deepClone, findLastIndex, isEmpty, trimQuote } from './utils';
import { Bot, Dict } from './types';
import { findLastIndex, trimQuote } from './utils';
import { deepClone, Dict, isEmpty } from '@zhinjs/shared';
import { Bot } from './types';
import { Adapter } from './adapter';
import { Message, segment } from './message';
import { Prompt } from './prompt';
Expand Down
18 changes: 9 additions & 9 deletions core/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'yaml';
import { WORK_DIR } from './constans';
import { CONFIG_DIR } from './constans';
import { App } from './app';
export class Config {
export class Config<T extends object = object> {
public static exts: string[] = ['.json', '.yaml', '.yml'];
filename: string = '';
#type: Config.Type = Config.Type.YAML;
private _data: App.Config;
private _data: T;
get data() {
return this._data;
}
constructor(name: string, defaultValue?: App.Config) {
constructor(name: string, defaultValue?: T) {
try {
this.filename = this.#resolveByName(name);
} catch (e) {
if (!defaultValue) throw e;
const ext = path.extname(name);
if (!Config.exts.includes(ext)) this.filename = path.join(WORK_DIR, `${name}${this.#resolveExt()}`);
if (!Config.exts.includes(ext)) this.filename = path.join(CONFIG_DIR, `${name}${this.#resolveExt()}`);
this.#saveConfig(defaultValue);
}
this._data = this.#loadConfig();
return new Proxy<App.Config>(this._data, {
return new Proxy<T>(this._data, {
get: (target, p, receiver) => {
if (Reflect.has(this, p)) return Reflect.get(this, p, receiver);
return this.#proxied(target, p, receiver);
Expand All @@ -38,7 +38,7 @@ export class Config {
this.#saveConfig();
return result;
},
}) as unknown as Config;
}) as unknown as Config<T>;
}
#resolveByName(name: string): string {
if (!Config.exts.includes(path.extname(name))) {
Expand All @@ -49,7 +49,7 @@ export class Config {
}
throw new Error(`未找到配置文件${name}`);
}
name = path.resolve(WORK_DIR, name);
name = path.resolve(CONFIG_DIR, name);
if (!fs.existsSync(name)) {
throw new Error(`未找到配置文件${name}`);
}
Expand Down Expand Up @@ -78,7 +78,7 @@ export class Config {
throw new Error(`不支持的配置文件类型${this.#type}`);
}
}
#saveConfig(data: App.Config = this._data) {
#saveConfig(data: T = this._data) {
switch (this.#type) {
case Config.Type.JSON:
return fs.writeFileSync(this.filename, JSON.stringify(data, null, 2));
Expand Down
2 changes: 2 additions & 0 deletions core/src/constans.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as os from 'os';
import process from 'process';
import path from 'path';

export const APP_KEY = Symbol('AppKey');
export const REQUIRED_KEY = Symbol('RequiredServices');
Expand All @@ -10,3 +11,4 @@ export const isMobile = !isLinux && !isMac && !isWin;
export const HOME_DIR = os.homedir();
export const TEMP_DIR = os.tmpdir();
export const WORK_DIR = process.env.PWD || process.cwd();
export const CONFIG_DIR = path.join(WORK_DIR, 'config');
1 change: 0 additions & 1 deletion core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from './adapter';
export * from './message';
export { default as axios } from 'axios';
export * as yaml from 'yaml';
export * from './types';
export * from './utils';
Expand Down
7 changes: 4 additions & 3 deletions core/src/message.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Bot, Dict } from './types';
import { Bot } from './types';
import { Dict } from '@zhinjs/shared';
import { Prompt } from './prompt';
import { Adapter, AdapterReceive } from './adapter';
export interface MessageBase {
Expand Down Expand Up @@ -130,8 +131,8 @@ segment.image = (file: string, type = 'png') => `<image file='${encodeURICompone
segment.video = (file: string, type = 'mp4') => `<video file='${encodeURIComponent(file)}' type='${type}'>`;
segment.audio = (file: string, type = 'mp3') => `<audio file='${encodeURIComponent(file)}' type='${type}'>`;
segment.at = user_id => `<at user_id='${encodeURIComponent(user_id)}'/>`;
type MessageSender = {
export interface MessageSender {
user_id?: string | number;
user_name?: string;
permissions?: string[];
};
}
13 changes: 9 additions & 4 deletions core/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { ArgsType, Command, defineCommand } from './command';
import { EventEmitter } from 'events';
import { Middleware } from './middleware';
import { getCallerStack, remove } from './utils';
import { getCallerStack } from './utils';
import { App } from './app';
import { APP_KEY, REQUIRED_KEY, WORK_DIR } from './constans';
import { Dict } from './types';
import { Dict, remove } from '@zhinjs/shared';
import path from 'path';
import { Adapter } from './adapter';
import * as fs from 'fs';
import { getLogger, Logger } from 'log4js';
import { Schema } from './schema';
import { Config } from './config';

export interface Plugin extends Plugin.Options {}

Expand All @@ -31,7 +33,6 @@ export class Plugin extends EventEmitter {
commands: Map<string, Command> = new Map<string, Command>();
middlewares: Middleware[] = [];
[APP_KEY]: App | null = null;

get app() {
return this[APP_KEY];
}
Expand All @@ -43,7 +44,11 @@ export class Plugin extends EventEmitter {
set display_name(name: string) {
this.name = name;
}

useConfig<T>(configPath: string, schema: Schema<T>): T | undefined {
if (schema.meta.type !== 'object') throw new Error(`config schema root must be type object`);
const config = new Config<T & object>(configPath, schema.meta.default as any);
return schema(config.data);
}
get statusText() {
return Plugin.StatusText[this.status];
}
Expand Down
3 changes: 2 additions & 1 deletion core/src/prompt.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Dict } from '@zhinjs/shared';
import { Adapter } from './adapter';
import { Middleware } from './middleware';
import { Bot, Dict } from './types';
import { Bot } from './types';
import { Message } from './message';
import { Schema } from './schema';

Expand Down
10 changes: 2 additions & 8 deletions core/src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isEmpty } from '@zhinjs/shared';

export class Schema<S = any, T = S> {
public [Symbol.toStringTag] = 'Schema';
constructor(
Expand Down Expand Up @@ -153,14 +155,6 @@ export namespace Schema {
}
: unknown;
export function checkDefault<T>(schema: Schema, value: T, fallback: T = value) {
const isEmpty = (value: string | object | T) => {
if (typeof value === 'undefined') return true;
if (typeof value === 'string' && value === '') return true;
if (typeof value === 'object' && value === null) return true;
if (Array.isArray(value) && value.length === 0) return true;
if (value instanceof Date && isNaN(value.getTime())) return true;
return value && typeof value === 'object' && Reflect.ownKeys(value).length === 0;
};
if (isEmpty(value)) {
value = schema.meta.default || fallback;
}
Expand Down
8 changes: 0 additions & 8 deletions core/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
import { Adapter, AdapterBot } from './adapter';
export { Logger } from 'log4js';
export type Dict<T = any, K extends string | symbol = string> = Record<K, T>;
export type Bot<AD extends Adapter> = Adapter.Bot<AdapterBot<AD>>;
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'mark' | 'off';
export type NumString<S extends string> = `${number}` | `${number}${S}${string}`;
export type Merge<First, Second> = {
[Key in keyof (First & Second)]: Key extends keyof Second
? Second[Key]
: Key extends keyof First
? First[Key]
: never;
};
56 changes: 1 addition & 55 deletions core/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import crypto, { BinaryLike } from 'crypto';
import { Dict, Merge } from './types';
import { Dict, Merge } from '@zhinjs/shared';
/**
* AES encryption
* @param data {BinaryLike} The data to encrypt
Expand Down Expand Up @@ -28,35 +28,6 @@ export function aesDecrypt(
return Buffer.concat([decipher.update(encryptedData), decipher.final()]);
}

export function isEmpty<T>(data: T) {
if (!data) return true;
if (typeof data !== 'object') return false;
return Reflect.ownKeys(data).length === 0;
}

export function remove<T>(list: T[], fn: (item: T) => boolean): void;
export function remove<T>(list: T[], item: T): void;
export function remove<T>(list: T[], arg: T | ((item: T) => boolean)) {
const index =
typeof arg === 'function' && !list.every(item => typeof item === 'function')
? list.findIndex(arg as (item: T) => boolean)
: list.indexOf(arg as T);
if (index !== -1) list.splice(index, 1);
}

export function deepClone<T>(obj: T): T {
if (typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(deepClone) as T;
if (!obj) return obj;
const Constructor = obj.constructor;

let newObj: T = Constructor() as T;
for (let key in obj) {
newObj[key] = deepClone(obj[key]) as any;
}
return newObj;
}

/**
* 寻找数组中最后一个符合条件的元素下标
* @param list 数组
Expand Down Expand Up @@ -153,20 +124,6 @@ export function formatDateTime(timestamp: number) {
})
.join(' ');
}
export function deepMerge<First, Second>(first: First, second: Second): Merge<First, Second> {
if (!first || typeof first !== typeof second || typeof first !== 'object') return first as any;
const result = (Array.isArray(first) ? [] : {}) as Merge<First, Second>;
for (const key of Reflect.ownKeys(first)) {
Reflect.set(result, key, Reflect.get(first, key));
}
for (const key of Reflect.ownKeys(second as object)) {
if (Reflect.has(result, key))
Reflect.set(result, key, deepMerge(Reflect.get(result, key), Reflect.get(second as object, key)));
else Reflect.set(result, key, Reflect.get(second as object, key));
}
return result;
}

export function getValueWithRuntime(template: string, ctx: Dict) {
const result = evaluate(template, ctx);
if (result === `return(${template})`) return template;
Expand Down Expand Up @@ -204,14 +161,6 @@ export function compiler(template: string, ctx: Dict) {
}
return template;
}
export const wrapExport = (filePath: string) => {
const result = require(filePath);
if (result.default) {
const { default: main, ...other } = result;
return Object.assign(main, other);
}
return result;
};

export function setValueToObj(obj: Dict, keys: string[], value: any): boolean;
export function setValueToObj(obj: Dict, key: string, value: any): boolean;
Expand Down Expand Up @@ -329,6 +278,3 @@ export function parseTimeFromStr(dateStr: string) {
}
return result;
}
export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
4 changes: 1 addition & 3 deletions packages/adapters/com-wechat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@
"directory": "packages/adapters/com-wechat"
},
"dependencies": {
"zhin": "workspace:^",
"ws": "latest",
"@zhinjs/plugin-http-server": "workspace:^"
"ws": "latest"
},
"peerDependencies": {
"zhin": "workspace:^",
Expand Down
4 changes: 1 addition & 3 deletions packages/adapters/dingtalk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@
"directory": "packages/adapters/dingtalk"
},
"dependencies": {
"zhin": "workspace:^",
"node-dd-bot": "latest"
},
"peerDependencies": {
"zhin": "workspace:^",
"node-dd-bot": "latest"
"zhin": "workspace:^"
}
}
Loading

0 comments on commit ad4e8e8

Please sign in to comment.