very-express 0.6.12-alpha → 0.6.13-alpha

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.
@@ -4,8 +4,9 @@ import { JsonWebTokenError } from "jsonwebtoken";
4
4
  import JWTService from "../_services/auth/JWTService.gen";
5
5
  import log from "../_utils/logger.gen";
6
6
  import response from "../_utils/response.gen";
7
+ import { VexResErr, VexResOk } from "../_types/vex";
7
8
 
8
- export default class Authentication {
9
+ class Authentication {
9
10
 
10
11
  private JWTService = new JWTService();
11
12
 
@@ -31,14 +32,16 @@ export default class Authentication {
31
32
  }
32
33
  catch (e: any) {
33
34
  if (typeof e === "number") {
34
- response.send(res, e);
35
+ throw new VexResErr(e, undefined);
35
36
  }
36
37
  else if (e instanceof JsonWebTokenError) {
37
- response.send(res, 400, { message: e?.message});
38
+ throw new VexResErr(400, undefined, e?.message);
38
39
  }
39
40
  else {
40
- response.send(res, 500, { message: e?.message});
41
+ throw new VexResErr(500, undefined, e?.message);
41
42
  }
42
43
  }
43
44
  };
44
- }
45
+ }
46
+
47
+ export default new Authentication();
@@ -0,0 +1,59 @@
1
+ // {{headerComment}}
2
+ import { Request, Response, NextFunction } from "express";
3
+ import { VexResErr } from "../_types/vex";
4
+ import joinWhitelistRegistry from "./JoinWhitelistRegistry.gen";
5
+
6
+ /**
7
+ * Validates join paths against the centralized whitelist registry.
8
+ *
9
+ * The registry maps documentName → { relationName → relatedDocumentName }
10
+ * and is generated at build time by VeryExpress from schema FK metadata.
11
+ *
12
+ * Nested paths like "user.userContact" on Package are validated hop-by-hop:
13
+ * 1. check "user" in Package's map → next doc = "User"
14
+ * 2. check "userContact" in User's map → ok
15
+ */
16
+ class JoinWhitelistMiddleware {
17
+ middleware(documentName: string) {
18
+ return (req: Request, res: Response, next: NextFunction): void => {
19
+ const join = this.extractJoin(req);
20
+
21
+ if (!join || join.length === 0) {
22
+ return next();
23
+ }
24
+
25
+ for (const joinPath of join) {
26
+ this.validateJoinPath(joinPath, documentName);
27
+ }
28
+
29
+ next();
30
+ };
31
+ }
32
+
33
+ private validateJoinPath(joinPath: string, rootDocumentName: string): void {
34
+ const segments = joinPath.split(".");
35
+ let currentDoc = rootDocumentName;
36
+
37
+ for (const segment of segments) {
38
+ const relations = joinWhitelistRegistry[currentDoc];
39
+ if (!relations || !(segment in relations)) {
40
+ throw new VexResErr(403, undefined, `Join "${segment}" is not allowed on "${currentDoc}"`);
41
+ }
42
+ currentDoc = relations[segment];
43
+ }
44
+ }
45
+
46
+ private extractJoin(req: Request): string[] | undefined {
47
+ // getList sends join inside POST body; get sends it as query param
48
+ const bodyJoin = (req.body as { join?: string[] })?.join;
49
+ const queryJoin = req.query?.join;
50
+
51
+ if (bodyJoin) return bodyJoin;
52
+ if (!queryJoin) return undefined;
53
+ return Array.isArray(queryJoin) ? (queryJoin as string[]) : [queryJoin as string];
54
+ }
55
+ }
56
+
57
+ export default new JoinWhitelistMiddleware();
58
+
59
+
@@ -19,8 +19,8 @@ OAUTH_GITHUB_CLIENTSECRET=
19
19
  # OAUTH_APPLE_CLIENTSECRET=
20
20
 
21
21
  # JWT token
22
- ACCESS_TOKEN_EXPIRE_TIME='5m'
23
- REFRESH_TOKEN_EXPIRE_TIME='15m'
22
+ ACCESS_TOKEN_EXPIRE_TIME='1h'
23
+ REFRESH_TOKEN_EXPIRE_TIME='24h'
24
24
  SESSION_COOKIE_SECRET='my-session-cookie-secret'
25
25
  JWT_ALGORITHM='HS256'
26
26
  JWT_SECRET0='my-secret-key0'
