diff --git a/bun.lock b/bun.lock index 2e1249299..8c9420dc5 100644 --- a/bun.lock +++ b/bun.lock @@ -370,6 +370,20 @@ "webpack": "^5", }, }, + "shared": { + "name": "shared", + "version": "1.0.0", + "dependencies": { + "database": "*", + "esbuild": "^0.25.2", + "zod": "^3.25.20", + }, + "devDependencies": { + "@biomejs/biome": "1.9.4", + "@types/node": "^17.0.21", + "typescript": "^4.9.5", + }, + }, }, "packages": { "@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="], @@ -2806,6 +2820,8 @@ "sha.js": ["sha.js@2.4.11", "", { "dependencies": { "inherits": "^2.0.1", "safe-buffer": "^5.0.1" }, "bin": { "sha.js": "./bin.js" } }, "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ=="], + "shared": ["shared@workspace:shared"], + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], @@ -3280,6 +3296,8 @@ "zen-observable-ts": ["zen-observable-ts@1.2.5", "", { "dependencies": { "zen-observable": "0.8.15" } }, "sha512-QZWQekv6iB72Naeake9hS1KxHlotfRpe+WGNbNx5/ta+R3DNjVO2bswf63gXlWDcs+EMd7XY8HfVQyP1X6T4Zg=="], + "zod": ["zod@3.25.20", "", {}, "sha512-z03fqpTMDF1G02VLKUMt6vyACE7rNWkh3gpXVHgPTw28NPtDFRGvcpTtPwn2kMKtQ0idtYJUTxchytmnqYswcw=="], + "@apollo/protobufjs/@types/node": ["@types/node@10.17.60", "", {}, "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw=="], "@apollographql/graphql-upload-8-fork/http-errors": ["http-errors@1.8.1", "", { "dependencies": { "depd": "~1.1.2", "inherits": "2.0.4", "setprototypeof": "1.2.0", "statuses": ">= 1.5.0 < 2", "toidentifier": "1.0.1" } }, "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g=="], diff --git a/package.json b/package.json index 0d73289a6..7979b9e77 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "database", "dht-node", "federation", - "frontend" + "frontend", + "shared" ], "scripts": { "release": "scripts/release.sh", diff --git a/shared/package.json b/shared/package.json new file mode 100644 index 000000000..f0434567a --- /dev/null +++ b/shared/package.json @@ -0,0 +1,37 @@ +{ + "name": "shared", + "version": "1.0.0", + "description": "Gradido Shared Code", + "main": "./build/index.js", + "types": "./src/index.ts", + "exports": { + ".": { + "import": "./build/index.js", + "require": "./build/index.js" + } + }, + "repository": "https://github.com/gradido/gradido/shared", + "author": "Gradido Academy - https://www.gradido.net", + "license": "Apache-2.0", + "private": true, + "scripts": { + "build": "esbuild src/index.ts --outdir=build --platform=node --target=node18.20.7 --bundle --packages=external", + "build:bun": "bun build src/index.ts --outdir=build --target=bun --packages=external", + "typecheck": "tsc --noEmit", + "lint": "biome check --error-on-warnings .", + "lint:fix": "biome check --error-on-warnings . --write" + }, + "devDependencies": { + "@biomejs/biome": "1.9.4", + "@types/node": "^17.0.21", + "typescript": "^4.9.5" + }, + "dependencies": { + "database": "*", + "esbuild": "^0.25.2", + "zod": "^3.25.20" + }, + "engines": { + "node": ">=18" + } +} diff --git a/shared/src/index.test.ts b/shared/src/index.test.ts new file mode 100644 index 000000000..b942d6baf --- /dev/null +++ b/shared/src/index.test.ts @@ -0,0 +1,5 @@ +describe('shared', () => { + it('should be true', () => { + expect(true).toBe(true) + }) +}) \ No newline at end of file diff --git a/shared/src/index.ts b/shared/src/index.ts new file mode 100644 index 000000000..e69de29bb diff --git a/shared/src/server/LogError.ts b/shared/src/server/LogError.ts new file mode 100644 index 000000000..346923019 --- /dev/null +++ b/shared/src/server/LogError.ts @@ -0,0 +1,8 @@ +import { backendLogger as logger } from './logger' + +export class LogError extends Error { + constructor(msg: string, ...details: any[]) { + super(msg) + logger.error(msg, ...details) + } +} diff --git a/shared/src/server/logger.ts b/shared/src/server/logger.ts new file mode 100644 index 000000000..24ae79c67 --- /dev/null +++ b/shared/src/server/logger.ts @@ -0,0 +1,21 @@ +import { readFileSync } from 'fs' + +import { configure, getLogger } from 'log4js' + +import { CONFIG } from '@/config' + +const options = JSON.parse(readFileSync(CONFIG.LOG4JS_CONFIG, 'utf-8')) + +options.categories.backend.level = CONFIG.LOG_LEVEL +options.categories.apollo.level = CONFIG.LOG_LEVEL + +configure(options) + +const apolloLogger = getLogger('apollo') +const backendLogger = getLogger('backend') +const klickTippLogger = getLogger('klicktipp') +const gmsLogger = getLogger('gms') + +backendLogger.addContext('user', 'unknown') + +export { apolloLogger, backendLogger, klickTippLogger, gmsLogger } diff --git a/shared/src/user/schema/alias.test.ts b/shared/src/user/schema/alias.test.ts new file mode 100644 index 000000000..0bdfb59a6 --- /dev/null +++ b/shared/src/user/schema/alias.test.ts @@ -0,0 +1,97 @@ +import { validateAlias } from './alias' + +describe('validate alias', () => { + beforeAll(() => { + jest.clearAllMocks() + }) + + describe('alias too short', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('Bi')).rejects.toEqual(new Error('Given alias is too short')) + expect(logger.error).toBeCalledWith('Given alias is too short', 'Bi') + }) + }) + + describe('alias too long', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('BibiBloxbergHexHexHex')).rejects.toEqual( + new Error('Given alias is too long'), + ) + expect(logger.error).toBeCalledWith('Given alias is too long', 'BibiBloxbergHexHexHex') + }) + }) + + describe('alias contains invalid characters', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('Bibi.Bloxberg')).rejects.toEqual( + new Error('Invalid characters in alias'), + ) + expect(logger.error).toBeCalledWith('Invalid characters in alias', 'Bibi.Bloxberg') + }) + }) + + describe('alias is a reserved word', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('admin')).rejects.toEqual(new Error('Alias is not allowed')) + expect(logger.error).toBeCalledWith('Alias is not allowed', 'admin') + }) + }) + + describe('alias is a reserved word with uppercase characters', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('Admin')).rejects.toEqual(new Error('Alias is not allowed')) + expect(logger.error).toBeCalledWith('Alias is not allowed', 'Admin') + }) + }) + + describe('hyphens and underscore', () => { + describe('alias starts with underscore', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('_bibi')).rejects.toEqual( + new Error('Invalid characters in alias'), + ) + expect(logger.error).toBeCalledWith('Invalid characters in alias', '_bibi') + }) + }) + + describe('alias contains two following hyphens', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('bi--bi')).rejects.toEqual( + new Error('Invalid characters in alias'), + ) + expect(logger.error).toBeCalledWith('Invalid characters in alias', 'bi--bi') + }) + }) + }) + + describe('test against existing alias in database', () => { + beforeAll(async () => { + const bibi = await userFactory(testEnv, bibiBloxberg) + const user = await User.findOne({ where: { id: bibi.id } }) + if (user) { + user.alias = 'b-b' + await user.save() + } + }) + + describe('alias exists in database', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('b-b')).rejects.toEqual(new Error('Alias already in use')) + expect(logger.error).toBeCalledWith('Alias already in use', 'b-b') + }) + }) + + describe('alias exists in database with in lower-case', () => { + it('throws and logs an error', async () => { + await expect(validateAlias('b-B')).rejects.toEqual(new Error('Alias already in use')) + expect(logger.error).toBeCalledWith('Alias already in use', 'b-B') + }) + }) + + describe('valid alias', () => { + it('resolves to true', async () => { + await expect(validateAlias('bibi')).resolves.toEqual(true) + }) + }) + }) +}) diff --git a/shared/src/user/schema/alias.ts b/shared/src/user/schema/alias.ts new file mode 100644 index 000000000..c273f12ba --- /dev/null +++ b/shared/src/user/schema/alias.ts @@ -0,0 +1,66 @@ +import { z } from 'zod' +import { User as DbUser } from 'database' +import { Raw } from 'typeorm' +// import { LogError } from '@/server/LogError' + +class LogError extends Error { + details: any[] + constructor(msg: string, ...details: any[]) { + super(msg) + this.name = 'LogError' + this.message = msg + this.stack = new Error().stack + this.details = details + } +} + +export const VALID_ALIAS_REGEX = /^(?=.{3,20}$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+?)*$/ + +const RESERVED_ALIAS = [ + 'admin', + 'email', + 'gast', + 'gdd', + 'gradido', + 'guest', + 'home', + 'root', + 'support', + 'temp', + 'tmp', + 'tmp', + 'user', + 'usr', + 'var', +] + +export const aliasSchema = z + .string() + .min(3, 'Alias is too short') + .max(20, 'Alias is too long') + .regex(VALID_ALIAS_REGEX, 'Invalid characters in alias') + .refine((val) => !RESERVED_ALIAS.includes(val.toLowerCase()), { + message: 'Alias is not allowed', + }) + +export const validateAlias = async (alias: string): Promise => { + try { + aliasSchema.parse(alias) + } catch (err) { + if (err instanceof z.ZodError) { + console.log(err) + throw new LogError(err.errors[0].message, alias) + } + throw err + } + + const aliasInUse = await DbUser.find({ + where: { alias: Raw((a) => `LOWER(${a}) = "${alias.toLowerCase()}"`) }, + }) + + if (aliasInUse.length !== 0) { + throw new LogError('Alias already in use', alias) + } + + return true +} diff --git a/shared/tsconfig.json b/shared/tsconfig.json new file mode 100644 index 000000000..04306edad --- /dev/null +++ b/shared/tsconfig.json @@ -0,0 +1,73 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./build/outfile.js", /* Concatenate and emit output to single file. */ + "outDir": "./build", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + "strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": ".", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [".", "../database"], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + }, + "references": [] /* Any project that is referenced must itself have a `references` array (which may be empty). */ +} diff --git a/shared/turbo.json b/shared/turbo.json new file mode 100644 index 000000000..2d56da524 --- /dev/null +++ b/shared/turbo.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://turbo.build/schema.json", + "tasks": { + "lint": { + }, + "lint:fix": { + }, + "test": { + }, + "typecheck": { + }, + "dev": { + "dependsOn": ["database#build"], + "persistent": true, + "cache": false + }, + "build": { + "dependsOn": ["^build"], + "outputs": ["build/**"], + "cache": true + } + } +} \ No newline at end of file