@mingjue8888/express-plus 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Usage
@@ -0,0 +1,36 @@
1
+ import {
2
+ ErrorRequestHandler,
3
+ Handler,
4
+ NextFunction,
5
+ Request,
6
+ RequestHandler,
7
+ Response
8
+ } from "express";
9
+
10
+ declare global {
11
+ namespace Express {
12
+ interface Request {
13
+ valid: {
14
+ param: any;
15
+ query: any;
16
+ body: any;
17
+ }
18
+ }
19
+ }
20
+ }
21
+
22
+ export type Middleware =
23
+ | Handler
24
+ | RequestHandler
25
+ | ErrorRequestHandler;
26
+
27
+ export type AsyncMiddlewareHandler =
28
+ (req: Request, res: Response) => Promise<void>;
29
+
30
+ export default function asyncMiddleware(handler: AsyncMiddlewareHandler): Middleware {
31
+ return function (req: Request, res: Response, next: NextFunction) {
32
+ handler(req, res)
33
+ .then(() => next())
34
+ .catch(err => next(err));
35
+ }
36
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class CatchCrawlerResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 418;
6
+ }
7
+ }
package/demo-app.ts ADDED
@@ -0,0 +1,39 @@
1
+ import routerA from "./demo-routerA";
2
+ import routerB, {NotFoundUserError} from "./demo-routerB";
3
+ import app from "./index";
4
+ import LoginAccount from "./login-account";
5
+ import LoginToken from "./login-token";
6
+ import NotFoundResponseError from "./not-found-response-error";
7
+
8
+ interface UserAccount extends LoginAccount {}
9
+
10
+ declare global {
11
+ namespace Express {
12
+ interface User extends UserAccount {}
13
+ }
14
+ }
15
+
16
+ const routers = [
17
+ routerA,
18
+ routerB,
19
+ ];
20
+
21
+ app(routers, {
22
+ APP_PORT: 3000,
23
+
24
+ async authenticate<UserAccount>(token: LoginToken) {
25
+ return {
26
+ id: token.sub,
27
+ isLocked: false,
28
+ isSuspended: false,
29
+ isBanned: false,
30
+ roles: [],
31
+ } as UserAccount;
32
+ },
33
+
34
+ onError(err: Error) {
35
+ if (err instanceof NotFoundUserError) {
36
+ return new NotFoundResponseError(err.constructor.name, "Not found user");
37
+ }
38
+ }
39
+ });
@@ -0,0 +1,35 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import Router from "./router";
4
+ import validBody from "./valid-body";
5
+ import validResponse from "./valid-response";
6
+
7
+ const login: Router = {
8
+ method: "POST",
9
+ path: "/login",
10
+ middlewares: [
11
+ validBody({
12
+ username: Joi.string()
13
+ .required(),
14
+
15
+ password: Joi.string()
16
+ .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/)
17
+ .required()
18
+ }),
19
+ asyncMiddleware(async function (req, res) {
20
+ const username = req.valid.body.username as string;
21
+ const password = req.valid.body.password as string;
22
+ const id = "UUID";
23
+ res.signToken(id);
24
+ }),
25
+ validResponse({
26
+ accessToken: Joi.string()
27
+ .required(),
28
+ }),
29
+ ],
30
+ }
31
+
32
+ export default [
33
+ login,
34
+ ];
35
+
@@ -0,0 +1,58 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import hasLogin from "./has-login";
4
+ import Router from "./router";
5
+ import validParam from "./valid-param";
6
+ import validResponse from "./valid-response";
7
+
8
+ export class NotFoundUserError extends Error {}
9
+
10
+ const findUser: Router = {
11
+ method: "GET",
12
+ path: "/users/:userId",
13
+ middlewares: [
14
+ hasLogin,
15
+ validParam({
16
+ userId: Joi.string()
17
+ .required(),
18
+ }),
19
+ asyncMiddleware(async function (req, res) {
20
+ throw new NotFoundUserError();
21
+ }),
22
+ validResponse({
23
+ id: Joi.string()
24
+ .required(),
25
+
26
+ name: Joi.string()
27
+ .required(),
28
+ }),
29
+ ],
30
+ }
31
+
32
+ const findUserPosts: Router = {
33
+ method: "GET",
34
+ path: "/users/:userId/posts",
35
+ middlewares: [
36
+ hasLogin,
37
+ validParam({
38
+ userId: Joi.string()
39
+ .required(),
40
+ }),
41
+ asyncMiddleware(async function (req, res) {
42
+ res.body = {
43
+ posts: []
44
+ }
45
+ }),
46
+ validResponse({
47
+ posts: Joi.array().items(Joi.object().keys({
48
+ id: Joi.string().required(),
49
+ content: Joi.string().required().default(""),
50
+ }))
51
+ })
52
+ ],
53
+ }
54
+
55
+ export default [
56
+ findUser,
57
+ findUserPosts,
58
+ ];
package/has-login.ts ADDED
@@ -0,0 +1,7 @@
1
+ import passport from "passport";
2
+ import {Middleware} from "./async-middleware";
3
+
4
+ const hasLogin: Middleware =
5
+ passport.authenticate("jwt", { session: false });
6
+
7
+ export default hasLogin;
@@ -0,0 +1,15 @@
1
+ import _ from "lodash";
2
+ import asyncMiddleware, {Middleware} from "./async-middleware";
3
+ import PermissionDeniedResponseError from "./permission-denied-response-error";
4
+
5
+
6
+ export default function hasPermissions(permissions: string[]): Middleware {
7
+ return asyncMiddleware(async function (req, _res) {
8
+ const userPermissions = req.user?.roles
9
+ .map(r => r.permissions)
10
+ .flat();
11
+
12
+ const noPermission = _.intersection(permissions, userPermissions).length === 0;
13
+ if (noPermission) throw new PermissionDeniedResponseError("PermissionDeniedError", "You do not have permission");
14
+ });
15
+ }
package/has-roles.ts ADDED
@@ -0,0 +1,12 @@
1
+ import _ from "lodash";
2
+ import asyncMiddleware, {Middleware} from "./async-middleware";
3
+ import PermissionDeniedResponseError from "./permission-denied-response-error";
4
+
5
+
6
+ export default function hasRoles(roles: string[]): Middleware {
7
+ return asyncMiddleware(async function (req, _res) {
8
+ const userRoles = req.user?.roles.map(r => r.name);
9
+ const noRole = _.intersection(roles, userRoles).length === 0;
10
+ if (noRole) throw new PermissionDeniedResponseError("NotQualifiedError", "You do not meet the qualifications");
11
+ });
12
+ }
@@ -0,0 +1,5 @@
1
+ import * as crypto from "node:crypto";
2
+
3
+ export default function idgen(): string {
4
+ return crypto.randomUUID().toString().replaceAll("-", "");
5
+ }
package/index.ts ADDED
@@ -0,0 +1,209 @@
1
+ import "dotenv/config";
2
+ import logger from "@mingjue8888/base-dependencies/logger";
3
+ import compression from "compression";
4
+ import cors from "cors";
5
+ import express from "express";
6
+ import rateLimit from "express-rate-limit";
7
+ import Joi from "joi";
8
+ import jwt from "jsonwebtoken";
9
+ import _ from "lodash";
10
+ import morgan from "morgan";
11
+ import passport from "passport";
12
+ import {ExtractJwt, Strategy, StrategyOptions} from "passport-jwt";
13
+ import {Middleware} from "./async-middleware";
14
+ import LoginAccount from "./login-account";
15
+ import LoginToken from "./login-token";
16
+ import PermissionDeniedResponseError from "./permission-denied-response-error";
17
+ import ResponseError from "./response-error";
18
+ import Router from "./router";
19
+ import ServerErrorResponseError from "./server-error-response-error";
20
+ import TooManyRequestsResponseError from "./too-many-requests-response-error";
21
+ import UnauthorizedResponseError from "./unauthorized-response-error";
22
+
23
+ type DeepArray<T> =
24
+ | T[]
25
+ | DeepArray<T>[];
26
+
27
+ type ResponseErrorConverter =
28
+ (err: Error) => ResponseError | void;
29
+
30
+ function errorConverter(onError?: ResponseErrorConverter): Middleware {
31
+ return function (
32
+ err: Error,
33
+ _req: express.Request,
34
+ _res: express.Response,
35
+ next: express.NextFunction
36
+ ) {
37
+ if (onError) {
38
+ const resErr = onError(err);
39
+ if (resErr) {
40
+ next(onError(err));
41
+ } else {
42
+ next(err);
43
+ }
44
+ } else {
45
+ next(err);
46
+ }
47
+ }
48
+ }
49
+
50
+ function errorHandler(
51
+ err: Error,
52
+ _req: express.Request,
53
+ res: express.Response,
54
+ _next: express.NextFunction
55
+ ) {
56
+ if (err instanceof ResponseError) {
57
+ res
58
+ .status(err.getHttpResponseStatus())
59
+ .send({ error: err.error, message: err.message });
60
+ } else {
61
+ logger.error(err);
62
+ res
63
+ .status(500)
64
+ .send({ error: "ServerError", message: err.stack });
65
+ }
66
+ }
67
+
68
+ declare global {
69
+ namespace Express {
70
+ interface User extends LoginAccount {}
71
+ interface Response {
72
+ signToken: (sub: string) => void;
73
+ body?: any;
74
+ }
75
+ }
76
+ }
77
+
78
+ interface EnvOptions {
79
+ APP_PORT?: number;
80
+ APP_REQUEST_RATE_LIMIT?: number;
81
+ APP_REQUEST_RATE_LIMIT_RANGE?: number;
82
+ APP_CORS_ALLOW_ORIGIN?: string;
83
+ JWT_SECRET?: string;
84
+ JWT_EXPIRE?: number;
85
+ }
86
+
87
+ interface StartupOptions extends EnvOptions {
88
+ authenticate?: <T extends LoginAccount>(token: LoginToken) => Promise<T>;
89
+ onError?: ResponseErrorConverter;
90
+ }
91
+
92
+ const oneSecond = 1000;
93
+ const oneMinute = oneSecond * 60;
94
+ const oneHour = oneMinute * 60;
95
+ const oneDay = oneHour * 24;
96
+
97
+ const optSchema = Joi.object<Required<StartupOptions>, StartupOptions>({
98
+ APP_PORT: Joi.number()
99
+ .integer()
100
+ .required()
101
+ .default(8086),
102
+
103
+ APP_REQUEST_RATE_LIMIT: Joi.number()
104
+ .required()
105
+ .default(20),
106
+
107
+ APP_REQUEST_RATE_LIMIT_RANGE: Joi.number()
108
+ .required()
109
+ .default(oneSecond),
110
+
111
+ APP_CORS_ALLOW_ORIGIN: Joi.string()
112
+ .required()
113
+ .default("*"),
114
+
115
+ JWT_SECRET: Joi.string()
116
+ .required()
117
+ .default("DefaultSecret"),
118
+
119
+ JWT_EXPIRE: Joi.number()
120
+ .integer()
121
+ .greater(0)
122
+ .when("JWT_SECRET", {
123
+ is: Joi.exist(),
124
+ then: Joi.required()
125
+ .default(oneDay * 7)
126
+ }),
127
+ });
128
+
129
+ export default function app(routers: DeepArray<Router>, opt?: StartupOptions) {
130
+ if (opt) {
131
+ Reflect.ownKeys(process.env)
132
+ .filter(key => key === key.toString().toUpperCase())
133
+ .forEach(key => Reflect.set(opt, key, process.env[key as string]));
134
+ }
135
+
136
+ const conf: Required<StartupOptions> =
137
+ Joi.attempt(opt || {}, optSchema, { allowUnknown: true });
138
+
139
+ const jwtStrategy: StrategyOptions = {
140
+ secretOrKey: conf.JWT_SECRET,
141
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
142
+ ignoreExpiration: true,
143
+ }
144
+
145
+ const strategy = new Strategy(jwtStrategy, function (payload: LoginToken, next) {
146
+ if (!opt?.authenticate) {
147
+ next(new ServerErrorResponseError("AuthenticationError", "Missing authentication logic"), false);
148
+ return;
149
+ }
150
+ const isExpired = (exp: number): boolean =>
151
+ exp < Math.floor(Date.now() / 1000);
152
+
153
+ if (isExpired(payload.exp)) {
154
+ next(new UnauthorizedResponseError("TokenExpiredError", "The token has expired"), false);
155
+ return;
156
+ }
157
+
158
+ opt.authenticate(payload)
159
+ .then(user => user.isLocked ? Promise.reject(new PermissionDeniedResponseError("AccountLockedError", "Your account has been locked")) : user)
160
+ .then(user => user.isSuspended ? Promise.reject(new PermissionDeniedResponseError("AccountSuspendedError", "Your account is disabled")) : user)
161
+ .then(user => user.isBanned ? Promise.reject(new PermissionDeniedResponseError("AccountBannedError", "Your account has been permanently banned")) : user)
162
+ .then(user => next(null, user))
163
+ .catch(err => next(err, false));
164
+ });
165
+
166
+ passport.use(strategy);
167
+
168
+ function addSignToken(_req: express.Request, res: express.Response, next: express.NextFunction) {
169
+ const now = Math.floor(Date.now() /1000);
170
+ res.signToken = (sub: string) => {
171
+ const payload = {
172
+ sub,
173
+ iat: now,
174
+ exp: now + conf.JWT_EXPIRE
175
+ };
176
+ const accessToken = jwt.sign(payload, conf.JWT_SECRET);
177
+ res.body = { accessToken };
178
+ }
179
+ next();
180
+ }
181
+
182
+ const routes = _.flattenDeep(routers).reduce(
183
+ (router: express.Router, route: Router): express.Router =>
184
+ Reflect.get(router, route.path.toLowerCase()).bind(router)(route.path, ...route.middlewares),
185
+ express.Router(),
186
+ );
187
+
188
+ return express()
189
+ .use(rateLimit({
190
+ windowMs: conf.APP_REQUEST_RATE_LIMIT_RANGE, limit: conf.APP_REQUEST_RATE_LIMIT,
191
+ handler: (_req, _res, next) =>
192
+ next(new TooManyRequestsResponseError("TooManyRequests", "Too many requests, please try again later"))
193
+ }))
194
+ .use(cors({ origin: conf.APP_CORS_ALLOW_ORIGIN }))
195
+ .use(morgan(":method :url :status :res[content-length] - :response-time ms", {
196
+ stream: {
197
+ write: message => logger.http(message.trim())
198
+ }
199
+ }))
200
+ .use(compression())
201
+ .use(express.urlencoded({ extended: true }))
202
+ .use(express.json())
203
+ .use(passport.initialize())
204
+ .use(addSignToken)
205
+ .use(routes)
206
+ .use(errorConverter(opt?.onError))
207
+ .use(errorHandler)
208
+ .listen(conf.APP_PORT, () => logger.info(`Server startup on port: ${conf.APP_PORT}`));
209
+ }
@@ -0,0 +1,11 @@
1
+ import RBAC0 from "./rbac0";
2
+
3
+ export default interface LoginAccount extends RBAC0 {
4
+ id: string;
5
+ isLocked: boolean;
6
+ isSuspended: boolean;
7
+ isBanned: boolean;
8
+ lockedReason?: string;
9
+ suspendedReason?: string;
10
+ bannedReason?: string;
11
+ }
package/login-token.ts ADDED
@@ -0,0 +1,7 @@
1
+ import {JwtPayload} from "jsonwebtoken";
2
+
3
+ export default interface LoginToken extends JwtPayload {
4
+ sub: string;
5
+ iat: number;
6
+ exp: number;
7
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class NotFoundResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 404;
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@mingjue8888/express-plus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "repository": "github:mingjue8888/express-plus",
5
+ "dependencies": {
6
+ "@mingjue8888/base-dependencies": "^1.1.0",
7
+ "bcrypt": "^6.0.0",
8
+ "compression": "^1.8.2",
9
+ "cors": "^2.8.6",
10
+ "express-rate-limit": "^8.7.4",
11
+ "jsonwebtoken": "^9.0.3",
12
+ "morgan": "^1.12.1",
13
+ "passport": "^0.7.0",
14
+ "passport-jwt": "^4.0.1"
15
+ },
16
+ "devDependencies": {
17
+ "@types/bcrypt": "^6.0.0",
18
+ "@types/compression": "^1.8.1",
19
+ "@types/cors": "^2.8.19",
20
+ "@types/express": "^5.0.6",
21
+ "@types/morgan": "^1.9.10",
22
+ "@types/passport": "^1.0.17",
23
+ "@types/passport-jwt": "^4.0.1"
24
+ }
25
+ }
@@ -0,0 +1,9 @@
1
+ import bcrypt from "bcrypt";
2
+
3
+ export function encode(password: string): string {
4
+ return bcrypt.hashSync(password, bcrypt.genSaltSync());
5
+ }
6
+
7
+ export function check(password: string, encoded: string): boolean {
8
+ return bcrypt.compareSync(password, encoded);
9
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class PermissionDeniedResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 403;
6
+ }
7
+ }
package/rbac0.ts ADDED
@@ -0,0 +1,9 @@
1
+
2
+ interface Role {
3
+ name: string;
4
+ permissions: string[];
5
+ }
6
+
7
+ export default interface RBAC0 {
8
+ roles: Role[];
9
+ }
@@ -0,0 +1,9 @@
1
+
2
+
3
+ export default abstract class ResponseError extends Error {
4
+ abstract getHttpResponseStatus(): number;
5
+ constructor(public error: string, message?: string) {
6
+ super(message);
7
+ }
8
+ }
9
+
package/router.ts ADDED
@@ -0,0 +1,18 @@
1
+ import {Middleware} from "./async-middleware";
2
+
3
+
4
+ type Method =
5
+ | "GET"
6
+ | "POST"
7
+ | "PUT"
8
+ | "DELETE";
9
+
10
+
11
+ type Path =
12
+ string;
13
+
14
+ export default interface Router {
15
+ method: Method,
16
+ path: Path,
17
+ middlewares: Middleware[];
18
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class ServerErrorResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 500;
6
+ }
7
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class TooManyRequestsResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 429;
6
+ }
7
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowArbitraryExtensions": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "alwaysStrict": true,
6
+ "esModuleInterop": true,
7
+ "forceConsistentCasingInFileNames": true,
8
+ "module": "esnext",
9
+ "moduleResolution": "node",
10
+ "noImplicitAny": false,
11
+ "skipLibCheck": true,
12
+ "strict": true,
13
+ "target": "esnext",
14
+ "useUnknownInCatchVariables": true
15
+ }
16
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class UnauthorizedResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 401;
6
+ }
7
+ }
package/valid-body.ts ADDED
@@ -0,0 +1,16 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import WrongParamsResponseError from "./wrong-params-response-error";
4
+
5
+ export default function validBody(sch: Record<string, Joi.AnySchema>) {
6
+ return asyncMiddleware(async function (req, _res) {
7
+ const { error, value } = Joi
8
+ .object(sch)
9
+ .validate(req.body, { allowUnknown: true });
10
+
11
+ if (error) {
12
+ throw new WrongParamsResponseError("WrongParamsError", error.message);
13
+ }
14
+ req.valid.body = value;
15
+ });
16
+ }
package/valid-param.ts ADDED
@@ -0,0 +1,16 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import WrongParamsResponseError from "./wrong-params-response-error";
4
+
5
+ export default function validParam(sch: Record<string, Joi.AnySchema>) {
6
+ return asyncMiddleware(async function (req, _res) {
7
+ const { error, value } = Joi
8
+ .object(sch)
9
+ .validate(req.params, { allowUnknown: true });
10
+
11
+ if (error) {
12
+ throw new WrongParamsResponseError("WrongParamsError", error.message);
13
+ }
14
+ req.valid.param = value;
15
+ });
16
+ }
package/valid-query.ts ADDED
@@ -0,0 +1,16 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import WrongParamsResponseError from "./wrong-params-response-error";
4
+
5
+ export default function validQuery(sch: Record<string, Joi.AnySchema>) {
6
+ return asyncMiddleware(async function (req, _res) {
7
+ const { error, value } = Joi
8
+ .object(sch)
9
+ .validate(req.query, { allowUnknown: true });
10
+
11
+ if (error) {
12
+ throw new WrongParamsResponseError("WrongParamsError", error.message);
13
+ }
14
+ req.valid.query = value;
15
+ });
16
+ }
@@ -0,0 +1,16 @@
1
+ import Joi from "joi";
2
+ import asyncMiddleware from "./async-middleware";
3
+ import ServerErrorResponseError from "./server-error-response-error";
4
+
5
+ export default function validResponse(sch: Record<string, Joi.AnySchema>) {
6
+ return asyncMiddleware(async function (_req, res) {
7
+ const { error, value } = Joi
8
+ .object(sch)
9
+ .validate(res.body);
10
+
11
+ if (error) {
12
+ throw new ServerErrorResponseError("WrongResponseError", error.message);
13
+ }
14
+ res.status(200).send(value);
15
+ });
16
+ }
@@ -0,0 +1,7 @@
1
+ import ResponseError from "./response-error";
2
+
3
+ export default class WrongParamsResponseError extends ResponseError {
4
+ getHttpResponseStatus(): number {
5
+ return 400;
6
+ }
7
+ }