@@ -0,0 +1,148 @@
1
+ // {{headerComment}}
2
+ import { Router, Request, Response } from "express";
3
+ import crypto from "crypto";
4
+
5
+ export interface LoginUIConfig {
6
+ localAuth: boolean;
7
+ oauthProviders: string[];
8
+ }
9
+
10
+ export default class LoginUI {
11
+
12
+ private router: Router = Router();
13
+ private config: LoginUIConfig;
14
+
15
+ constructor(config: LoginUIConfig) {
16
+ this.config = config;
17
+ this.registerRoutes();
18
+ }
19
+
20
+ getRouter(): Router {
21
+ return this.router;
22
+ }
23
+
24
+ private registerRoutes(): void {
25
+ this.router.get("/", this.homePage.bind(this));
26
+ this.router.get("/login", this.loginPage.bind(this));
27
+ this.router.get("/logout", this.logoutPage.bind(this));
28
+ this.router.get("/mytokens", this.myTokensPage.bind(this));
29
+ this.router.get("/refreshtoken", this.refreshTokenPage.bind(this));
30
+ this.router.get("/logincallback", this.loginCallbackPage.bind(this));
31
+ }
32
+
33
+ private nonce(): string {
34
+ return crypto.randomBytes(16).toString("base64");
35
+ }
36
+
37
+ private homePage(_req: Request, res: Response): void {
38
+ const authLinks = this.config.localAuth || this.config.oauthProviders.length > 0
39
+ ? `<li><a href="/login">Login</a></li>
40
+ <li><a href="/mytokens">myTokens</a></li>
41
+ <li><a href="/refreshtoken">RefreshToken</a></li>
42
+ <li><a href="/logout">LogOut</a></li>`
43
+ : "";
44
+
45
+ res.send(`
46
+ <div>
47
+ <h1>Hello World</h1>
48
+ <ul>
49
+ ${authLinks}
50
+ <li><a href="/swagger">Swagger UI</a></li>
51
+ </ul>
52
+ <h1>Others</h1>
53
+ <ul>
54
+ <li><a href="/logincallback">logincallback</a></li>
55
+ </ul>
56
+ </div>
57
+ `);
58
+ }
59
+
60
+ private loginPage(_req: Request, res: Response): void {
61
+ const nonce = this.nonce();
62
+ res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
63
+
64
+ let formHtml = "";
65
+ if (this.config.localAuth) {
66
+ formHtml += `
67
+ <p>Email:</p>
68
+ <input type="email" id="email"/>
69
+ <p>Password:</p>
70
+ <input type="password" id="password"/>
71
+ <br/><br/>
72
+ <button id="localLoginBtn">Login</button>
73
+ <button id="localRegisterBtn">Register</button>
74
+ <br/><br/>`;
75
+ }
76
+
77
+ formHtml += " <p>Login with SSO:</p>\n";
78
+ if (this.config.oauthProviders.length === 0) {
79
+ formHtml += " <p>No OAuth provider configured.</p>\n";
80
+ }
81
+ else {
82
+ this.config.oauthProviders.forEach((provider) => {
83
+ formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
84
+ });
85
+ }
86
+
87
+ const scriptTag = this.config.localAuth
88
+ ? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
89
+ : "";
90
+
91
+ res.send(`${scriptTag}<body>${formHtml}</body>`);
92
+ }
93
+
94
+ private logoutPage(_req: Request, res: Response): void {
95
+ const nonce = this.nonce();
96
+ res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
97
+ res.send(`
98
+ <script nonce="${nonce}">
99
+ localStorage.removeItem('accessToken');
100
+ localStorage.removeItem('accessTokenIndex');
101
+ localStorage.removeItem('refreshToken');
102
+ localStorage.removeItem('refreshTokenIndex');
103
+ </script>
104
+ `);
105
+ }
106
+
107
+ private myTokensPage(_req: Request, res: Response): void {
108
+ const nonce = this.nonce();
109
+ res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
110
+ res.send(`
111
+ <script nonce="${nonce}" src="/js/mytokens.js"></script>
112
+ <link rel="stylesheet" href="/css/style.css">
113
+ <body>
114
+ <h1>My Token</h1>
115
+ <pre id="tokenData"></pre>
116
+ <a href="/">back to home</a>
117
+ </body>
118
+ `);
119
+ }
120
+
121
+ private refreshTokenPage(_req: Request, res: Response): void {
122
+ const nonce = this.nonce();
123
+ res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
124
+ res.send(`
125
+ <script nonce="${nonce}" src="/js/refreshtokens.js"></script>
126
+ <link rel="stylesheet" href="/css/style.css">
127
+ <body>
128
+ <h1>New Token</h1>
129
+ <pre id="tokenData"></pre>
130
+ <a href="/">back to home</a>
131
+ </body>
132
+ `);
133
+ }
134
+
135
+ private loginCallbackPage(_req: Request, res: Response): void {
136
+ const nonce = this.nonce();
137
+ res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
138
+ res.send(`
139
+ <script nonce="${nonce}" src="/js/logincallback.js"></script>
140
+ <link rel="stylesheet" href="/css/style.css">
141
+ <body>
142
+ <h1>Profile Data</h1>
143
+ <pre id="tokenData"></pre>
144
+ <a href="/">back to home</a>
145
+ </body>
146
+ `);
147
+ }
148
+ }
@@ -1,5 +1,5 @@
1
1
  // {{headerComment}}
