添加更多配置文件设置,实现了一个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
Signed by: Lama3L9R
GPG Key ID: 1762AFC05157CE18
14 changed files with 596 additions and 21 deletions

44
.drone.yml Normal file
View File

@ -0,0 +1,44 @@
---
################
# Build & Test #
################
kind: pipeline
name: test
steps:
- name: install
image: node16-alpine
commands:
- yarn install
- yarn test
- name: telgram_notify
image: appleboy/drone-telegram
when:
status:
- success
- failure
settings:
token:
from_secret: telegram_token
to:
format: markdown
message: >
{{#success build.status}}
✅ `{{repo.name}}` #{{build.number}} 号构建测试已通过 .
📝 {{commit.author}} 在 `{{commit.branch}}` 的提交:
```
{{commit.message}}
```
🌐 {{ build.link }}
{{else}}
❌ `{{repo.name}}` #{{build.number}} 号构建测试已失败 .
📝 {{commit.author}} 在 `{{commit.branch}}` 的提交:
```
{{commit.message}}
```
🌐 {{ build.link }}
{{/success}}

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
yarn-error.log
node_modules
production

41
build.js Normal file
View File

@ -0,0 +1,41 @@
import esbuild from 'esbuild'
import exec from 'shelljs.exec'
const productionVersion = "1.0"
const build = exec('git log -n 1 --pretty=format:"%h on %as with key %GK"', { async: false }).stdout
const buildDate = new Date().toTimeString()
const banner = `
==========================================================================
__ _____ ______ __ __ _ __
/ / / ___// __ \\ \\/ /___ _____ _____/ /________ ______(_) /
/ / \\__ \\/ /_/ /\\ / __ \`/ __ \`/ __ / ___/ __ \`/ ___/ / /
/ /______/ / ____/ / / /_/ / /_/ / /_/ / / / /_/ (__ ) / /
/_____/____/_/ /_/\\__, /\\__, /\\__,_/_/ \\__,_/____/_/_/
/____//____/
A high performance mojang yggdrasil and authlib-injector implmentation
Version ${productionVersion} ${build}
Build on ${buildDate}
THIS PROGRAM IS FREE AND OPENSOURCE UNDER THE Anti-996 LICENSE (996.icu)
Copyright (c) 2022-present, Qumolama.d
==========================================================================
`
console.log(banner)
console.log("Creating a production build...")
esbuild.build({
entryPoints: ['./src/index.js'],
outfile: './production/lsp-yggdrasil.full.js',
bundle: true,
platform: 'node',
target: 'es2018',
external: ['./config.js'],
banner: {
js: `/*\n${banner}\n*/`
},
}).then(() => {
console.log("Done! Enjoy the yggdrasil server as FAST as LSP")
})

View File

@ -1,3 +0,0 @@
const esbuild = require('esbuild')
esbuild.build({})

195
jest.config.mjs Normal file
View File

@ -0,0 +1,195 @@
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\Guzhi\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
// coverageDirectory: undefined,
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

View File

@ -6,16 +6,20 @@
"main": "src/index.js",
"license": "Anti-996",
"devDependencies": {
"cross-env": "^7.0.3",
"esbuild": "^0.14.38",
"jest": "^28.0.3",
"nodemon": "^2.0.16"
"nodemon": "^2.0.16",
"shelljs.exec": "^1.1.8"
},
"dependencies": {
"fastify": "^3.29.0",
"hex-to-uuid": "^1.1.1",
"mongoose": "^6.3.1",
"pino-pretty": "^7.6.1"
},
"scripts": {
"dev": "nodemon --watch src/index.js"
"dev": "nodemon --watch src/index.js",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules UNIT_TEST=1 NODE_NO_WARNINGS=1 jest"
}
}

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
})
}
}

15
tests/generator.test.js Normal file
View File

@ -0,0 +1,15 @@
import * as Generator from "../src/generator"
beforeAll(() => {
})
test("generateToken", () => {
const tokens = []
for(let i = 0; i < 1000; i++) {
tokens.push(Generator.generateToken("Qumolama.d"))
}
expect(new Set(tokens).size === tokens.length).toBeTruthy()
})

View File

@ -1100,7 +1100,14 @@ cookie@^0.4.0:
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.2.tgz#0e41f24de5ecf317947c82fc789e06a884824432"
integrity sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==
cross-spawn@^7.0.3:
cross-env@^7.0.3:
version "7.0.3"
resolved "https://registry.yarnpkg.com/cross-env/-/cross-env-7.0.3.tgz#865264b29677dc015ba8418918965dd232fc54cf"
integrity sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==
dependencies:
cross-spawn "^7.0.1"
cross-spawn@^7.0.1, cross-spawn@^7.0.3:
version "7.0.3"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==
@ -1637,6 +1644,14 @@ has@^1.0.3:
dependencies:
function-bind "^1.1.1"
hex-to-uuid@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/hex-to-uuid/-/hex-to-uuid-1.1.1.tgz#d7ab48f58dc1927f10b4106d4010d44d7b1b6b5d"
integrity sha512-CfrwCInfQbWBmGXn8htN//OVXv+jb4yfV29yqTIO9aAsogRYMQGVAOej0tt6c2EVCBgunS55FpBTuNM+lpte6Q==
dependencies:
uuid-parse "^1.1.0"
validator "^9.4.1"
html-escaper@^2.0.0:
version "2.0.2"
resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453"
@ -2904,6 +2919,11 @@ shebang-regex@^3.0.0:
resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172"
integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==
shelljs.exec@^1.1.8:
version "1.1.8"
resolved "https://registry.yarnpkg.com/shelljs.exec/-/shelljs.exec-1.1.8.tgz#6f3c8dd017cb96d2dea82e712b758eab4fc2f68c"
integrity sha512-vFILCw+lzUtiwBAHV8/Ex8JsFjelFMdhONIsgKNLgTzeRckp2AOYRQtHJE/9LhNvdMmE27AGtzWx0+DHpwIwSw==
sift@16.0.0:
version "16.0.0"
resolved "https://registry.yarnpkg.com/sift/-/sift-16.0.0.tgz#447991577db61f1a8fab727a8a98a6db57a23eb8"
@ -3220,6 +3240,11 @@ util-deprecate@^1.0.1:
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
uuid-parse@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/uuid-parse/-/uuid-parse-1.1.0.tgz#7061c5a1384ae0e1f943c538094597e1b5f3a65b"
integrity sha512-OdmXxA8rDsQ7YpNVbKSJkNzTw2I+S5WsbMDnCtIWSQaosNAcWtFuI/YK1TjzUI6nbkgiqEyh8gWngfcv8Asd9A==
v8-to-istanbul@^9.0.0:
version "9.0.0"
resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-9.0.0.tgz#be0dae58719fc53cb97e5c7ac1d7e6d4f5b19511"
@ -3229,6 +3254,11 @@ v8-to-istanbul@^9.0.0:
"@types/istanbul-lib-coverage" "^2.0.1"
convert-source-map "^1.6.0"
validator@^9.4.1:
version "9.4.1"
resolved "https://registry.yarnpkg.com/validator/-/validator-9.4.1.tgz#abf466d398b561cd243050112c6ff1de6cc12663"
integrity sha512-YV5KjzvRmSyJ1ee/Dm5UED0G+1L4GZnLN3w6/T+zZm8scVua4sOhYKWTUrKa0H/tMiJyO9QLHMPN+9mB/aMunA==
walker@^1.0.7:
version "1.0.8"
resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f"