very-express 0.7.9 → 0.8.1
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/AGENTS.md +116 -0
- package/CLAUDE.md +8 -160
- package/dist/index.js +501 -458
- package/dist/templates/_middlewares/DataIsolationContext.ts +10 -4
- package/dist/templates/_projectSettings/env +1 -0
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +66 -3
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +72 -11
- package/dist/templates/_services/auth/JWTService.ts +32 -4
- package/dist/templates/_types/vex/VexRepository.ts +5 -4
- package/dist/templates/jsonSchema/User.json +17 -1
- package/docs/CONTRIBUTING.md +8 -3
- package/docs/architecture/authAndRouting.md +95 -0
- package/docs/architecture/databaseTargets.md +99 -0
- package/docs/architecture/generatorPipeline.md +198 -0
- package/docs/architecture/templates.md +66 -0
- package/docs/features/auditFields.md +240 -0
- package/docs/features/dataIsolation.md +19 -7
- package/docs/releaseNote/v0-8-0.md +95 -0
- package/docs/vexJsonSchema.md +40 -2
- package/package.json +8 -4
- package/vitest.config.ts +18 -0
- package/.github/copilot-instructions.md +0 -106
|
@@ -10,13 +10,19 @@ const als = new AsyncLocalStorage<DataIsolationStore>();
|
|
|
10
10
|
|
|
11
11
|
class DataIsolationContext {
|
|
12
12
|
/**
|
|
13
|
-
* Express middleware — creates ALS context with authenticated user's
|
|
13
|
+
* Express middleware — creates ALS context with the authenticated user's identity value.
|
|
14
14
|
* Must run AFTER Authentication.middleware (which sets req.user).
|
|
15
|
+
*
|
|
16
|
+
* The identity is the `vexUserId` token claim, which the auth service fills from the field
|
|
17
|
+
* tagged `x-vexData: "userId"` in the schemas. `_id` is the fallback for tokens issued
|
|
18
|
+
* before that claim existed.
|
|
15
19
|
*/
|
|
16
20
|
middleware(req: Request, _res: Response, next: NextFunction): void {
|
|
17
|
-
const user = (req as
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
const user = (req as Request & { user?: { vexUserId?: string, _id?: string } }).user;
|
|
22
|
+
const userId = user?.vexUserId ?? user?._id;
|
|
23
|
+
|
|
24
|
+
if (userId) {
|
|
25
|
+
als.run({ userId }, () => next());
|
|
20
26
|
} else {
|
|
21
27
|
next();
|
|
22
28
|
}
|
|
@@ -1,11 +1,68 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
import { Model, Document } from "mongoose";
|
|
3
3
|
import { VexRepository, Select, Filter, Join, VexPagination } from "../_types/vex";
|
|
4
|
+
import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
|
|
5
|
+
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
4
6
|
import utils from "../_utils";
|
|
5
7
|
|
|
8
|
+
/** When a framework-managed field is written. */
|
|
9
|
+
type writePhase = "create" | "update";
|
|
10
|
+
|
|
11
|
+
/** Phase a reserved default keyword belongs to — `onCreate*` is write-once, `onUpdate*` is refreshed. */
|
|
12
|
+
function vexFieldPhaseOf(type: VexFieldEntry["type"]): writePhase {
|
|
13
|
+
return type.startsWith("onCreate") ? "create" : "update";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Value the DB layer writes for a framework-managed field.
|
|
18
|
+
* Mongo documents store `Timestamp` fields as ISO strings and `UnixTimestamp` fields as
|
|
19
|
+
* epoch seconds, so both targets end up with the same values.
|
|
20
|
+
* Returns undefined when the field has no value in this context (no authenticated user).
|
|
21
|
+
*/
|
|
22
|
+
function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unknown {
|
|
23
|
+
switch (type) {
|
|
24
|
+
case "onCreateTimestamp":
|
|
25
|
+
case "onUpdateTimestamp":
|
|
26
|
+
return new Date().toISOString();
|
|
27
|
+
case "onCreateUnixTimestamp":
|
|
28
|
+
case "onUpdateUnixTimestamp":
|
|
29
|
+
return Math.floor(Date.now() / 1000);
|
|
30
|
+
case "onCreateUserId":
|
|
31
|
+
case "onUpdateUserId":
|
|
32
|
+
return userId;
|
|
33
|
+
default:
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
6
38
|
export class MongooseRepositoryAdapter<T extends Document> implements VexRepository<T> {
|
|
7
39
|
constructor(private model: Model<T>) {}
|
|
8
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Framework-managed audit fields: strip the caller's values first — a client must never
|
|
43
|
+
* forge createdBy / updatedAt — then fill the ones owned by this write phase.
|
|
44
|
+
* Fields of the other phase are stripped without being written, which is what keeps
|
|
45
|
+
* createdAt / createdBy immutable across an update.
|
|
46
|
+
*/
|
|
47
|
+
private applyVexFields(data: Partial<T>, phase: writePhase): void {
|
|
48
|
+
const fields = entityVexFields[this.model.modelName + "Entity"] ?? [];
|
|
49
|
+
if (fields.length === 0) return;
|
|
50
|
+
|
|
51
|
+
const userId = DataIsolationContext.getStore()?.userId;
|
|
52
|
+
const values: Record<string, unknown> = {};
|
|
53
|
+
|
|
54
|
+
for (const entry of fields) {
|
|
55
|
+
delete (data as Record<string, unknown>)[entry.field];
|
|
56
|
+
|
|
57
|
+
if (vexFieldPhaseOf(entry.type) !== phase) continue;
|
|
58
|
+
|
|
59
|
+
const value = resolveVexFieldValue(entry.type, userId);
|
|
60
|
+
if (value !== undefined) values[entry.field] = value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
Object.assign(data, values);
|
|
64
|
+
}
|
|
65
|
+
|
|
9
66
|
public get native(): Model<T> {
|
|
10
67
|
return this.model;
|
|
11
68
|
}
|
|
@@ -31,7 +88,9 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
31
88
|
}
|
|
32
89
|
|
|
33
90
|
async create(data: Partial<T>): Promise<T> {
|
|
34
|
-
const
|
|
91
|
+
const enriched = { ...data };
|
|
92
|
+
this.applyVexFields(enriched, "create");
|
|
93
|
+
const doc = new this.model(enriched);
|
|
35
94
|
return doc.save();
|
|
36
95
|
}
|
|
37
96
|
|
|
@@ -40,7 +99,9 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
40
99
|
utils.log.error("MongooseRepositoryAdapter.replace called without id — refuse replace document");
|
|
41
100
|
return Promise.resolve(null);
|
|
42
101
|
}
|
|
43
|
-
|
|
102
|
+
const enriched = { ...data };
|
|
103
|
+
this.applyVexFields(enriched, "update");
|
|
104
|
+
return this.model.findByIdAndUpdate(id, enriched, { new: true, overwrite: true }).exec();
|
|
44
105
|
}
|
|
45
106
|
|
|
46
107
|
update(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
@@ -48,7 +109,9 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
48
109
|
utils.log.error("MongooseRepositoryAdapter.update called without id — refuse update document");
|
|
49
110
|
return Promise.resolve(null);
|
|
50
111
|
}
|
|
51
|
-
|
|
112
|
+
const enriched = { ...data };
|
|
113
|
+
this.applyVexFields(enriched, "update");
|
|
114
|
+
return this.model.findByIdAndUpdate(id, { $set: enriched }, { new: true }).exec();
|
|
52
115
|
}
|
|
53
116
|
|
|
54
117
|
async delete(id: string | undefined): Promise<void> {
|
|
@@ -3,20 +3,79 @@ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like
|
|
|
3
3
|
import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination } from "../_types/vex";
|
|
4
4
|
import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
|
|
5
5
|
import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
|
|
6
|
+
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
7
|
import utils from "../_utils";
|
|
7
8
|
|
|
9
|
+
/** When a framework-managed field is written. */
|
|
10
|
+
type writePhase = "create" | "update";
|
|
11
|
+
|
|
12
|
+
/** Phase a reserved default keyword belongs to — `onCreate*` is write-once, `onUpdate*` is refreshed. */
|
|
13
|
+
function vexFieldPhaseOf(type: VexFieldEntry["type"]): writePhase {
|
|
14
|
+
return type.startsWith("onCreate") ? "create" : "update";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Value the DB layer writes for a framework-managed field.
|
|
19
|
+
* Returns undefined when the field has no value in this context (no authenticated user) —
|
|
20
|
+
* the column is then left untouched instead of being set to "undefined".
|
|
21
|
+
*/
|
|
22
|
+
function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unknown {
|
|
23
|
+
switch (type) {
|
|
24
|
+
case "onCreateTimestamp":
|
|
25
|
+
case "onUpdateTimestamp":
|
|
26
|
+
return new Date().toISOString();
|
|
27
|
+
case "onCreateUnixTimestamp":
|
|
28
|
+
case "onUpdateUnixTimestamp":
|
|
29
|
+
return Math.floor(Date.now() / 1000);
|
|
30
|
+
case "onCreateUserId":
|
|
31
|
+
case "onUpdateUserId":
|
|
32
|
+
return userId;
|
|
33
|
+
default:
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
8
38
|
export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRepository<T> {
|
|
9
39
|
constructor(private repo: Repository<T>) {}
|
|
10
40
|
|
|
41
|
+
/** Entity class name from TypeORM metadata — the key used by the generated registries. */
|
|
42
|
+
private getEntityName(): string {
|
|
43
|
+
return this.repo.metadata.target instanceof Function
|
|
44
|
+
? this.repo.metadata.target.name
|
|
45
|
+
: "";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Framework-managed audit fields: strip the caller's values first — a client must never
|
|
50
|
+
* forge createdBy / updatedAt — then fill the ones owned by this write phase.
|
|
51
|
+
* Fields of the other phase are stripped without being written, which is what keeps
|
|
52
|
+
* createdAt / createdBy immutable across an update.
|
|
53
|
+
*/
|
|
54
|
+
private applyVexFields(data: Partial<T>, phase: writePhase): void {
|
|
55
|
+
const fields = entityVexFields[this.getEntityName()] ?? [];
|
|
56
|
+
if (fields.length === 0) return;
|
|
57
|
+
|
|
58
|
+
const userId = DataIsolationContext.getStore()?.userId;
|
|
59
|
+
const values: Record<string, unknown> = {};
|
|
60
|
+
|
|
61
|
+
for (const entry of fields) {
|
|
62
|
+
delete (data as Record<string, unknown>)[entry.field];
|
|
63
|
+
|
|
64
|
+
if (vexFieldPhaseOf(entry.type) !== phase) continue;
|
|
65
|
+
|
|
66
|
+
const value = resolveVexFieldValue(entry.type, userId);
|
|
67
|
+
if (value !== undefined) values[entry.field] = value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
Object.assign(data, values);
|
|
71
|
+
}
|
|
72
|
+
|
|
11
73
|
/** Build ownership filter from current request context, or null. */
|
|
12
74
|
private getOwnershipFilter(): Record<string, unknown> | null {
|
|
13
75
|
const store = DataIsolationContext.getStore();
|
|
14
76
|
if (!store?.userId) return null;
|
|
15
77
|
|
|
16
|
-
const
|
|
17
|
-
? this.repo.metadata.target.name
|
|
18
|
-
: "";
|
|
19
|
-
const config = entityIsolation[entityName];
|
|
78
|
+
const config = entityIsolation[this.getEntityName()];
|
|
20
79
|
if (!config) return null;
|
|
21
80
|
|
|
22
81
|
return { [config.field]: store.userId };
|
|
@@ -141,14 +200,12 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
141
200
|
const enriched = { ...data };
|
|
142
201
|
const store = DataIsolationContext.getStore();
|
|
143
202
|
if (store?.userId) {
|
|
144
|
-
const
|
|
145
|
-
? this.repo.metadata.target.name
|
|
146
|
-
: "";
|
|
147
|
-
const config = entityIsolation[entityName];
|
|
203
|
+
const config = entityIsolation[this.getEntityName()];
|
|
148
204
|
if (config && config.field !== "_id") {
|
|
149
|
-
(enriched as
|
|
205
|
+
(enriched as Record<string, unknown>)[config.field] = store.userId;
|
|
150
206
|
}
|
|
151
207
|
}
|
|
208
|
+
this.applyVexFields(enriched, "create");
|
|
152
209
|
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
153
210
|
}
|
|
154
211
|
|
|
@@ -157,9 +214,11 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
157
214
|
utils.log.error("TypeOrmRepositoryAdapter.replace called without id — refuse replace entity");
|
|
158
215
|
return null;
|
|
159
216
|
}
|
|
217
|
+
const enriched = { ...data };
|
|
218
|
+
this.applyVexFields(enriched, "update");
|
|
160
219
|
const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
|
|
161
220
|
if (!existing) return null;
|
|
162
|
-
return this.repo.save(this.repo.merge(existing,
|
|
221
|
+
return this.repo.save(this.repo.merge(existing, enriched as DeepPartial<T>));
|
|
163
222
|
}
|
|
164
223
|
|
|
165
224
|
async update(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
@@ -167,8 +226,10 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
167
226
|
utils.log.error("TypeOrmRepositoryAdapter.update called without id — refuse update entity");
|
|
168
227
|
return null;
|
|
169
228
|
}
|
|
229
|
+
const enriched = { ...data };
|
|
230
|
+
this.applyVexFields(enriched, "update");
|
|
170
231
|
const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
|
|
171
|
-
await this.repo.update(where as FindOptionsWhere<T>,
|
|
232
|
+
await this.repo.update(where as FindOptionsWhere<T>, enriched);
|
|
172
233
|
return this.findOne({ _id: id } as unknown as Filter<T>);
|
|
173
234
|
}
|
|
174
235
|
|
|
@@ -11,6 +11,7 @@ import { VexRepository, VexResErr } from "../../_types/vex";
|
|
|
11
11
|
import VexDb from "../VexDb.gen";
|
|
12
12
|
import { UserEntity, UserWithRelations } from "../../_models/UserModel.gen";
|
|
13
13
|
import { SessionEntity, Session } from "../../_models/SessionModel.gen";
|
|
14
|
+
import { vexUserIdField } from "../../_middlewares/VexFieldRegistry.gen";
|
|
14
15
|
|
|
15
16
|
interface tokenObj {
|
|
16
17
|
token: string,
|
|
@@ -18,6 +19,11 @@ interface tokenObj {
|
|
|
18
19
|
clientIndex?: string
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
function rolesOf(user: unknown): string[] {
|
|
23
|
+
const relation = (user as { userRole?: Array<{ role: string }> }).userRole;
|
|
24
|
+
return Array.isArray(relation) ? relation.map((r) => r.role) : [];
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export default class JWTService {
|
|
22
28
|
private keyStore = new JWTKeyStore();
|
|
23
29
|
|
|
@@ -88,8 +94,8 @@ export default class JWTService {
|
|
|
88
94
|
|
|
89
95
|
public returnToken(userProfile: UserWithRelations) {
|
|
90
96
|
const sanitizedProfile = this.sanitizeUser(userProfile);
|
|
91
|
-
const accessToken = this.generateToken(
|
|
92
|
-
const refreshToken = this.generateToken({
|
|
97
|
+
const accessToken = this.generateToken(this.tokenPayload(userProfile), undefined, process.env.ACCESS_TOKEN_EXPIRE_TIME);
|
|
98
|
+
const refreshToken = this.generateToken({ vexUserId: this.userIdOf(userProfile) }, 0, process.env.REFRESH_TOKEN_EXPIRE_TIME);
|
|
93
99
|
|
|
94
100
|
return {
|
|
95
101
|
profile: sanitizedProfile,
|
|
@@ -102,13 +108,35 @@ export default class JWTService {
|
|
|
102
108
|
|
|
103
109
|
/** utils */
|
|
104
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Identity value of a user record: the field tagged `x-vexData: "userId"` in the schemas,
|
|
113
|
+
* with `_id` as the fallback. This is what every audit field (createdBy / updatedBy) stores.
|
|
114
|
+
*/
|
|
115
|
+
public userIdOf(user: UserWithRelations): string | undefined {
|
|
116
|
+
const raw = user as unknown as Record<string, unknown>;
|
|
117
|
+
return (raw[vexUserIdField] as string | undefined) ?? user._id;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Access-token payload: the public profile plus the identity claims the DB layer reads.
|
|
122
|
+
* The profile itself is unchanged, so API responses keep their existing shape.
|
|
123
|
+
* Roles are a signing-time snapshot, which is why they belong to the short-lived access token only.
|
|
124
|
+
*/
|
|
125
|
+
public tokenPayload(user: UserWithRelations) {
|
|
126
|
+
return {
|
|
127
|
+
...this.sanitizeUser(user),
|
|
128
|
+
vexUserId: this.userIdOf(user),
|
|
129
|
+
vexRole: rolesOf(user)
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
105
133
|
public sanitizeUser(user: UserWithRelations) {
|
|
106
134
|
return {
|
|
107
135
|
_id: user._id,
|
|
108
136
|
email: user.email,
|
|
109
137
|
name: user.name,
|
|
110
138
|
locale: user.locale,
|
|
111
|
-
roles: user
|
|
139
|
+
roles: rolesOf(user),
|
|
112
140
|
profileErrors: user.profileErrors,
|
|
113
141
|
active: user.active
|
|
114
142
|
};
|
|
@@ -139,7 +167,7 @@ export default class JWTService {
|
|
|
139
167
|
|
|
140
168
|
public async generateAccessToken(user: UserWithRelations, index?: number): Promise<tokenObj> {
|
|
141
169
|
|
|
142
|
-
const userInfo = this.
|
|
170
|
+
const userInfo = this.tokenPayload(user);
|
|
143
171
|
|
|
144
172
|
return this.generateToken(userInfo, index, process.env.ACCESS_TOKEN_EXPIRE_TIME);
|
|
145
173
|
}
|
|
@@ -10,14 +10,15 @@ import { Select, Filter, Join, VexPagination } from "./VexRequest.gen";
|
|
|
10
10
|
* DB-agnostic repository interface.
|
|
11
11
|
* Controllers and services talk only to this — the adapter layer (TypeORM/Mongoose) absorbs DB specifics.
|
|
12
12
|
*/
|
|
13
|
-
export interface VexRepository<T> {
|
|
14
|
-
find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]>;
|
|
13
|
+
export interface VexRepository<T, U=undefined> {
|
|
14
|
+
find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<[U] extends [undefined] ? T[] : U[]>;
|
|
15
15
|
count(filter: Filter<T>): Promise<number>;
|
|
16
|
-
findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
|
|
17
|
-
findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
|
|
16
|
+
findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
17
|
+
findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
18
18
|
create(data: Partial<T>): Promise<T>;
|
|
19
19
|
replace(id: string | undefined, data: Partial<T>): Promise<T | null>;
|
|
20
20
|
update(id: string | undefined, data: Partial<T>): Promise<T | null>;
|
|
21
21
|
delete(id: string | undefined): Promise<void>;
|
|
22
22
|
deleteWhere(filter: Filter<T>): Promise<void>;
|
|
23
23
|
}
|
|
24
|
+
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"properties": {
|
|
26
26
|
"_id": {
|
|
27
27
|
"type": "string",
|
|
28
|
-
"x-format": "
|
|
28
|
+
"x-format": "PrimaryUUID",
|
|
29
|
+
"x-vexData": "userId",
|
|
29
30
|
"index": true
|
|
30
31
|
},
|
|
31
32
|
"email": {
|
|
@@ -49,6 +50,21 @@
|
|
|
49
50
|
},
|
|
50
51
|
"profileErrors": {
|
|
51
52
|
"type": "string"
|
|
53
|
+
},
|
|
54
|
+
"createdAt": {
|
|
55
|
+
"type": "string",
|
|
56
|
+
"x-format": "Timestamp",
|
|
57
|
+
"default": "onCreateTimestamp"
|
|
58
|
+
},
|
|
59
|
+
"updatedAt": {
|
|
60
|
+
"type": "string",
|
|
61
|
+
"x-format": "Timestamp",
|
|
62
|
+
"default": "onUpdateTimestamp"
|
|
63
|
+
},
|
|
64
|
+
"updatedBy": {
|
|
65
|
+
"type": "string",
|
|
66
|
+
"x-format": "UUID",
|
|
67
|
+
"default": "onUpdateUserId"
|
|
52
68
|
}
|
|
53
69
|
},
|
|
54
70
|
"required": [
|
package/docs/CONTRIBUTING.md
CHANGED
|
@@ -16,9 +16,10 @@ npm run dev
|
|
|
16
16
|
## Workflow
|
|
17
17
|
- Fork repository
|
|
18
18
|
- Create branch `feature/<name>` or `fix/<ticket>`
|
|
19
|
-
- Run linter and build before PR:
|
|
19
|
+
- Run linter, tests and build before PR:
|
|
20
20
|
```
|
|
21
21
|
npm run lint
|
|
22
|
+
npm test
|
|
22
23
|
npm run build
|
|
23
24
|
```
|
|
24
25
|
- Submit PR with clear description and tests (if applicable).
|
|
@@ -26,13 +27,17 @@ npm run build
|
|
|
26
27
|
## Code style
|
|
27
28
|
- TypeScript: prefer explicit types, avoid `any` where possible.
|
|
28
29
|
- Split large functions into small chunks.
|
|
29
|
-
- Keep templates in `templates/`, generators in `src/generators/`, types in `src/types`.
|
|
30
|
+
- Keep static templates in `src/templates/`, generators in `src/generators/`, types in `src/types`.
|
|
31
|
+
- Never hand-edit generated `*.gen.ts` files — see [AGENTS.md](../AGENTS.md).
|
|
30
32
|
## JSON Schema contributions
|
|
31
|
-
-
|
|
33
|
+
- Working schemas live in `vex.config.json → jsonSchemaDir` (this repo: `output/jsonSchema`).
|
|
34
|
+
- Sample schemas are re-copied from `src/templates/jsonSchema/` on every generation run — edit them there to make a schema stick.
|
|
32
35
|
- `x-documentConfig.documentName` must match filename (see docs/vexJsonSchema.md).
|
|
33
36
|
|
|
34
37
|
## PR checklist
|
|
35
38
|
- Lint passes
|
|
39
|
+
- Tests pass (`npm test`)
|
|
36
40
|
- Build succeeds
|
|
37
41
|
- Relevant docs updated
|
|
42
|
+
- If generated output changed intentionally, goldens regenerated with `npm run test:update` and the diff reviewed
|
|
38
43
|
- output app can run
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Auth & Routing Generation
|
|
2
|
+
|
|
3
|
+
Routes come from three generators in `src/generators/routes/`. `routes.generator.ts` is the entry; it emits auth and swagger routes and leaves the API routes to tsoa.
|
|
4
|
+
|
|
5
|
+
## TSOA integration
|
|
6
|
+
|
|
7
|
+
Generation writes `tsoa.json` into the output root, so the `tsoa` CLI produces Express routes + an OpenAPI spec from controller decorators. Controllers use `@Route`, `@Get`, `@Post`, `@Security`, `@Tags`, `@Middlewares`.
|
|
8
|
+
|
|
9
|
+
Route path is always `documentName.toLowerCase()`:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
@Route("user") // from documentName "User"
|
|
13
|
+
@Tags("User") // raw documentName
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Auth middleware for the generated app: `src/templates/_middlewares/tsoaAuthentication.ts`, handling the `BearerAuth` and `AuthIndex` security schemes.
|
|
17
|
+
|
|
18
|
+
### Both credentials are required
|
|
19
|
+
|
|
20
|
+
Secured operations need **both**:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
Authorization: Bearer <accessToken>
|
|
24
|
+
X-Auth-Index: <accessTokenIndex>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
(`accessTokenIndex` comes back from the token endpoint alongside `accessToken`; it
|
|
28
|
+
selects the rolling JWT key slot.) Sending only one header returns 401.
|
|
29
|
+
|
|
30
|
+
Controllers declare this as a single security requirement object:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
@Security({ BearerAuth: [], AuthIndex: [] })
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
OpenAPI reads one requirement object listing two schemes as **AND**; two separate
|
|
37
|
+
`@Security("BearerAuth")` / `@Security("AuthIndex")` decorators produce two requirement
|
|
38
|
+
objects, which means **OR** — i.e. "either credential suffices", contradicting the
|
|
39
|
+
middleware. The single-object form keeps the emitted spec honest.
|
|
40
|
+
|
|
41
|
+
Note `/api/auth/token` is **not** a login endpoint: it takes `?code=` from a session and
|
|
42
|
+
exchanges it for tokens. Local login goes through `/api/auth/local`, which answers 302
|
|
43
|
+
with `{ result: { url: "...?code=..." } }`.
|
|
44
|
+
|
|
45
|
+
The `@Security` decorator and its tsoa import are both gated on auth being enabled;
|
|
46
|
+
they must use the same condition, or the generated controller references an
|
|
47
|
+
unimported decorator.
|
|
48
|
+
|
|
49
|
+
## Route kinds
|
|
50
|
+
|
|
51
|
+
| Kind | Output | Generator |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| **API routes** | generated by tsoa from controller decorators | `src/generators/controller/controller.template.ts` |
|
|
54
|
+
| **Auth (tsoa)** | `_controllers/AuthController.gen.ts` — login, register, token refresh at `/api/auth/*` | `routes/auth.generator.ts` → `compileController()` |
|
|
55
|
+
| **Auth (express)** | `_routes/AuthRouter.gen.ts` — OAuth passport redirect flows at `/auth/<provider>` | `routes/auth.generator.ts` → `compileRouter()` |
|
|
56
|
+
| **Swagger UI** | `_routes/SwaggerRouter.gen.ts` — serves OpenAPI spec + UI | `routes/swagger.generator.ts` |
|
|
57
|
+
|
|
58
|
+
Conditional emission:
|
|
59
|
+
|
|
60
|
+
- `AuthController.gen.ts` — only when `utils.generator.isAuthEnabled(options)` (i.e. `auth.localAuth`)
|
|
61
|
+
- `AuthRouter.gen.ts` — additionally requires at least one OAuth provider to be enabled (`hasOAuthProviders()`); supported providers come from `utils.generator.OAuthProviders`
|
|
62
|
+
- `SwaggerRouter.gen.ts` — only when `app.enableSwagger` is true
|
|
63
|
+
|
|
64
|
+
## Config knobs (`vex.config.json`)
|
|
65
|
+
|
|
66
|
+
```jsonc
|
|
67
|
+
{
|
|
68
|
+
"app": { "enableSwagger": true },
|
|
69
|
+
"auth": {
|
|
70
|
+
"localAuth": true,
|
|
71
|
+
"useHttpOnlyCookieToken": true,
|
|
72
|
+
"oauthProviders": { "google": false, "github": false }
|
|
73
|
+
},
|
|
74
|
+
"useRBAC": { "roles": ["visitor", "member", "admin"], "default": "admin" }
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
RBAC is **opt-in**: it is generated only when `useRBAC` is present *and* declares at
|
|
79
|
+
least one role (`utils.generator.isRbacEnabled`). Omitting the key, or passing
|
|
80
|
+
`"roles": []`, generates the app with no RBAC at all — no `RoleBaseAccessControl`, no
|
|
81
|
+
`_roles/`, no `UserRole` model. See
|
|
82
|
+
[`generatorPipeline.md`](generatorPipeline.md#rbac-is-opt-in).
|
|
83
|
+
|
|
84
|
+
When RBAC is on, `src/templates/jsonSchemaRBAC/` is copied over the sample schemas and
|
|
85
|
+
`UserRole.role`'s enum is synced from `useRBAC.roles`.
|
|
86
|
+
|
|
87
|
+
## Auth internals
|
|
88
|
+
|
|
89
|
+
JWT rolling keys and OAuth2 provider setup are documented in [`docs/appGenerated/auth.md`](../appGenerated/auth.md).
|
|
90
|
+
|
|
91
|
+
## Client-facing API behaviour
|
|
92
|
+
|
|
93
|
+
Pagination, search and the response envelope: [`docs/apiUsage.md`](../apiUsage.md).
|
|
94
|
+
|
|
95
|
+
Filter DSL for `find` / `count`: [`docs/features/filterOperators.md`](../features/filterOperators.md).
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Database Targets, Repository Layer & Data Isolation
|
|
2
|
+
|
|
3
|
+
## Target selection
|
|
4
|
+
|
|
5
|
+
`vex.config.json → dbType`:
|
|
6
|
+
|
|
7
|
+
| Value | Model generator |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `"mongo"` | `src/generators/db/mongooseModel.generator.ts` |
|
|
10
|
+
| `"sql"` | `src/generators/db/typeormEntity.generator.ts` |
|
|
11
|
+
|
|
12
|
+
The generated app's DB target is fixed at generation time.
|
|
13
|
+
|
|
14
|
+
### SQL schema creation
|
|
15
|
+
|
|
16
|
+
Schemas come from TypeORM `synchronize` at generated-app startup, controlled by the `SQL_SYNCHRONIZE` env var and wired in `_services/VexDbConnector.ts`.
|
|
17
|
+
|
|
18
|
+
The Knex-based `src/generators/db/sqlMigration.generator.ts` is **legacy/disabled**. Both its import and its call in `src/index.ts` are commented out, along with the `sqlMigrations` runner in `VexDbConnector.ts`. Do not treat it as live code.
|
|
19
|
+
|
|
20
|
+
## Repository adapter pattern
|
|
21
|
+
|
|
22
|
+
Controllers never touch the ORM/ODM directly. They call `VexDb.getRepository(Entity)`, which returns a `VexRepository<T>`.
|
|
23
|
+
|
|
24
|
+
Interface: `src/templates/_types/vex/VexRepository.ts`
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
find(filter, join?, select?, pagination?) count(filter)
|
|
28
|
+
findOne(filter, join?, select?) findOneWhere(filter, join?, select?)
|
|
29
|
+
create(data) replace(id, data)
|
|
30
|
+
update(id, data) delete(id)
|
|
31
|
+
deleteWhere(filter)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`join` and `select` are optional on the `find` variants; the generic `U` parameter carries the joined/selected shape.
|
|
35
|
+
|
|
36
|
+
| Adapter | Target | Notes |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| `src/templates/_services/TypeOrmRepositoryAdapter.ts` | SQL | Maps `$and` / `$or` / `$like` / `$gt` etc. → TypeORM `FindOptions`. Applies the data-isolation ownership filter |
|
|
39
|
+
| `src/templates/_services/MongooseRepositoryAdapter.ts` | Mongo | Thin wrapper. Join, select, pagination and count are largely TODO — Mongoose support is less mature than SQL |
|
|
40
|
+
|
|
41
|
+
Both are static templates — file extensions are `.ts` in-repo, copied as `.gen.ts` into the generated app.
|
|
42
|
+
|
|
43
|
+
### The Mongo target does not currently type-check
|
|
44
|
+
|
|
45
|
+
`npm run test:e2e` compiles a generated app per config variant. The Mongoose variant
|
|
46
|
+
is asserted with `it.fails` because it fails with **8 TypeScript errors with auth off
|
|
47
|
+
and 11 with it on**. These are independent of RBAC and of auth being enabled:
|
|
48
|
+
|
|
49
|
+
| Error | Where |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `declares 'User' locally, but it is not exported` | `_models/*Model.gen.ts` do not re-export the entity types their importers expect (the TypeORM generator does: `export * from "./../_types/User.gen"`) |
|
|
52
|
+
| `has no exported member 'UserWithRelations'` | same — the relations type is not surfaced by the Mongoose model template |
|
|
53
|
+
| `'{ type: StringConstructor, … ref: {...} }' is not assignable to 'SchemaDefinitionProperty'` | Mongoose model template's `ref` shape |
|
|
54
|
+
| `VexRepository<UserDocument…> is not assignable to VexRepository<User>` | the Mongoose adapter's generics |
|
|
55
|
+
|
|
56
|
+
Consequence: `vex` with `dbType: "mongo"` produces an app that cannot be built with
|
|
57
|
+
`npm run build` (`tsc -p .`). The golden scenarios still cover the mongo *output text*,
|
|
58
|
+
which is why this went unnoticed — goldens compare text, they do not compile.
|
|
59
|
+
|
|
60
|
+
`test/e2e/compile.test.ts` turns red once the Mongoose target compiles, as a prompt to
|
|
61
|
+
move it into the passing variant matrix.
|
|
62
|
+
|
|
63
|
+
## Filter operators
|
|
64
|
+
|
|
65
|
+
The SQL adapter maps the filter DSL (`$and`, `$or`, `$like`, `$in`, comparison operators) onto TypeORM `FindOptions`. See [`docs/features/filterOperators.md`](../features/filterOperators.md).
|
|
66
|
+
|
|
67
|
+
## Data isolation (row-level ownership)
|
|
68
|
+
|
|
69
|
+
Declared per entity in `x-documentConfig → dataIsolation: { field: "ownerId" }`.
|
|
70
|
+
|
|
71
|
+
Generation produces three pieces:
|
|
72
|
+
|
|
73
|
+
1. `DataIsolationRegistry.gen.ts` (`src/generators/middlewares/dataIsolationRegistry.generator.ts`) — entity → ownership-field map
|
|
74
|
+
2. `DataIsolationContext.ts` middleware — `AsyncLocalStorage` carrying the current user through the request pipeline
|
|
75
|
+
3. The TypeORM adapter reads the user ID from that context and injects `{ [field]: userId }` into every query — transparent row-level ownership, no per-controller code
|
|
76
|
+
|
|
77
|
+
Full guide: [`docs/features/dataIsolation.md`](../features/dataIsolation.md).
|
|
78
|
+
|
|
79
|
+
## Auto-written audit fields
|
|
80
|
+
|
|
81
|
+
Columns declared with a reserved `default` keyword (`onCreateTimestamp`, `onUpdateUserId`, …) are filled by
|
|
82
|
+
the repository adapters on `create` / `update` / `replace` — a shared helper strips client-supplied values
|
|
83
|
+
first, then injects per write phase. Both targets implement it; the entity → field map comes from
|
|
84
|
+
`VexFieldRegistry.gen.ts` (`src/generators/middlewares/vexFieldRegistry.generator.ts`), which also exports the
|
|
85
|
+
`x-vexData: "userId"` identity field the token pipeline reads.
|
|
86
|
+
|
|
87
|
+
Guide: [`docs/features/auditFields.md`](../features/auditFields.md).
|
|
88
|
+
|
|
89
|
+
## Join whitelist
|
|
90
|
+
|
|
91
|
+
`src/generators/middlewares/joinWhitelistRegistry.generator.ts` emits a static entity → allowed-joins map consumed by `JoinWhitelistMiddleware.ts`. Populated from `x-documentConfig.restApi.joinWhitelist`; auto-filled by `jsonSchemaForeignKeys.ts` when unset. Controllers with a whitelist get `@Middlewares(JoinWhitelistMiddleware.middleware("<DocName>"))`.
|
|
92
|
+
|
|
93
|
+
See [`docs/features/joinWhitelist.md`](../features/joinWhitelist.md) and [`docs/ForeignKey.md`](../ForeignKey.md).
|
|
94
|
+
|
|
95
|
+
## RBAC
|
|
96
|
+
|
|
97
|
+
`src/generators/middlewares/RBACmiddleware.generator.ts` produces `RoleBaseAccessControl.gen.ts`, enforcing per-document CRUD permissions from the role JSON files. Role sources live in `src/roles/` (user-editable); `roleDefinitions.ts` keeps per-role files present with default permissions.
|
|
98
|
+
|
|
99
|
+
See [`docs/features/rbac.md`](../features/rbac.md).
|