2
- import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, Raw } from "typeorm";
2
+ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, Raw, FindManyOptions } from "typeorm";
3
3
  import { VexRepository, Select, Filter, Join, FieldOperators } from "../_types/vex";
4
4
  import utils from "../_utils";
5
5
 
@@ -69,12 +69,14 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
69
69
  return this.repo;
70
70
  }
71
71
 
72
- find(filter: Filter<T>, join?: Join, select?: Select): Promise<T[]> {
72
+ find(filter: Filter<T>, join?: Join, select?: Select, options?: FindManyOptions<T>): Promise<T[]> {
73
73
  const where = this.mapOperators(filter) as FindOptionsWhere<T>;
74
74
  return this.repo.find({
75
75
  select,
76
76
  where,
77
- relations: join
77
+ relations: join,
78
+ take: options?.take || 500,
79
+ ...options
78
80
  });
79
81
  }
80
82
 
@@ -3,7 +3,7 @@ import { Request, Response, NextFunction } from "express";
3
3
  import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
4
4
  import mongoose, { Document } from "mongoose";
5
5
  import { sqlMigrations } from "../_models/sqlMigration.gen";
6
- import { VexRepository } from "../_types/vex";
6
+ import { VexRepository, VexResErr } from "../_types/vex";
7
7
  import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
8
8
  import { MongooseRepositoryAdapter } from "./MongooseRepositoryAdapter.gen";
9
9
  import utils from "./../_utils";
@@ -165,7 +165,8 @@ export class VexDbConnector {
165
165
  next();
166
166
  }
167
167
  catch (err: unknown) {
168
- utils.response.send(res, 503, { code: utils.response.code.DB_Action_ERR, message: (err as Error).message });
168
+ utils.response.send(res, 500, { code: utils.response.code.DB_CONN_ERR });
169
+ return;
169
170
  }
170
171
  }
171
172
  }
@@ -6,7 +6,8 @@
6
6
  import { ResponseCode } from "./../../_utils/response.gen";
7
7
 
8
8
  export interface VexResponse<T = unknown>{
9
- code?: ResponseCode;
10
- message?: string | null;
9
+ ret_code?: ResponseCode;
10
+ ret_msg?: string | null;
11
+ elapse?: number;
11
12
  result?: T;
12
13
  }
@@ -3,6 +3,8 @@
3
3
  "x-documentConfig": {
4
4
  "documentName": "Session",
5
5
  "methods": [],
6
+ "apiJoinWhitelist": [],
7
+ "apiSkipRoute": true,
6
8
  "uniqueIndex": [
7
9
  [
8
10
  "sessionCode"
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "type": "object",
3
3
  "x-documentConfig": {
4
+ "documentName": "User",
4
5
  "methods": [
5
6
  "get",
6
- "getList",
7
- "post",
8
7
  "patch"
9
8
  ],
10
- "documentName": "User",
9
+ "apiJoinWhitelist": [],
10
+ "apiSkipRoute": false,
11
+ "noApiRelations": true,
11
12
  "uniqueIndex": [
12
13
  [
13
14
  "email"
@@ -1,13 +1,9 @@
1
1
  {
2
2
  "type": "object",
3
3
  "x-documentConfig": {
4
- "methods": [
5
- "get",
6
- "getList",
7
- "post",
8
- "patch",
9
- "delete"
10
- ],
4
+ "methods": [],
5
+ "apiJoinWhitelist": [],
6
+ "apiSkipRoute": true,
11
7
  "documentName": "UserAuthProfiles"
12
8
  },
13
9
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.6.12-alpha",
3
+ "version": "0.6.13-alpha",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",