very-express 0.8.1 → 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.
@@ -2,6 +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 { isActiveIdentity } from "../_services/auth/AccountStateGuard.gen";
6
+ import UserContext, { userIdOfToken } from "./UserContext.gen";
5
7
  import log from "../_utils/logger.gen";
6
8
  import { VexResErr } from "../_types/vex";
7
9
 
@@ -9,38 +11,54 @@ class Authentication {
9
11
 
10
12
  private JWTService = new JWTService();
11
13
 
12
- public middleware = (req: Request, res: Response, next: NextFunction) => {
13
- try {
14
- // gate keeper
15
- // log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
16
- const token = req.headers.authorization?.split(" ")[1];
17
- const accessTokenIndex = req.headers["x-auth-index"]?.toString();
18
-
19
- if (!token || !accessTokenIndex) {
20
- log.warn("invalid header", {
21
- "X-Auth-Index": req.headers["x-auth-index"],
22
- "Authorization": req.headers.authorization
23
- });
24
- throw 401;
25
- }
26
-
27
- // verify token
28
- const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
29
- req.user = tokenData;
30
- next();
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;
31
39
  }
32
- catch (e: any) {
33
- if (typeof e === "number") {
34
- throw new VexResErr(e, undefined);
35
- }
36
- else if (e instanceof JsonWebTokenError) {
37
- throw new VexResErr(400, undefined, e?.message);
38
- }
39
- else {
40
- throw new VexResErr(500, undefined, e?.message);
41
- }
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");
42
49
  }
43
- };
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
+ }
44
62
  }
45
63
 
46
- export default new Authentication();
64
+ export default new Authentication();
@@ -0,0 +1,54 @@
1
+ // {{headerComment}}
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+
4
+ /** Identity-bearing claims carried from the verified access token. */
5
+ export interface UserContextData {
6
+ tokenData: Record<string, unknown>;
7
+ }
8
+
9
+ /**
10
+ * Pure: identity value carried by a verified access token.
11
+ *
12
+ * `vexUserId` is the schema-declared identity (the field tagged `x-vexData: "userId"`,
13
+ * which JWTService copies into the token); `_id` keeps tokens issued before that claim
14
+ * existed working.
15
+ */
16
+ export function userIdOfToken(tokenData: Record<string, unknown> | undefined): string | undefined {
17
+ return (tokenData?.vexUserId as string | undefined) ?? (tokenData?._id as string | undefined);
18
+ }
19
+
20
+ const als = new AsyncLocalStorage<UserContextData>();
21
+
22
+ class UserContext {
23
+ /**
24
+ * Enter the per-request identity context.
25
+ *
26
+ * Called ONLY by Authentication.middleware, after token verification succeeded — at
27
+ * that point a verified token always exists, so this runs unconditionally. The store
28
+ * is the request's context; whether it carries a usable identity is decided when it
29
+ * is read (`userId`), not when it is created.
30
+ *
31
+ * Never use `enterWith()`: it mutates the current execution context instead of
32
+ * scoping a new one, and leaks into whatever runs next on the same tick.
33
+ */
34
+ run<T>(tokenData: Record<string, unknown>, fn: () => T): T {
35
+ return als.run({ tokenData }, fn);
36
+ }
37
+
38
+ /** Current store from the per-request async context. */
39
+ getStore(): UserContextData | undefined {
40
+ return als.getStore();
41
+ }
42
+
43
+ /**
44
+ * Normalized identity of the authenticated caller.
45
+ *
46
+ * The data layer MUST read the identity through this accessor and never inspect the
47
+ * token shape itself — that keeps the token → identity mapping in exactly one place.
48
+ */
49
+ get userId(): string | undefined {
50
+ return userIdOfToken(als.getStore()?.tokenData);
51
+ }
52
+ }
53
+
54
+ export default new UserContext();
@@ -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
  }
@@ -1,8 +1,8 @@
1
1
  // {{headerComment}}
2
2
  import { Model, Document } from "mongoose";
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";
3
+ import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
4
+ import UserContext from "../_middlewares/UserContext.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. */
@@ -38,6 +38,21 @@ function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unk
38
38
  export class MongooseRepositoryAdapter<T extends Document> implements VexRepository<T> {
39
39
  constructor(private model: Model<T>) {}
40
40
 
41
+ /**
42
+ * Fail loud when an entity declares a create-phase user field but no identity is in
43
+ * scope — a silent NULL is exactly the failure this enforcement exists to kill.
44
+ *
45
+ * `onUpdateUserId` is deliberately NOT enforced: `updatedBy` is allowed to stay absent,
46
+ * and refusing a context-less update would also break pre-auth writes that don't touch it.
47
+ */
48
+ private assertCreateIdentity(fields: VexFieldEntry[]): void {
49
+ if (!fields.some(f => f.type === "onCreateUserId")) return;
50
+ if (UserContext.userId) return;
51
+
52
+ throw new VexResErr(500, undefined,
53
+ `${this.model.modelName} declares onCreateUserId but UserContext carries no user identity`);
54
+ }
55
+
41
56
  /**
42
57
  * Framework-managed audit fields: strip the caller's values first — a client must never
43
58
  * forge createdBy / updatedAt — then fill the ones owned by this write phase.
@@ -48,7 +63,9 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
48
63
  const fields = entityVexFields[this.model.modelName + "Entity"] ?? [];
49
64
  if (fields.length === 0) return;
50
65
 
51
- const userId = DataIsolationContext.getStore()?.userId;
66
+ if (phase === "create") this.assertCreateIdentity(fields);
67
+
68
+ const userId = UserContext.userId;
52
69
  const values: Record<string, unknown> = {};
53
70
 
54
71
  for (const entry of fields) {
@@ -67,9 +84,34 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
67
84
  return this.model;
68
85
  }
69
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
+
70
112
  find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
71
113
  // TODO: complete mongoose support, handle join, select, and pagination
72
- return this.model.find((filter || {}) as any).exec();
114
+ return this.model.find(this.mergeFilter(filter) as any).exec();
73
115
  }
74
116
 
75
117
  async count(filter: Filter): Promise<number> {
@@ -79,12 +121,12 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
79
121
 
80
122
  findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
81
123
  // TODO: complete mongoose support, handle join and select
82
- return this.model.findOne(filter as any).exec();
124
+ return this.model.findOne(this.mergeFilter(filter) as any).exec();
83
125
  }
84
126
 
85
127
  findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
86
128
  // TODO: complete mongoose support, handle join and select
87
- return this.model.findOne(filter as any).exec();
129
+ return this.model.findOne(this.mergeFilter(filter) as any).exec();
88
130
  }
89
131
 
90
132
  async create(data: Partial<T>): Promise<T> {
@@ -123,6 +165,43 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
123
165
  }
124
166
 
125
167
  async deleteWhere(filter: Record<string, unknown>): Promise<void> {
126
- 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();
127
206
  }
128
207
  }
@@ -1,9 +1,9 @@
1
1
  // {{headerComment}}
2
2
  import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, FindManyOptions } from "typeorm";
3
- import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination } from "../_types/vex";
4
- import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
3
+ import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
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. */
@@ -45,6 +45,21 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
45
45
  : "";
46
46
  }
