添加更多配置文件设置,实现了一个api,完成部分文件的部分测试
Some checks reported errors
continuous-integration/drone/push Build encountered an error

This commit is contained in:
Qumolama.d
2022-05-03 18:57:20 +08:00
parent 3de6ad9a2a
commit 3b8712a212
14 changed files with 596 additions and 21 deletions

View File

@ -1,7 +1,8 @@
const defaultPrehandler = async function (req, rep) { }
export const config = {
database: {
url: 'mongodb://localhost:27017',
db: 'yggdrasil'
url: 'mongodb://localhost:27017/yggdrasil?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false',
},
server: {
port: 3000,
@ -10,5 +11,13 @@ export const config = {
signing: {
public: '/path/to/public.pem',
private: '/path/to/private.key'
},
custom: {
overridePrehandler: (url) => {
return defaultPrehandler
},
preHooks: (fastify) => {},
preRouting: (fastify) => {},
postRouting: (fastify) => {},
}
}
}

View File

@ -1,11 +1,37 @@
import * as Crypto from 'crypto'
import { server } from './index.js'
import hexToUuid from 'hex-to-uuid'
export function generateToken(username) {
const key = `${Date.now()}-${ Crypto.createHash('sha256').update(Crypto.randomBytes(32)).digest('hex')}-${username}-lsp-${Math.random() * 1.048596}`
const token = Crypto.createHash('sha256').update(key).digest('hex')
return [token, key]
}
server.log.info(`随机生成器 > 为玩家 ${username} 生成令牌: ${token} | 随机 key = ${key}`)
return token
}
export function uuid(input) {
let md5Bytes = Crypto.createHash('md5').update(input).digest()
md5Bytes[6] &= 0x0f; // clear version
md5Bytes[6] |= 0x30; // set to version 3
md5Bytes[8] &= 0x3f; // clear variant
md5Bytes[8] |= 0x80; // set to IETF variant
return hexToUuid(md5Bytes.toString('hex'))
}
export function noSymboUUID(input) {
let md5Bytes = Crypto.createHash('md5').update(input).digest()
md5Bytes[6] &= 0x0f; // clear version
md5Bytes[6] |= 0x30; // set to version 3
md5Bytes[8] &= 0x3f; // clear variant
md5Bytes[8] |= 0x80; // set to IETF variant
return md5Bytes.toString('hex')
}
export function uuidToNoSymboUUID(uuid) {
return uuid.replace('-', '')
}
export function toSymboUUID(uuid) {
return hexToUuid(uuid)
}
console.log(uuid('test'))

View File

@ -16,6 +16,10 @@ export async function headerValidation(req, rep) {
}
}
export async function deserilize(req, payload) {
return JSON.parse(payload)
export async function handleError(err, req, rep) {
return rep.code(500).send({
error: "InternalServerError",
errorMessage: "服务器内部错误",
cause: err.message
})
}

View File

@ -1,8 +1,8 @@
import { fastify } from 'fastify'
import { mongoose } from 'mongoose'
import { generateToken } from './generator.js'
import { registerModels } from './models/index.js';
import * as Hooks from './hooks.js'
import * as AuthenticateRoutings from './routes/authenticate.js'
export const server = fastify({
logger: {
@ -10,12 +10,13 @@ export const server = fastify({
}
})
//export const logger = server.log
;(async () => {
const { config } = await import('./config.js')
server.decorate('config', config)
server.decorate('conf', config)
const mongooseClient = await mongoose.connect(config.database.url)
const models = registerModels(mongooseClient)
@ -23,10 +24,36 @@ export const server = fastify({
server.decorate('mongoose', mongooseClient)
server.decorate('models', models)
config.custom.preHooks(server)
server.addHook('preHandler', Hooks.headerValidation)
config.custom.preRouting(server)
server.route(AuthenticateRoutings.authenticate)
config.custom.postRouting(server)
/*
// Create a test player
await new models.Player({
username: 'test',
password: '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92',
email: 'i@lama.icu',
uuid: '098f6bcd-4621-3373-8ade-4e832627b4f6',
texture: {
skin: 'assets.lama.icu/textures/skin/steve.png',
cape: 'assets.lama.icu/textures/cape/default.png'
},
registerDate: Date.now(),
permissions: [{ node: 'login', allowed: true, duration: 0, eternal: true, startDate: Date.now(), highPriority: false }]
}).save()
*/
if(!process.env["UNIT_TEST"]) {
await launch(config)
}
})()
const launch = async (config) => {
await server.listen(config.server.port, config.server.url)
server.log.info("老色批世界树 > 基于 fastify 的高性能 HTTP 服务器已启动")
})()
}

View File

@ -2,7 +2,7 @@ import mongoose from 'mongoose'
const { Schema } = mongoose
export const PlayerSchema = new Schema({
username: String,
username: String, // 有符号 UUID
password: String,
email: String,
uuid: String,
@ -11,5 +11,57 @@ export const PlayerSchema = new Schema({
cape: String,
},
registerDate: Number,
permissions: [{ node: String, allowed: Boolean, duration: Number, eternal: Boolean, startDate: Number, highPriority: Boolean }], // ban -> true
})
permissions: [{ node: String, allowed: Boolean, duration: Number, startDate: Number, highPriority: Boolean }], // ban -> true
})
export const PlayerSeriliazationSchema = {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"properties": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "string"
},
"signature": {
"type": "string"
}
}
}
}
}
}
export const PlayerAccountSerializationSchema = {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"properties": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
}
}

