very-express 0.8.3 → 0.8.4
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 +1 -1
- package/dist/index.js +548 -373
- package/dist/templates/_middlewares/Authentication.ts +49 -32
- package/dist/templates/_routes/LoginUI.ts +49 -0
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +67 -5
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +70 -4
- package/dist/templates/_services/oauth/OAuthProfileMap.ts +25 -6
- package/dist/templates/_types/auth.ts +15 -0
- package/dist/templates/_types/vex/VexRepository.ts +21 -0
- package/dist/templates/jsonSchema/User.json +8 -1
- package/dist/templates/root/public/js/deleteaccount.js +80 -0
- package/docs/architecture/authAndRouting.md +8 -1
- package/docs/features/accountDeletion.md +150 -0
- package/docs/features/auditFields.md +0 -30
- package/docs/vexJsonSchema.md +11 -1
- package/package.json +1 -1
- package/vex.config.json +3 -1
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { Request, Response, NextFunction } from "express";
|
|
3
3
|
import { JsonWebTokenError } from "jsonwebtoken";
|
|
4
4
|
import JWTService from "../_services/auth/JWTService.gen";
|
|
5
|
-
import
|
|
5
|
+
import { isActiveIdentity } from "../_services/auth/AccountStateGuard.gen";
|
|
6
|
+
import UserContext, { userIdOfToken } from "./UserContext.gen";
|
|
6
7
|
import log from "../_utils/logger.gen";
|
|
7
8
|
import { VexResErr } from "../_types/vex";
|
|
8
9
|
|
|
@@ -10,38 +11,54 @@ class Authentication {
|
|
|
10
11
|
|
|
11
12
|
private JWTService = new JWTService();
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Express request handler.
|
|
16
|
+
*
|
|
17
|
+
* Deliberately NOT `async`: both call sites are express chains — `@Middlewares(...)`, which the
|
|
18
|
+
* tsoa route file spreads as a plain RequestHandler, and `router.use(...)`. Express 4 does not
|
|
19
|
+
* catch a rejected promise, so an async handler would turn every failure into an unhandled
|
|
20
|
+
* rejection instead of a response. The asynchronous part lives in `handle()` and every outcome
|
|
21
|
+
* is routed to `next()`.
|
|
22
|
+
*/
|
|
23
|
+
public middleware = (req: Request, res: Response, next: NextFunction): void => {
|
|
24
|
+
this.handle(req, next).catch((e: unknown) => next(this.toVexErr(e)));
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
private async handle(req: Request, next: NextFunction): Promise<void> {
|
|
28
|
+
// gate keeper
|
|
29
|
+
// log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
|
|
30
|
+
const token = req.headers.authorization?.split(" ")[1];
|
|
31
|
+
const accessTokenIndex = req.headers["x-auth-index"]?.toString();
|
|
32
|
+
|
|
33
|
+
if (!token || !accessTokenIndex) {
|
|
34
|
+
log.warn("invalid header", {
|
|
35
|
+
"X-Auth-Index": req.headers["x-auth-index"],
|
|
36
|
+
"Authorization": req.headers.authorization
|
|
37
|
+
});
|
|
38
|
+
throw 401;
|
|
32
39
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
40
|
+
|
|
41
|
+
// verify token
|
|
42
|
+
const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
|
|
43
|
+
|
|
44
|
+
// The signature only proves the token was issued; it says nothing about the account still
|
|
45
|
+
// being there. A deleted account is soft-deleted, so this check is what stops its token
|
|
46
|
+
// from working for the rest of its lifetime.
|
|
47
|
+
if (!(await isActiveIdentity(userIdOfToken(tokenData)))) {
|
|
48
|
+
throw new VexResErr(401, undefined, "Account is not active");
|
|
43
49
|
}
|
|
44
|
-
|
|
50
|
+
|
|
51
|
+
req.user = tokenData;
|
|
52
|
+
UserContext.run(tokenData, () => next());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private toVexErr(e: unknown): VexResErr {
|
|
56
|
+
if (typeof e === "number") return new VexResErr(e, undefined);
|
|
57
|
+
if (e instanceof VexResErr) return e;
|
|
58
|
+
if (e instanceof JsonWebTokenError) return new VexResErr(400, undefined, e?.message);
|
|
59
|
+
|
|
60
|
+
return new VexResErr(500, undefined, e instanceof Error ? e.message : undefined);
|
|
61
|
+
}
|
|
45
62
|
}
|
|
46
63
|
|
|
47
|
-
export default new Authentication();
|
|
64
|
+
export default new Authentication();
|
|
@@ -5,6 +5,13 @@ import crypto from "crypto";
|
|
|
5
5
|
export interface LoginUIConfig {
|
|
6
6
|
localAuth: boolean;
|
|
7
7
|
oauthProviders: string[];
|
|
8
|
+
/**
|
|
9
|
+
* Serve the self-service deletion page at `/delete_account`.
|
|
10
|
+
*
|
|
11
|
+
* Optional and defaulting to true so an app generated before this feature existed still
|
|
12
|
+
* constructs — its `server.ts` is generated once and is not overwritten on later runs.
|
|
13
|
+
*/
|
|
14
|
+
deleteAccount?: boolean;
|
|
8
15
|
}
|
|
9
16
|
|
|
10
17
|
export default class LoginUI {
|
|
@@ -21,6 +28,10 @@ export default class LoginUI {
|
|
|
21
28
|
return this.router;
|
|
22
29
|
}
|
|
23
30
|
|
|
31
|
+
private get deleteAccountEnabled(): boolean {
|
|
32
|
+
return this.config.deleteAccount ?? true;
|
|
33
|
+
}
|
|
34
|
+
|
|
24
35
|
private registerRoutes(): void {
|
|
25
36
|
this.router.get("/", this.homePage.bind(this));
|
|
26
37
|
this.router.get("/login", this.loginPage.bind(this));
|
|
@@ -28,6 +39,9 @@ export default class LoginUI {
|
|
|
28
39
|
this.router.get("/mytokens", this.myTokensPage.bind(this));
|
|
29
40
|
this.router.get("/refreshtoken", this.refreshTokenPage.bind(this));
|
|
30
41
|
this.router.get("/logincallback", this.loginCallbackPage.bind(this));
|
|
42
|
+
if (this.deleteAccountEnabled) {
|
|
43
|
+
this.router.get("/delete_account", this.deleteAccountPage.bind(this));
|
|
44
|
+
}
|
|
31
45
|
}
|
|
32
46
|
|
|
33
47
|
private nonce(): string {
|
|
@@ -42,11 +56,16 @@ export default class LoginUI {
|
|
|
42
56
|
<li><a href="/logout">LogOut</a></li>`
|
|
43
57
|
: "";
|
|
44
58
|
|
|
59
|
+
const deleteAccountLink = this.deleteAccountEnabled
|
|
60
|
+
? `<li><a href="/delete_account">Delete account</a></li>`
|
|
61
|
+
: "";
|
|
62
|
+
|
|
45
63
|
res.send(`
|
|
46
64
|
<div>
|
|
47
65
|
<h1>Hello World</h1>
|
|
48
66
|
<ul>
|
|
49
67
|
${authLinks}
|
|
68
|
+
${deleteAccountLink}
|
|
50
69
|
<li><a href="/swagger">Swagger UI</a></li>
|
|
51
70
|
</ul>
|
|
52
71
|
<h1>Others</h1>
|
|
@@ -145,4 +164,34 @@ export default class LoginUI {
|
|
|
145
164
|
</body>
|
|
146
165
|
`);
|
|
147
166
|
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Self-service account deletion.
|
|
170
|
+
*
|
|
171
|
+
* The copy is deliberately explicit about what survives: this is a tombstone, not an erasure of
|
|
172
|
+
* everything. Claiming otherwise would contradict both the implementation and the store listing.
|
|
173
|
+
*/
|
|
174
|
+
private deleteAccountPage(_req: Request, res: Response): void {
|
|
175
|
+
const nonce = this.nonce();
|
|
176
|
+
res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
|
|
177
|
+
res.send(`
|
|
178
|
+
<link rel="stylesheet" href="/css/style.css">
|
|
179
|
+
<body>
|
|
180
|
+
<h1>Delete account</h1>
|
|
181
|
+
<p><strong>This cannot be undone.</strong></p>
|
|
182
|
+
<p>
|
|
183
|
+
You will need to create a new account to use the service again; the same
|
|
184
|
+
sign-in provider will not restore this one.
|
|
185
|
+
</p>
|
|
186
|
+
<p>Type <code>DELETE</code> to confirm:</p>
|
|
187
|
+
<input type="text" id="confirmInput" autocomplete="off"/>
|
|
188
|
+
<br/><br/>
|
|
189
|
+
<button id="deleteAccountBtn">Delete my account</button>
|
|
190
|
+
<br/><br/>
|
|
191
|
+
<pre id="deleteResult"></pre>
|
|
192
|
+
<a href="/">back to home</a>
|
|
193
|
+
</body>
|
|
194
|
+
<script nonce="${nonce}" src="/js/deleteaccount.js"></script>
|
|
195
|
+
`);
|
|
196
|
+
}
|
|
148
197
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Model, Document } from "mongoose";
|
|
3
3
|
import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
|
-
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
5
|
+
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
6
|
import utils from "../_utils";
|
|
7
7
|
|
|
8
8
|
/** When a framework-managed field is written. */
|
|
@@ -84,9 +84,34 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
84
84
|
return this.model;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Entity class name — the key used by the generated registries. */
|
|
88
|
+
private getEntityName(): string {
|
|
89
|
+
return this.model.modelName + "Entity";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Soft-delete term for this model, or null when it declares no marker.
|
|
94
|
+
*
|
|
95
|
+
* `$ne: true` (not `$eq: false`) so documents written before the field existed still count as
|
|
96
|
+
* live — the same leniency the SQL side gets from NOT NULL DEFAULT false.
|
|
97
|
+
*/
|
|
98
|
+
private getSoftDeleteFilter(): Record<string, unknown> | null {
|
|
99
|
+
if (showSoftDeleted) return null;
|
|
100
|
+
|
|
101
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
102
|
+
if (!field) return null;
|
|
103
|
+
|
|
104
|
+
return { [field]: { $ne: true } };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private mergeFilter(filter: Filter, options?: { includeSoftDeleted?: boolean }): Record<string, unknown> {
|
|
108
|
+
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
109
|
+
return { ...((filter || {}) as Record<string, unknown>), ...softDelete };
|
|
110
|
+
}
|
|
111
|
+
|
|
87
112
|
find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
88
113
|
// TODO: complete mongoose support, handle join, select, and pagination
|
|
89
|
-
return this.model.find((filter
|
|
114
|
+
return this.model.find(this.mergeFilter(filter) as any).exec();
|
|
90
115
|
}
|
|
91
116
|
|
|
92
117
|
async count(filter: Filter): Promise<number> {
|
|
@@ -96,12 +121,12 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
96
121
|
|
|
97
122
|
findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
98
123
|
// TODO: complete mongoose support, handle join and select
|
|
99
|
-
return this.model.findOne(filter as any).exec();
|
|
124
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
100
125
|
}
|
|
101
126
|
|
|
102
127
|
findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
103
128
|
// TODO: complete mongoose support, handle join and select
|
|
104
|
-
return this.model.findOne(filter as any).exec();
|
|
129
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
105
130
|
}
|
|
106
131
|
|
|
107
132
|
async create(data: Partial<T>): Promise<T> {
|
|
@@ -140,6 +165,43 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
140
165
|
}
|
|
141
166
|
|
|
142
167
|
async deleteWhere(filter: Record<string, unknown>): Promise<void> {
|
|
143
|
-
await this.model.deleteOne(filter as any).exec();
|
|
168
|
+
await this.model.deleteOne(this.mergeFilter(filter as Filter) as any).exec();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Tombstone the document: run the normal update-phase field machinery (so `updatedAt` /
|
|
173
|
+
* `updatedBy` record who deleted it and when), then write the marker plus any redaction
|
|
174
|
+
* the caller merged in.
|
|
175
|
+
*/
|
|
176
|
+
async softDelete(id: string | undefined, data?: Partial<T>): Promise<T | null> {
|
|
177
|
+
if (!id) {
|
|
178
|
+
utils.log.error("MongooseRepositoryAdapter.softDelete called without id — refuse update document");
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
183
|
+
if (!field) {
|
|
184
|
+
utils.log.error(
|
|
185
|
+
`MongooseRepositoryAdapter.softDelete on ${this.getEntityName()} — entity declares no ` +
|
|
186
|
+
`x-vexData "softDelete" field, refuse update document`
|
|
187
|
+
);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
|
|
192
|
+
this.applyVexFields(enriched as Partial<T>, "update");
|
|
193
|
+
enriched[field] = true;
|
|
194
|
+
|
|
195
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
196
|
+
return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Read a document that may be soft-deleted: skips the soft-delete term only.
|
|
201
|
+
* Framework-internal — see VexRepository.
|
|
202
|
+
*/
|
|
203
|
+
findOneWithDeleted(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
204
|
+
// TODO: complete mongoose support, handle join and select
|
|
205
|
+
return this.model.findOne(this.mergeFilter(filter, { includeSoftDeleted: true }) as any).exec();
|
|
144
206
|
}
|
|
145
207
|
}
|
|
@@ -3,7 +3,7 @@ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like
|
|
|
3
3
|
import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
5
|
import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
|
|
6
|
-
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
|
+
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
7
7
|
import utils from "../_utils";
|
|
8
8
|
|
|
9
9
|
/** When a framework-managed field is written. */
|
|
@@ -98,16 +98,36 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
98
98
|
return { [config.field]: userId };
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Soft-delete term for this entity, or null when it declares no marker.
|
|
103
|
+
*
|
|
104
|
+
* `Not(true)` rather than `deleted: false`: the generated column is NOT NULL DEFAULT false, so
|
|
105
|
+
* the two are equivalent for rows written by this schema, and `Not(true)` stays correct for a
|
|
106
|
+
* row that predates the column (NULL) on a target where that can happen.
|
|
107
|
+
*/
|
|
108
|
+
private getSoftDeleteFilter(): Record<string, unknown> | null {
|
|
109
|
+
if (showSoftDeleted) return null;
|
|
110
|
+
|
|
111
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
112
|
+
if (!field) return null;
|
|
113
|
+
|
|
114
|
+
return { [field]: Not(true) };
|
|
115
|
+
}
|
|
116
|
+
|
|
101
117
|
/** Merge caller filter with ownership filter. Ownership always wins. */
|
|
102
|
-
private mergeFilter(
|
|
118
|
+
private mergeFilter(
|
|
119
|
+
callerFilter: Filter<T>,
|
|
120
|
+
options?: { includeSoftDeleted?: boolean },
|
|
121
|
+
): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
103
122
|
const mapped = this.mapOperators(callerFilter);
|
|
104
123
|
const ownership = this.getOwnershipFilter();
|
|
124
|
+
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
105
125
|
|
|
106
126
|
if (mapped instanceof Array) {
|
|
107
|
-
return mapped.map(branch => ({ ...branch, ...ownership }));
|
|
127
|
+
return mapped.map(branch => ({ ...branch, ...softDelete, ...ownership }));
|
|
108
128
|
}
|
|
109
129
|
else {
|
|
110
|
-
return { ...mapped, ...ownership };
|
|
130
|
+
return { ...mapped, ...softDelete, ...ownership };
|
|
111
131
|
}
|
|
112
132
|
}
|
|
113
133
|
|
|
@@ -263,4 +283,50 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
263
283
|
const where = this.mergeFilter(filter as unknown as Filter<T>);
|
|
264
284
|
await this.repo.delete(where as FindOptionsWhere<T>);
|
|
265
285
|
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Tombstone the row: run the normal update-phase field machinery (so `updatedAt` /
|
|
289
|
+
* `updatedBy` record who deleted it and when), then write the marker plus any redaction
|
|
290
|
+
* the caller merged in.
|
|
291
|
+
*/
|
|
292
|
+
async softDelete(id: string | undefined, data?: Partial<T>): Promise<T | null> {
|
|
293
|
+
if (!id) {
|
|
294
|
+
utils.log.error("TypeOrmRepositoryAdapter.softDelete called without id — refuse update entity");
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
299
|
+
if (!field) {
|
|
300
|
+
utils.log.error(
|
|
301
|
+
`TypeOrmRepositoryAdapter.softDelete on ${this.getEntityName()} — entity declares no ` +
|
|
302
|
+
`x-vexData "softDelete" field, refuse update entity`
|
|
303
|
+
);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const enriched = { ...(data ?? {}) } as Record<string, unknown>;
|
|
308
|
+
this.applyVexFields(enriched as Partial<T>, "update");
|
|
309
|
+
enriched[field] = true;
|
|
310
|
+
|
|
311
|
+
const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
|
|
312
|
+
// the generic ObjectLiteral constraint makes TypeORM's own _QueryDeepPartialEntity
|
|
313
|
+
// unresolvable here; `update` already accepts the same shape on the ordinary path
|
|
314
|
+
await this.repo.update(where as FindOptionsWhere<T>, enriched as never);
|
|
315
|
+
return this.repo.findOne({
|
|
316
|
+
where: { _id: id } as unknown as T
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Read a row that may be soft-deleted: skips the soft-delete term only, so the ownership
|
|
322
|
+
* filter still applies. Framework-internal — see VexRepository.
|
|
323
|
+
*/
|
|
324
|
+
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
325
|
+
const where = this.mergeFilter(filter, { includeSoftDeleted: true }) as FindOptionsWhere<T>;
|
|
326
|
+
return this.repo.findOne({
|
|
327
|
+
select,
|
|
328
|
+
where,
|
|
329
|
+
relations: join
|
|
330
|
+
});
|
|
331
|
+
}
|
|
266
332
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
import { Profile } from "passport";
|
|
3
3
|
import { UserWithRelations } from "./../../_types/User.gen";
|
|
4
|
+
import { entitySoftDeleteFields } from "./../../_middlewares/VexFieldRegistry.gen";
|
|
4
5
|
|
|
5
6
|
export interface IProfile extends Profile {
|
|
6
7
|
[key: string]: any;
|
|
@@ -24,8 +25,26 @@ export default class OAuthProfileMap {
|
|
|
24
25
|
return authProfile;
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Seed the soft-delete marker on a brand-new OAuth user.
|
|
30
|
+
*
|
|
31
|
+
* `User` is only soft-deletable in projects that tag a marker, and when they do the field is
|
|
32
|
+
* required — so the profile built here must carry it. Reusing the registry keeps this template
|
|
33
|
+
* correct for both kinds of project, including one whose marker is not named "deleted".
|
|
34
|
+
*
|
|
35
|
+
* The marker is assigned onto the finished profile rather than spread into its literal: the
|
|
36
|
+
* field name is only known at runtime, and a spread of a `Record<string, boolean>` widens the
|
|
37
|
+
* property to `boolean | undefined`, which the required `User` field rejects.
|
|
38
|
+
*/
|
|
39
|
+
private applyNewUserMarker(user: UserWithRelations): UserWithRelations {
|
|
40
|
+
const field = entitySoftDeleteFields["UserEntity"];
|
|
41
|
+
if (field) (user as unknown as Record<string, unknown>)[field] = false;
|
|
42
|
+
|
|
43
|
+
return user;
|
|
44
|
+
}
|
|
45
|
+
|
|
27
46
|
private GithubProfileMapping(oauthProfile: IProfile): UserWithRelations {
|
|
28
|
-
const user
|
|
47
|
+
const user = {
|
|
29
48
|
active: true,
|
|
30
49
|
userAuthProfiles: [{
|
|
31
50
|
provider: oauthProfile.provider,
|
|
@@ -36,12 +55,12 @@ export default class OAuthProfileMap {
|
|
|
36
55
|
email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
|
|
37
56
|
locale: undefined,
|
|
38
57
|
profileErrors: ""
|
|
39
|
-
};
|
|
58
|
+
} as unknown as UserWithRelations;
|
|
40
59
|
|
|
41
|
-
return user;
|
|
60
|
+
return this.applyNewUserMarker(user);
|
|
42
61
|
}
|
|
43
62
|
private GoogleProfileMapping(oauthProfile: IProfile): UserWithRelations {
|
|
44
|
-
const user
|
|
63
|
+
const user = {
|
|
45
64
|
active: true,
|
|
46
65
|
userAuthProfiles: [{
|
|
47
66
|
provider: oauthProfile.provider,
|
|
@@ -53,9 +72,9 @@ export default class OAuthProfileMap {
|
|
|
53
72
|
email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
|
|
54
73
|
locale: oauthProfile._json.locale || undefined,
|
|
55
74
|
profileErrors: ""
|
|
56
|
-
};
|
|
75
|
+
} as unknown as UserWithRelations;
|
|
57
76
|
|
|
58
|
-
return user;
|
|
77
|
+
return this.applyNewUserMarker(user);
|
|
59
78
|
}
|
|
60
79
|
|
|
61
80
|
}
|
|
@@ -16,4 +16,19 @@ export interface registerResponse {
|
|
|
16
16
|
|
|
17
17
|
export interface localLoginResponse {
|
|
18
18
|
url: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Row counts removed alongside the tombstone, so the caller can log and retry. */
|
|
22
|
+
export interface deleteAccountCounts {
|
|
23
|
+
authProfiles: number;
|
|
24
|
+
userRoles: number;
|
|
25
|
+
sessions: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Result of a self-service account deletion. */
|
|
29
|
+
export interface deleteAccountResponse {
|
|
30
|
+
userId: string;
|
|
31
|
+
/** When the tombstone was written (the row's updatedAt). Empty on a repeat call. */
|
|
32
|
+
tombstonedAt: string;
|
|
33
|
+
deleted: deleteAccountCounts;
|
|
19
34
|
}
|
|
@@ -20,5 +20,26 @@ export interface VexRepository<T, U=undefined> {
|
|
|
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
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Mark an entity soft-deleted, optionally merging app-level redaction into the same write.
|
|
26
|
+
*
|
|
27
|
+
* Runs the normal update-phase machinery, so `updatedAt` / `updatedBy` record who tombstoned
|
|
28
|
+
* the row and when. No-op returning null when the entity declares no marker.
|
|
29
|
+
*
|
|
30
|
+
* Only for framework-internal callers: the marker is deliberately not part of `Filter`, and
|
|
31
|
+
* it is stripped from every generated request body, so no client can reach this through the API.
|
|
32
|
+
*/
|
|
33
|
+
softDelete(id: string | undefined, data?: Partial<T>): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Read a row that may be soft-deleted.
|
|
37
|
+
*
|
|
38
|
+
* Skips ONLY the adapter's soft-delete term — the ownership filter still applies, so this is
|
|
39
|
+
* not a way around `dataIsolation`. Exists for internal state checks (account-deletion
|
|
40
|
+
* idempotency, the account-state guard); a `Filter`-level escape hatch would have been part of
|
|
41
|
+
* every HTTP filter body, which is exactly what must not be possible.
|
|
42
|
+
*/
|
|
43
|
+
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
23
44
|
}
|
|
24
45
|
|
|
@@ -65,10 +65,17 @@
|
|
|
65
65
|
"type": "string",
|
|
66
66
|
"x-format": "UUID",
|
|
67
67
|
"default": "onUpdateUserId"
|
|
68
|
+
},
|
|
69
|
+
"deleted": {
|
|
70
|
+
"type": "boolean",
|
|
71
|
+
"default": false,
|
|
72
|
+
"x-vexData": "softDelete",
|
|
73
|
+
"description": "Soft-delete marker. Framework-managed; never client-writable. Hides the row from every ordinary query unless app.showSoftDeleted is on."
|
|
68
74
|
}
|
|
69
75
|
},
|
|
70
76
|
"required": [
|
|
71
77
|
"name",
|
|
72
|
-
"active"
|
|
78
|
+
"active",
|
|
79
|
+
"deleted"
|
|
73
80
|
]
|
|
74
81
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Self-service account deletion page.
|
|
2
|
+
//
|
|
3
|
+
// Sends the access token the same way the rest of the app does — Authorization + X-Auth-Index —
|
|
4
|
+
// and clears the stored tokens on success, because the account is gone the moment the tombstone
|
|
5
|
+
// is written: keeping a token the server will now reject only produces confusing 401s.
|
|
6
|
+
|
|
7
|
+
// The page loads this script from <head>, so it must wait for the DOM: at parse time the
|
|
8
|
+
// button does not exist yet and getElementById would return null.
|
|
9
|
+
document.addEventListener("DOMContentLoaded", function () {
|
|
10
|
+
var button = document.getElementById("deleteAccountBtn");
|
|
11
|
+
var input = document.getElementById("confirmInput");
|
|
12
|
+
var result = document.getElementById("deleteResult");
|
|
13
|
+
|
|
14
|
+
if (!button || !input || !result) return;
|
|
15
|
+
|
|
16
|
+
function clearTokens() {
|
|
17
|
+
localStorage.removeItem("accessToken");
|
|
18
|
+
localStorage.removeItem("accessTokenIndex");
|
|
19
|
+
localStorage.removeItem("refreshToken");
|
|
20
|
+
localStorage.removeItem("refreshTokenIndex");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function render(data) {
|
|
24
|
+
result.textContent = JSON.stringify(data, null, 2);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
button.addEventListener("click", function () {
|
|
28
|
+
if (input.value !== "DELETE") {
|
|
29
|
+
render({ error: 'Type DELETE in the box to confirm.' });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
button.disabled = true;
|
|
34
|
+
render({ status: "Deleting…" });
|
|
35
|
+
|
|
36
|
+
fetch("/api/auth/delete-account", {
|
|
37
|
+
method: "POST",
|
|
38
|
+
credentials: "include",
|
|
39
|
+
headers: {
|
|
40
|
+
"Content-Type": "application/json",
|
|
41
|
+
"Authorization": "Bearer " + (localStorage.getItem("accessToken") || ""),
|
|
42
|
+
"X-Auth-Index": localStorage.getItem("accessTokenIndex") || "",
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
.then(function (response) {
|
|
46
|
+
// read as text first: an error response may not be JSON (a proxy or the
|
|
47
|
+
// express error handler can return HTML), and response.json() would then
|
|
48
|
+
// reject and hide the real status behind a parse error
|
|
49
|
+
return response.text().then(function (text) {
|
|
50
|
+
var body;
|
|
51
|
+
try {
|
|
52
|
+
body = text ? JSON.parse(text) : {};
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
body = { raw: text };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { ok: response.ok, status: response.status, body: body };
|
|
59
|
+
});
|
|
60
|
+
})
|
|
61
|
+
.then(function (outcome) {
|
|
62
|
+
if (!outcome.ok) {
|
|
63
|
+
render({ status: outcome.status, error: outcome.body });
|
|
64
|
+
button.disabled = false;
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
clearTokens();
|
|
69
|
+
render({
|
|
70
|
+
status: "Account deleted. You have been signed out.",
|
|
71
|
+
result: outcome.body,
|
|
72
|
+
});
|
|
73
|
+
input.value = "";
|
|
74
|
+
})
|
|
75
|
+
.catch(function (err) {
|
|
76
|
+
render({ error: String(err) });
|
|
77
|
+
button.disabled = false;
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -65,10 +65,11 @@ Conditional emission:
|
|
|
65
65
|
|
|
66
66
|
```jsonc
|
|
67
67
|
{
|
|
68
|
-
"app": { "enableSwagger": true },
|
|
68
|
+
"app": { "enableSwagger": true, "showSoftDeleted": false },
|
|
69
69
|
"auth": {
|
|
70
70
|
"localAuth": true,
|
|
71
71
|
"useHttpOnlyCookieToken": true,
|
|
72
|
+
"deleteAccount": true,
|
|
72
73
|
"oauthProviders": { "google": false, "github": false }
|
|
73
74
|
},
|
|
74
75
|
"useRBAC": { "roles": ["visitor", "member", "admin"], "default": "admin" }
|
|
@@ -84,6 +85,12 @@ least one role (`utils.generator.isRbacEnabled`). Omitting the key, or passing
|
|
|
84
85
|
When RBAC is on, `src/templates/jsonSchemaRBAC/` is copied over the sample schemas and
|
|
85
86
|
`UserRole.role`'s enum is synced from `useRBAC.roles`.
|
|
86
87
|
|
|
88
|
+
Account deletion is the opposite — **opt-out**. `auth.deleteAccount` defaults to true, so
|
|
89
|
+
`AuthController` gains `POST /api/auth/delete-account` and the UI gains `/delete_account` unless the
|
|
90
|
+
project explicitly disables it (auth must also be enabled). `app.showSoftDeleted` controls whether
|
|
91
|
+
the repository hides soft-deleted rows; unset means hidden. See
|
|
92
|
+
[`docs/features/accountDeletion.md`](../features/accountDeletion.md).
|
|
93
|
+
|
|
87
94
|
## Auth internals
|
|
88
95
|
|
|
89
96
|
JWT rolling keys and OAuth2 provider setup are documented in [`docs/appGenerated/auth.md`](../appGenerated/auth.md).
|