47
47
 
48
+ /**
49
+ * Fail loud when an entity declares a create-phase user field but no identity is in
50
+ * scope — a silent NULL is exactly the failure this enforcement exists to kill.
51
+ *
52
+ * `onUpdateUserId` is deliberately NOT enforced: `updatedBy` is allowed to stay absent,
53
+ * and refusing a context-less update would also break pre-auth writes that don't touch it.
54
+ */
55
+ private assertCreateIdentity(fields: VexFieldEntry[]): void {
56
+ if (!fields.some(f => f.type === "onCreateUserId")) return;
57
+ if (UserContext.userId) return;
58
+
59
+ throw new VexResErr(500, undefined,
60
+ `${this.getEntityName()} declares onCreateUserId but UserContext carries no user identity`);
61
+ }
62
+
48
63
  /**
49
64
  * Framework-managed audit fields: strip the caller's values first — a client must never
50
65
  * forge createdBy / updatedAt — then fill the ones owned by this write phase.
@@ -55,7 +70,9 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
55
70
  const fields = entityVexFields[this.getEntityName()] ?? [];
56
71
  if (fields.length === 0) return;
57
72
 
58
- const userId = DataIsolationContext.getStore()?.userId;
73
+ if (phase === "create") this.assertCreateIdentity(fields);
74
+
75
+ const userId = UserContext.userId;
59
76
  const values: Record<string, unknown> = {};
60
77
 
61
78
  for (const entry of fields) {
@@ -72,25 +89,45 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
72
89
 
73
90
  /** Build ownership filter from current request context, or null. */
74
91
  private getOwnershipFilter(): Record<string, unknown> | null {
75
- const store = DataIsolationContext.getStore();
76
- if (!store?.userId) return null;
92
+ const userId = UserContext.userId;
93
+ if (!userId) return null;
77
94
 
78
95
  const config = entityIsolation[this.getEntityName()];
79
96
  if (!config) return null;
80
97
 
81
- return { [config.field]: store.userId };
98
+ return { [config.field]: userId };
99
+ }
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) };
82
115
  }
83
116
 
84
117
  /** Merge caller filter with ownership filter. Ownership always wins. */
85
- private mergeFilter(callerFilter: Filter<T>): Record<string, unknown> | Array<Record<string, unknown>> {
118
+ private mergeFilter(
119
+ callerFilter: Filter<T>,
120
+ options?: { includeSoftDeleted?: boolean },
121
+ ): Record<string, unknown> | Array<Record<string, unknown>> {
86
122
  const mapped = this.mapOperators(callerFilter);
87
123
  const ownership = this.getOwnershipFilter();
124
+ const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
88
125
 
89
126
  if (mapped instanceof Array) {
90
- return mapped.map(branch => ({ ...branch, ...ownership }));
127
+ return mapped.map(branch => ({ ...branch, ...softDelete, ...ownership }));
91
128
  }
92
129
  else {
93
- return { ...mapped, ...ownership };
130
+ return { ...mapped, ...softDelete, ...ownership };
94
131
  }
95
132
  }
96
133
 
@@ -198,11 +235,11 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
198
235
 
199
236
  async create(data: Partial<T>): Promise<T> {
200
237
  const enriched = { ...data };
201
- const store = DataIsolationContext.getStore();
202
- if (store?.userId) {
238
+ const userId = UserContext.userId;
239
+ if (userId) {
203
240
  const config = entityIsolation[this.getEntityName()];
204
241
  if (config && config.field !== "_id") {
205
- (enriched as Record<string, unknown>)[config.field] = store.userId;
242
+ (enriched as Record<string, unknown>)[config.field] = userId;
206
243
  }
207
244
  }
208
245
  this.applyVexFields(enriched, "create");
@@ -246,4 +283,50 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
246
283
  const where = this.mergeFilter(filter as unknown as Filter<T>);
247
284
  await this.repo.delete(where as FindOptionsWhere<T>);
248
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
+ }
249
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: UserWithRelations = {
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: UserWithRelations = {
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
  }