View File

@ -0,0 +1,130 @@
import * as PlayerModel from '../models/player.js'
import { createHash } from 'crypto'
import { generateToken, uuidToNoSymboUUID } from '../generator.js'
export const authenticate = {
method: 'POST',
url: '/authserver/authenticate',
schema: {
body: {
"type": "object",
"properties": {
"username": {
"type": "string"
},
"password": {
"type": "string"
},
"clientToken": {
"type": "string"
},
"requestUser": {
"type": "boolean"
},
"agent": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "integer"
}
}
}
}
},
response: {
200: {
"type": "object",
"properties": {
"accessToken": {
"type": "string"
},
"clientToken": {
"type": "string"
},
"availableProfiles": {
"type": "array",
"items": [{...PlayerModel.PlayerSeriliazationSchema}]
},
"selectedProfile": PlayerModel.PlayerSeriliazationSchema,
"user": PlayerModel.PlayerAccountSerializationSchema
}
}
}
},
preHandler: async function(req, rep) {
this.conf.custom.overridePrehandler('/authserver/authenticate')
},
handler: async function (req, rep) {
let { username, password, clientToken, requestUser, agent } = req.body
const player = await this.models.Player.findOne({ email: username, password: createHash('sha256').update(password).digest().toString('hex').toLowerCase() })
if(!player || !player.permissions.some((it) => {
return it.node === 'login' && it.allowed && (it.duration === 0 || it.startDate + it.duration > Date.now())
})) {
return await rep.code(401).send({
error: "Unauthorized",
errorMessage: "用户名或密码错误",
cause: "用户名或密码错误"
})
}
if(!clientToken) {
clientToken = createHash('sha256').update( "" + Math.random() * 1.048596).digest().toString('hex')
}
const [token, key] = await generateToken(clientToken, requestUser, agent)
this.log.info(`/authserver/authenticate > 为玩家 ${username} 生成令牌: ${token} | 随机 key = ${key}`)
const account = {
id: uuidToNoSymboUUID(player.uuid),
properties: [
{
preferredLanguage: "zh_CN"
}
]
}
const textures = {
timestamp: 0,
profileId: uuidToNoSymboUUID(player.uuid),
profileName: player.username,
textures: { }
}
if(player.textures.skin && player.textures.skin != 0) { // Must be '!=' if this change to '!==' will never works
textures.textures.SKIN = {
url: player.textures.skin,
metadata
}
}
const profile = {
uuid: uuidToNoSymboUUID(player.uuid),
name: player.username,
properties: [
{
name: "texturs",
value: Buffer.from(JSON.stringify(textures)).toString('base64')
}
]
}
new this.models.Token({
uuid: player.uuid,
token: token,
expireDate: Date.now() + 1000 * 60 * 60 * 24 * 15,
deadDate: Date.now() + 1000 * 60 * 60 * 24 * 30,
state: 'alive'
}).save()
return await rep.send({
accessToken: token,
clientToken: clientToken,
availableProfiles: [ profile ],
selectedProfile: profile,
user: account
})
}
}