very-express 0.9.0-alpha → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tmp/als-proof.mjs +15 -0
- package/.tmp/als-proof2.mjs +9 -0
- package/.tmp/gen/out/.env +41 -0
- package/.tmp/gen/out/.vex/meta.json +381 -0
- package/.tmp/gen/out/Dockerfile +20 -0
- package/.tmp/gen/out/README.md +39 -0
- package/.tmp/gen/out/package.json +51 -0
- package/.tmp/gen/out/public/css/style.css +8 -0
- package/.tmp/gen/out/public/js/deleteaccount.js +80 -0
- package/.tmp/gen/out/public/js/login.js +59 -0
- package/.tmp/gen/out/public/js/logincallback.js +19 -0
- package/.tmp/gen/out/public/js/mytokens.js +11 -0
- package/.tmp/gen/out/public/js/refreshtokens.js +23 -0
- package/.tmp/gen/out/scripts/build.js +39 -0
- package/.tmp/gen/out/scripts/oacg-fix.js +83 -0
- package/.tmp/gen/out/tsconfig.json +30 -0
- package/.tmp/gen/out/tsoa.json +32 -0
- package/.tmp/gen/schemas/Project.json +50 -0
- package/.tmp/gen/schemas/Session.json +49 -0
- package/.tmp/gen/schemas/User.json +81 -0
- package/.tmp/gen/schemas/UserAuthProfiles.json +54 -0
- package/.tmp/gen/schemas/UserRole.json +40 -0
- package/.tmp/gen/schemas/UserTenant.json +39 -0
- package/.tmp/gen/vex.config.json +39 -0
- package/.tmp/gen0/out/.env +41 -0
- package/.tmp/gen0/out/.vex/meta.json +323 -0
- package/.tmp/gen0/out/Dockerfile +20 -0
- package/.tmp/gen0/out/README.md +39 -0
- package/.tmp/gen0/out/package.json +51 -0
- package/.tmp/gen0/out/public/css/style.css +8 -0
- package/.tmp/gen0/out/public/js/deleteaccount.js +80 -0
- package/.tmp/gen0/out/public/js/login.js +59 -0
- package/.tmp/gen0/out/public/js/logincallback.js +19 -0
- package/.tmp/gen0/out/public/js/mytokens.js +11 -0
- package/.tmp/gen0/out/public/js/refreshtokens.js +23 -0
- package/.tmp/gen0/out/scripts/build.js +39 -0
- package/.tmp/gen0/out/scripts/oacg-fix.js +83 -0
- package/.tmp/gen0/out/tsconfig.json +30 -0
- package/.tmp/gen0/out/tsoa.json +32 -0
- package/.tmp/gen0/schemas/Session.json +49 -0
- package/.tmp/gen0/schemas/User.json +81 -0
- package/.tmp/gen0/schemas/UserAuthProfiles.json +54 -0
- package/.tmp/gen0/schemas/UserRole.json +38 -0
- package/.tmp/gen0/vex.config.json +32 -0
- package/.tmp/gend/out/.env +41 -0
- package/.tmp/gend/out/.vex/meta.json +317 -0
- package/.tmp/gend/out/Dockerfile +20 -0
- package/.tmp/gend/out/README.md +39 -0
- package/.tmp/gend/out/package.json +51 -0
- package/.tmp/gend/out/public/css/style.css +8 -0
- package/.tmp/gend/out/public/js/deleteaccount.js +80 -0
- package/.tmp/gend/out/public/js/login.js +59 -0
- package/.tmp/gend/out/public/js/logincallback.js +19 -0
- package/.tmp/gend/out/public/js/mytokens.js +11 -0
- package/.tmp/gend/out/public/js/refreshtokens.js +23 -0
- package/.tmp/gend/out/scripts/build.js +39 -0
- package/.tmp/gend/out/scripts/oacg-fix.js +83 -0
- package/.tmp/gend/out/tsconfig.json +30 -0
- package/.tmp/gend/out/tsoa.json +32 -0
- package/.tmp/gend/schemas/Session.json +49 -0
- package/.tmp/gend/schemas/User.json +81 -0
- package/.tmp/gend/schemas/UserAuthProfiles.json +54 -0
- package/.tmp/gend/schemas/UserContact.json +40 -0
- package/.tmp/gend/schemas/UserNote.json +27 -0
- package/.tmp/gend/vex.config.json +33 -0
- package/.tmp/genh/out/.env +41 -0
- package/.tmp/genh/out/.vex/meta.json +323 -0
- package/.tmp/genh/out/Dockerfile +20 -0
- package/.tmp/genh/out/README.md +39 -0
- package/.tmp/genh/out/package.json +51 -0
- package/.tmp/genh/out/public/css/style.css +8 -0
- package/.tmp/genh/out/public/js/deleteaccount.js +80 -0
- package/.tmp/genh/out/public/js/login.js +59 -0
- package/.tmp/genh/out/public/js/logincallback.js +19 -0
- package/.tmp/genh/out/public/js/mytokens.js +11 -0
- package/.tmp/genh/out/public/js/refreshtokens.js +23 -0
- package/.tmp/genh/out/scripts/build.js +39 -0
- package/.tmp/genh/out/scripts/oacg-fix.js +83 -0
- package/.tmp/genh/out/tsconfig.json +30 -0
- package/.tmp/genh/out/tsoa.json +32 -0
- package/.tmp/genh/schemas/Project.json +41 -0
- package/.tmp/genh/schemas/Session.json +49 -0
- package/.tmp/genh/schemas/User.json +81 -0
- package/.tmp/genh/schemas/UserAuthProfiles.json +54 -0
- package/.tmp/genh/schemas/UserTenant.json +39 -0
- package/.tmp/genh/vex.config.json +31 -0
- package/.tmp/gens/out/.env +41 -0
- package/.tmp/gens/out/.vex/meta.json +335 -0
- package/.tmp/gens/out/Dockerfile +20 -0
- package/.tmp/gens/out/README.md +39 -0
- package/.tmp/gens/out/package.json +51 -0
- package/.tmp/gens/out/public/css/style.css +8 -0
- package/.tmp/gens/out/public/js/deleteaccount.js +80 -0
- package/.tmp/gens/out/public/js/login.js +59 -0
- package/.tmp/gens/out/public/js/logincallback.js +19 -0
- package/.tmp/gens/out/public/js/mytokens.js +11 -0
- package/.tmp/gens/out/public/js/refreshtokens.js +23 -0
- package/.tmp/gens/out/scripts/build.js +39 -0
- package/.tmp/gens/out/scripts/oacg-fix.js +83 -0
- package/.tmp/gens/out/tsconfig.json +30 -0
- package/.tmp/gens/out/tsoa.json +32 -0
- package/.tmp/gens/schemas/Session.json +49 -0
- package/.tmp/gens/schemas/User.json +81 -0
- package/.tmp/gens/schemas/UserAuthProfiles.json +54 -0
- package/.tmp/gens/schemas/UserRole.json +38 -0
- package/.tmp/gens/vex.config.json +32 -0
- package/.tmp/npmtest/package.json +1 -0
- package/.tmp/ro-test +0 -0
- package/AGENTS.md +26 -12
- package/README.md +1 -0
- package/dist/index.js +1108 -1037
- package/dist/templates/_middlewares/Authentication.ts +1 -4
- package/dist/templates/_middlewares/UserContext.ts +31 -22
- package/dist/templates/_projectSettings/env +13 -12
- package/dist/templates/_projectSettings/package.json +2 -2
- package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
- package/dist/templates/_routes/LoginUI.ts +293 -242
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +68 -4
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +68 -24
- package/dist/templates/_services/VexDbConnector.ts +1 -26
- package/dist/templates/_services/auth/JWTService.ts +13 -17
- package/dist/templates/_tenant/TenantScopeContext.ts +56 -0
- package/dist/templates/_types/auth.ts +19 -9
- package/dist/templates/_types/vex/VexRepository.ts +2 -2
- package/dist/templates/_utils/hash.ts +0 -16
- package/dist/templates/root/public/js/deleteaccount.js +0 -54
- package/dist/templates/tenantJsonSchema/UserTenant.json +33 -0
- package/docs/appGenerated/auth.md +84 -0
- package/docs/architecture/authAndRouting.md +1 -1
- package/docs/architecture/databaseTargets.md +18 -8
- package/docs/architecture/generatorPipeline.md +2 -1
- package/docs/features/accountDeletion.md +63 -12
- package/docs/features/auditFields.md +2 -2
- package/docs/features/dataIsolation.md +58 -31
- package/docs/features/tenantIsolation.md +138 -0
- package/docs/releaseNote/v0-10-0.md +147 -0
- package/docs/releaseNote/v0-8-5.md +98 -0
- package/docs/releaseNote/v0-9-0.md +41 -47
- package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
- package/docs/vexJsonSchema.md +39 -0
- package/package.json +1 -1
- package/vex.config.json +1 -6
- package/vitest.config.ts +3 -0
- package/dist/templates/_routes/ExternalIdentityUI.gen.ts +0 -20
- package/dist/templates/root/public/js/externallogin.js +0 -133
- package/docs/features/auth.md +0 -34
- package/docs/features/externalIdentity.md +0 -163
- /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
- /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
|
@@ -2,6 +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 { entityIsolation, DataIsolationEntry } from "../_middlewares/DataIsolationRegistry.gen";
|
|
5
6
|
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
7
|
import utils from "../_utils";
|
|
7
8
|
|
|
@@ -104,9 +105,64 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
104
105
|
return { [field]: { $ne: true } };
|
|
105
106
|
}
|
|
106
107
|
|
|
108
|
+
/** Value the request context supplies for one isolation rule. */
|
|
109
|
+
private resolveIsolationValue(source: DataIsolationEntry["source"]): string | undefined {
|
|
110
|
+
return source === "user.tenantId" ? UserContext.tenantId : UserContext.userId;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Isolation terms for this model, ANDed into the caller's filter.
|
|
115
|
+
* A tenant term fails closed; an ownership term skips when unauthenticated.
|
|
116
|
+
*/
|
|
117
|
+
private getIsolationFilter(): Record<string, unknown> | null {
|
|
118
|
+
const rules = entityIsolation[this.getEntityName()] ?? [];
|
|
119
|
+
if (rules.length === 0) return null;
|
|
120
|
+
|
|
121
|
+
const terms: Record<string, unknown> = {};
|
|
122
|
+
|
|
123
|
+
for (const rule of rules) {
|
|
124
|
+
const value = this.resolveIsolationValue(rule.source);
|
|
125
|
+
if (value === undefined) {
|
|
126
|
+
if (rule.onMissing === "deny") {
|
|
127
|
+
throw new VexResErr(403, undefined,
|
|
128
|
+
`${this.model.modelName} is isolated by ${rule.source} but the request carries no such value`);
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
terms[rule.field] = value;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return Object.keys(terms).length > 0 ? terms : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private stripIsolationFields(data: Partial<T>): void {
|
|
140
|
+
for (const rule of entityIsolation[this.getEntityName()] ?? []) {
|
|
141
|
+
if (rule.field === "_id") continue;
|
|
142
|
+
delete (data as Record<string, unknown>)[rule.field];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private stampIsolationFields(data: Partial<T>): void {
|
|
147
|
+
for (const rule of entityIsolation[this.getEntityName()] ?? []) {
|
|
148
|
+
if (rule.field === "_id") continue;
|
|
149
|
+
|
|
150
|
+
// `all` is a read scope: a write still needs a concrete tenant to stamp.
|
|
151
|
+
const value = this.resolveIsolationValue(rule.source);
|
|
152
|
+
if (value !== undefined) {
|
|
153
|
+
(data as Record<string, unknown>)[rule.field] = value;
|
|
154
|
+
}
|
|
155
|
+
else if (rule.onMissing === "deny") {
|
|
156
|
+
throw new VexResErr(403, undefined,
|
|
157
|
+
`${this.model.modelName} is isolated by ${rule.source} but the request carries no such value`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
107
162
|
private mergeFilter(filter: Filter, options?: { includeSoftDeleted?: boolean }): Record<string, unknown> {
|
|
163
|
+
const isolation = this.getIsolationFilter();
|
|
108
164
|
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
109
|
-
return { ...((filter || {}) as Record<string, unknown>), ...softDelete };
|
|
165
|
+
return { ...((filter || {}) as Record<string, unknown>), ...softDelete, ...isolation };
|
|
110
166
|
}
|
|
111
167
|
|
|
112
168
|
find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
@@ -131,6 +187,8 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
131
187
|
|
|
132
188
|
async create(data: Partial<T>): Promise<T> {
|
|
133
189
|
const enriched = { ...data };
|
|
190
|
+
this.stripIsolationFields(enriched);
|
|
191
|
+
this.stampIsolationFields(enriched);
|
|
134
192
|
this.applyVexFields(enriched, "create");
|
|
135
193
|
const doc = new this.model(enriched);
|
|
136
194
|
return doc.save();
|
|
@@ -142,8 +200,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
142
200
|
return Promise.resolve(null);
|
|
143
201
|
}
|
|
144
202
|
const enriched = { ...data };
|
|
203
|
+
this.stripIsolationFields(enriched);
|
|
145
204
|
this.applyVexFields(enriched, "update");
|
|
146
|
-
|
|
205
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
206
|
+
return this.model.findOneAndUpdate(filter as any, enriched, { new: true, overwrite: true }).exec();
|
|
147
207
|
}
|
|
148
208
|
|
|
149
209
|
update(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
@@ -152,8 +212,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
152
212
|
return Promise.resolve(null);
|
|
153
213
|
}
|
|
154
214
|
const enriched = { ...data };
|
|
215
|
+
this.stripIsolationFields(enriched);
|
|
155
216
|
this.applyVexFields(enriched, "update");
|
|
156
|
-
|
|
217
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
218
|
+
return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
|
|
157
219
|
}
|
|
158
220
|
|
|
159
221
|
async delete(id: string | undefined): Promise<void> {
|
|
@@ -161,7 +223,8 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
161
223
|
utils.log.error("MongooseRepositoryAdapter.delete called without id — refuse delete document");
|
|
162
224
|
return;
|
|
163
225
|
}
|
|
164
|
-
|
|
226
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
227
|
+
await this.model.findOneAndDelete(filter as any).exec();
|
|
165
228
|
}
|
|
166
229
|
|
|
167
230
|
async deleteWhere(filter: Record<string, unknown>): Promise<void> {
|
|
@@ -189,6 +252,7 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
189
252
|
}
|
|
190
253
|
|
|
191
254
|
const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
|
|
255
|
+
this.stripIsolationFields(enriched as Partial<T>);
|
|
192
256
|
this.applyVexFields(enriched as Partial<T>, "update");
|
|
193
257
|
enriched[field] = true;
|
|
194
258
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, FindManyOptions } from "typeorm";
|
|
3
3
|
import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
|
-
import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
|
|
5
|
+
import { entityIsolation, DataIsolationEntry } from "../_middlewares/DataIsolationRegistry.gen";
|
|
6
6
|
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
7
7
|
import utils from "../_utils";
|
|
8
8
|
|
|
@@ -87,15 +87,67 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
87
87
|
Object.assign(data, values);
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
/**
|
|
91
|
-
private
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
/** Value the request context supplies for one isolation rule. */
|
|
91
|
+
private resolveIsolationValue(source: DataIsolationEntry["source"]): string | undefined {
|
|
92
|
+
return source === "user.tenantId" ? UserContext.tenantId : UserContext.userId;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Isolation terms for this entity, ANDed into the caller's filter.
|
|
97
|
+
*
|
|
98
|
+
* A tenant term fails closed: a document that declares one is unreachable when the
|
|
99
|
+
* request carries no tenant, unless a cross-tenant role lifted the scope. An ownership
|
|
100
|
+
* term keeps its historical skip-when-unauthenticated behaviour.
|
|
101
|
+
*/
|
|
102
|
+
private getIsolationFilter(): Record<string, unknown> | null {
|
|
103
|
+
const rules = entityIsolation[this.getEntityName()] ?? [];
|
|
104
|
+
if (rules.length === 0) return null;
|
|
105
|
+
|
|
106
|
+
const terms: Record<string, unknown> = {};
|
|
107
|
+
|
|
108
|
+
for (const rule of rules) {
|
|
109
|
+
const value = this.resolveIsolationValue(rule.source);
|
|
110
|
+
if (value === undefined) {
|
|
111
|
+
if (rule.onMissing === "deny") {
|
|
112
|
+
throw new VexResErr(403, undefined,
|
|
113
|
+
`${this.getEntityName()} is isolated by ${rule.source} but the request carries no such value`);
|
|
114
|
+
}
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
94
117
|
|
|
95
|
-
|
|
96
|
-
|
|
118
|
+
terms[rule.field] = value;
|
|
119
|
+
}
|
|
97
120
|
|
|
98
|
-
return
|
|
121
|
+
return Object.keys(terms).length > 0 ? terms : null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Remove isolation fields from caller-supplied data. A client must never be able to
|
|
126
|
+
* move a row under another owner or into another tenant.
|
|
127
|
+
*/
|
|
128
|
+
private stripIsolationFields(data: Partial<T>): void {
|
|
129
|
+
for (const rule of entityIsolation[this.getEntityName()] ?? []) {
|
|
130
|
+
if (rule.field === "_id") continue;
|
|
131
|
+
delete (data as Record<string, unknown>)[rule.field];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Fill isolation fields from the request context on create. */
|
|
136
|
+
private stampIsolationFields(data: Partial<T>): void {
|
|
137
|
+
for (const rule of entityIsolation[this.getEntityName()] ?? []) {
|
|
138
|
+
// a rule on `_id` filters the row's own id; it is never stamped
|
|
139
|
+
if (rule.field === "_id") continue;
|
|
140
|
+
|
|
141
|
+
// `all` is a read scope: a write still needs a concrete tenant to stamp.
|
|
142
|
+
const value = this.resolveIsolationValue(rule.source);
|
|
143
|
+
if (value !== undefined) {
|
|
144
|
+
(data as Record<string, unknown>)[rule.field] = value;
|
|
145
|
+
}
|
|
146
|
+
else if (rule.onMissing === "deny") {
|
|
147
|
+
throw new VexResErr(403, undefined,
|
|
148
|
+
`${this.getEntityName()} is isolated by ${rule.source} but the request carries no such value`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
99
151
|
}
|
|
100
152
|
|
|
101
153
|
/**
|
|
@@ -114,26 +166,25 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
114
166
|
return { [field]: Not(true) };
|
|
115
167
|
}
|
|
116
168
|
|
|
117
|
-
/** Merge caller filter with
|
|
169
|
+
/** Merge caller filter with isolation and soft-delete terms. Isolation always wins. */
|
|
118
170
|
private mergeFilter(
|
|
119
171
|
callerFilter: Filter<T>,
|
|
120
172
|
options?: { includeSoftDeleted?: boolean },
|
|
121
173
|
): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
122
174
|
const mapped = this.mapOperators(callerFilter);
|
|
123
|
-
const
|
|
175
|
+
const isolation = this.getIsolationFilter();
|
|
124
176
|
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
125
177
|
|
|
126
178
|
if (mapped instanceof Array) {
|
|
127
|
-
return mapped.map(branch => ({ ...branch, ...softDelete, ...
|
|
179
|
+
return mapped.map(branch => ({ ...branch, ...softDelete, ...isolation }));
|
|
128
180
|
}
|
|
129
181
|
else {
|
|
130
|
-
return { ...mapped, ...softDelete, ...
|
|
182
|
+
return { ...mapped, ...softDelete, ...isolation };
|
|
131
183
|
}
|
|
132
184
|
}
|
|
133
185
|
|
|
134
186
|
private mapOperators(filter: Filter<T>): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
135
187
|
if (!filter || typeof filter !== "object") return {};
|
|
136
|
-
// if (Array.isArray(filter)) return filter.map(f => this.mapOperators(f));
|
|
137
188
|
|
|
138
189
|
let out: Record<string, unknown> | Array<Record<string, unknown>> = {};
|
|
139
190
|
|
|
@@ -177,10 +228,6 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
177
228
|
out[key] = Like(oval.$like as string);
|
|
178
229
|
continue;
|
|
179
230
|
}
|
|
180
|
-
// if (val?.$raw) {
|
|
181
|
-
// out[key] = Raw(val.$raw as string);
|
|
182
|
-
// continue;
|
|
183
|
-
// }
|
|
184
231
|
} else {
|
|
185
232
|
out[key] = val;
|
|
186
233
|
}
|
|
@@ -235,13 +282,8 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
235
282
|
|
|
236
283
|
async create(data: Partial<T>): Promise<T> {
|
|
237
284
|
const enriched = { ...data };
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const config = entityIsolation[this.getEntityName()];
|
|
241
|
-
if (config && config.field !== "_id") {
|
|
242
|
-
(enriched as Record<string, unknown>)[config.field] = userId;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
285
|
+
this.stripIsolationFields(enriched);
|
|
286
|
+
this.stampIsolationFields(enriched);
|
|
245
287
|
this.applyVexFields(enriched, "create");
|
|
246
288
|
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
247
289
|
}
|
|
@@ -252,6 +294,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
252
294
|
return null;
|
|
253
295
|
}
|
|
254
296
|
const enriched = { ...data };
|
|
297
|
+
this.stripIsolationFields(enriched);
|
|
255
298
|
this.applyVexFields(enriched, "update");
|
|
256
299
|
const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
|
|
257
300
|
if (!existing) return null;
|
|
@@ -264,6 +307,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
264
307
|
return null;
|
|
265
308
|
}
|
|
266
309
|
const enriched = { ...data };
|
|
310
|
+
this.stripIsolationFields(enriched);
|
|
267
311
|
this.applyVexFields(enriched, "update");
|
|
268
312
|
const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
|
|
269
313
|
await this.repo.update(where as FindOptionsWhere<T>, enriched);
|
|
@@ -2,11 +2,8 @@
|
|
|
2
2
|
import { Request, Response, NextFunction } from "express";
|
|
3
3
|
import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
|
|
4
4
|
import mongoose from "mongoose";
|
|
5
|
-
// import { Document } from "mongoose";
|
|
6
|
-
// import { sqlMigrations } from "../_models/sqlMigration.gen";
|
|
7
5
|
import { VexRepository } from "../_types/vex";
|
|
8
6
|
import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
|
|
9
|
-
// import { MongooseRepositoryAdapter } from "./MongooseRepositoryAdapter.gen";
|
|
10
7
|
import utils from "./../_utils";
|
|
11
8
|
|
|
12
9
|
export class VexDbConnector {
|
|
@@ -73,7 +70,6 @@ export class VexDbConnector {
|
|
|
73
70
|
.then(() => {
|
|
74
71
|
this.dataSource = ds;
|
|
75
72
|
utils.log.infoSql("TypeORM DataSource initialized");
|
|
76
|
-
// this.runSqlMigrations(ds);
|
|
77
73
|
})
|
|
78
74
|
.catch((err) => {
|
|
79
75
|
utils.log.errorSql(`Failed to initialize TypeORM, retrying in ${retryTime}s`, err);
|
|
@@ -84,23 +80,6 @@ export class VexDbConnector {
|
|
|
84
80
|
connectWithRetry(10);
|
|
85
81
|
}
|
|
86
82
|
|
|
87
|
-
// private async runSqlMigrations(ds: DataSource): Promise<void> {
|
|
88
|
-
// if (!sqlMigrations.length) return;
|
|
89
|
-
// const runner = ds.createQueryRunner();
|
|
90
|
-
// await runner.connect();
|
|
91
|
-
// try {
|
|
92
|
-
// for (const sql of sqlMigrations) {
|
|
93
|
-
// utils.log.infoSql(`Applying migration: ${sql}`);
|
|
94
|
-
// await runner.query(sql);
|
|
95
|
-
// }
|
|
96
|
-
// utils.log.infoSql(`${sqlMigrations.length} migrations applied`);
|
|
97
|
-
// } catch (err) {
|
|
98
|
-
// utils.log.errorSql("SQL migration failed", err);
|
|
99
|
-
// } finally {
|
|
100
|
-
// await runner.release();
|
|
101
|
-
// }
|
|
102
|
-
// }
|
|
103
|
-
|
|
104
83
|
closeSql(): void {
|
|
105
84
|
if (this.dataSource?.isInitialized) {
|
|
106
85
|
this.dataSource.destroy()
|
|
@@ -109,7 +88,7 @@ export class VexDbConnector {
|
|
|
109
88
|
}
|
|
110
89
|
}
|
|
111
90
|
|
|
112
|
-
// TODO: complete mongoose support
|
|
91
|
+
// TODO: complete mongoose support
|
|
113
92
|
connectMongo(): void {
|
|
114
93
|
console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
|
|
115
94
|
utils.log.infoMongo("Connecting to MongoDB (Driver: Mongoose)...");
|
|
@@ -124,7 +103,6 @@ export class VexDbConnector {
|
|
|
124
103
|
connectWithRetry(10);
|
|
125
104
|
}
|
|
126
105
|
|
|
127
|
-
// TODO: complete mongoose support, handle join and select
|
|
128
106
|
closeMongo(): void {
|
|
129
107
|
console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
|
|
130
108
|
mongoose.disconnect()
|
|
@@ -132,13 +110,10 @@ export class VexDbConnector {
|
|
|
132
110
|
.catch((err) => utils.log.errorMongo("Error disconnecting Mongoose", err));
|
|
133
111
|
}
|
|
134
112
|
|
|
135
|
-
// getRepository<T extends Document>(target: { schema: unknown; modelName: string }): VexRepository<T>;
|
|
136
113
|
getRepository<T extends ObjectLiteral>(target: EntityTarget<T>): VexRepository<T>;
|
|
137
114
|
getRepository<T>(target: EntityTarget<ObjectLiteral> | any): VexRepository<T> {
|
|
138
|
-
// TODO: complete mongoose support, handle join and select
|
|
139
115
|
if (target?.schema && target?.modelName) {
|
|
140
116
|
console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
|
|
141
|
-
// return new MongooseRepositoryAdapter<T & Document>(target);
|
|
142
117
|
}
|
|
143
118
|
if (!this.dataSource) throw new Error("SQL DataSource not initialized");
|
|
144
119
|
return new TypeOrmRepositoryAdapter<T & ObjectLiteral>(this.dataSource.getRepository(target));
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
import jwt from "jsonwebtoken";
|
|
3
3
|
import ms from "ms";
|
|
4
4
|
import path from "path";
|
|
5
|
-
// import express, { CookieOptions } from "express";
|
|
6
5
|
|
|
7
6
|
import JWTKeyStore from "./JWTKeyStore.gen";
|
|
8
7
|
|
|
@@ -36,13 +35,6 @@ export default class JWTService {
|
|
|
36
35
|
|
|
37
36
|
constructor() {}
|
|
38
37
|
|
|
39
|
-
/**
|
|
40
|
-
* Verifies a JSON Web Token (JWT) using the provided token and key index.
|
|
41
|
-
*
|
|
42
|
-
* @param {string} token - The JSON Web Token to be verified.
|
|
43
|
-
* @param {number} index - The index of the key used to verify the token.
|
|
44
|
-
* @return {jwt.JwtPayload } The decoded token payload, an error message, or false if verification fails.
|
|
45
|
-
*/
|
|
46
38
|
public verifyToken(token: string, index?: number | string): jwt.JwtPayload {
|
|
47
39
|
|
|
48
40
|
if (token.startsWith("Bearer ")) {
|
|
@@ -67,9 +59,6 @@ export default class JWTService {
|
|
|
67
59
|
}
|
|
68
60
|
}
|
|
69
61
|
|
|
70
|
-
/**
|
|
71
|
-
* Process of login user, assign tokens and create session.
|
|
72
|
-
*/
|
|
73
62
|
public async assignTokens(user: UserWithRelations, provider: string): Promise<string> {
|
|
74
63
|
if(!user._id) {
|
|
75
64
|
throw new VexResErr(500, null, "User Data Error, User._id missing.");
|
|
@@ -77,7 +66,6 @@ export default class JWTService {
|
|
|
77
66
|
|
|
78
67
|
const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
79
68
|
|
|
80
|
-
// insert new unique session for user
|
|
81
69
|
await this.sessionRepo.deleteWhere({ userId: user._id });
|
|
82
70
|
await this.sessionRepo.create({
|
|
83
71
|
sessionCode,
|
|
@@ -86,7 +74,6 @@ export default class JWTService {
|
|
|
86
74
|
expired: Date.now() + 5000,
|
|
87
75
|
});
|
|
88
76
|
|
|
89
|
-
// return appAuthCode to client
|
|
90
77
|
const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
|
|
91
78
|
|
|
92
79
|
return redirectPath;
|
|
@@ -106,8 +93,6 @@ export default class JWTService {
|
|
|
106
93
|
};
|
|
107
94
|
}
|
|
108
95
|
|
|
109
|
-
/** utils */
|
|
110
|
-
|
|
111
96
|
/**
|
|
112
97
|
* Identity value of a user record: the field tagged `x-vexData: "userId"` in the schemas,
|
|
113
98
|
* with `_id` as the fallback. This is what every audit field (createdBy / updatedBy) stores.
|
|
@@ -165,9 +150,20 @@ export default class JWTService {
|
|
|
165
150
|
};
|
|
166
151
|
}
|
|
167
152
|
|
|
168
|
-
|
|
153
|
+
/**
|
|
154
|
+
* `extraClaims` carries caller-supplied claims (for example a tenant) into the payload.
|
|
155
|
+
* The auth module stays unaware of which features add them.
|
|
156
|
+
*/
|
|
157
|
+
public async generateAccessToken(
|
|
158
|
+
user: UserWithRelations,
|
|
159
|
+
index?: number,
|
|
160
|
+
extraClaims?: Record<string, unknown>,
|
|
161
|
+
): Promise<tokenObj> {
|
|
169
162
|
|
|
170
|
-
const userInfo =
|
|
163
|
+
const userInfo = {
|
|
164
|
+
...this.tokenPayload(user) as Record<string, unknown>,
|
|
165
|
+
...(extraClaims ?? {}),
|
|
166
|
+
};
|
|
171
167
|
|
|
172
168
|
return this.generateToken(userInfo, index, process.env.ACCESS_TOKEN_EXPIRE_TIME);
|
|
173
169
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// {{headerComment}}
|
|
2
|
+
|
|
3
|
+
export type TenantIsolationMode = "preSelect" | "option";
|
|
4
|
+
|
|
5
|
+
export type TenantError =
|
|
6
|
+
| "missing-header"
|
|
7
|
+
| "invalid-tenant"
|
|
8
|
+
| "missing-claim"
|
|
9
|
+
| "invalid-claim";
|
|
10
|
+
|
|
11
|
+
export interface TenantDecision {
|
|
12
|
+
tenantId?: string;
|
|
13
|
+
error?: TenantError;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
+
|
|
18
|
+
/** Tenant ids are UUIDs everywhere: header, claim and the UserTenant table. */
|
|
19
|
+
export function isTenantId(value: unknown): value is string {
|
|
20
|
+
return typeof value === "string" && UUID_PATTERN.test(value);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Decide the tenant of a request.
|
|
25
|
+
*
|
|
26
|
+
* `preSelect` — the app build is bound to one tenant: the header is required and is the only
|
|
27
|
+
* source; a token claim is not used.
|
|
28
|
+
*
|
|
29
|
+
* `option` — the user logs in first and then selects a tenant. A token that carries the
|
|
30
|
+
* `tenantId` claim decides; a token without one is rejected. A request with no token is a
|
|
31
|
+
* guest, and the header identifies the tenant for public endpoints.
|
|
32
|
+
*
|
|
33
|
+
* `tokenData` is absent on the L0 pass because authentication has not run yet.
|
|
34
|
+
*/
|
|
35
|
+
export function resolveTenantContext(
|
|
36
|
+
mode: TenantIsolationMode,
|
|
37
|
+
tokenData: Record<string, unknown> | undefined,
|
|
38
|
+
headerTenantId: string | undefined,
|
|
39
|
+
): TenantDecision {
|
|
40
|
+
if (mode === "preSelect") {
|
|
41
|
+
if (!headerTenantId) return { error: "missing-header" };
|
|
42
|
+
if (!isTenantId(headerTenantId)) return { error: "invalid-tenant" };
|
|
43
|
+
return { tenantId: headerTenantId };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (tokenData) {
|
|
47
|
+
const claimed = tokenData.tenantId;
|
|
48
|
+
if (claimed === undefined || claimed === "") return { error: "missing-claim" };
|
|
49
|
+
if (!isTenantId(claimed)) return { error: "invalid-claim" };
|
|
50
|
+
return { tenantId: claimed };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!headerTenantId) return {};
|
|
54
|
+
if (!isTenantId(headerTenantId)) return { error: "invalid-tenant" };
|
|
55
|
+
return { tenantId: headerTenantId };
|
|
56
|
+
}
|
|
@@ -14,16 +14,20 @@ export interface registerResponse {
|
|
|
14
14
|
message: string
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export interface localLoginResponse {
|
|
18
|
+
url: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
/**
|
|
18
|
-
*
|
|
19
|
-
* `
|
|
20
|
-
*
|
|
21
|
-
* Neutral name on purpose: `/auth/local` and `/auth/external` both answer with this shape, and the two
|
|
22
|
-
* are independently enabled (`localAuth` vs `auth.externalIdentity`), so the type cannot live behind
|
|
23
|
-
* either flag.
|
|
22
|
+
* `POST /auth/firebase` — the answer to a Firebase sign-in.
|
|
23
|
+
* `isNewUser` is true only when this call created the `User` row; a user linked by a verified email address is false.
|
|
24
24
|
*/
|
|
25
|
-
export interface
|
|
26
|
-
|
|
25
|
+
export interface firebaseLoginResponse {
|
|
26
|
+
accessToken: string;
|
|
27
|
+
accessTokenIndex: string;
|
|
28
|
+
refreshToken: string;
|
|
29
|
+
refreshTokenIndex: string;
|
|
30
|
+
isNewUser: boolean;
|
|
27
31
|
}
|
|
28
32
|
|
|
29
33
|
/** Row counts removed alongside the tombstone, so the caller can log and retry. */
|
|
@@ -31,12 +35,18 @@ export interface deleteAccountCounts {
|
|
|
31
35
|
authProfiles: number;
|
|
32
36
|
userRoles: number;
|
|
33
37
|
sessions: number;
|
|
38
|
+
/** Tenant mappings removed (tenant isolation only). */
|
|
39
|
+
userTenants?: number;
|
|
34
40
|
}
|
|
35
41
|
|
|
36
42
|
/** Result of a self-service account deletion. */
|
|
37
43
|
export interface deleteAccountResponse {
|
|
38
44
|
userId: string;
|
|
39
|
-
/** When the tombstone was written (the row's updatedAt). Empty on a repeat call. */
|
|
45
|
+
/** When the tombstone was written (the row's updatedAt). Empty on a repeat call or a tenant leave. */
|
|
40
46
|
tombstonedAt: string;
|
|
41
47
|
deleted: deleteAccountCounts;
|
|
48
|
+
/** Set when the account left one tenant instead of being tombstoned. */
|
|
49
|
+
tenantId?: string;
|
|
50
|
+
/** Rows removed from `auth.deleteAccount.deleteTables`, keyed by document name. */
|
|
51
|
+
related?: Record<string, number>;
|
|
42
52
|
}
|
|
@@ -35,8 +35,8 @@ export interface VexRepository<T, U=undefined> {
|
|
|
35
35
|
/**
|
|
36
36
|
* Read a row that may be soft-deleted.
|
|
37
37
|
*
|
|
38
|
-
* Skips ONLY the adapter's soft-delete term — the
|
|
39
|
-
* not a way around `
|
|
38
|
+
* Skips ONLY the adapter's soft-delete term — the isolation terms still apply, so this is
|
|
39
|
+
* not a way around `isolation`. Exists for internal state checks (account-deletion
|
|
40
40
|
* idempotency, the account-state guard); a `Filter`-level escape hatch would have been part of
|
|
41
41
|
* every HTTP filter body, which is exactly what must not be possible.
|
|
42
42
|
*/
|
|
@@ -1,15 +1,7 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
import crypto from "crypto";
|
|
3
|
-
// import log from "~/utils/logger";
|
|
4
3
|
import { UserWithRelations } from "../_types/User.gen";
|
|
5
4
|
|
|
6
|
-
/**
|
|
7
|
-
* Hashes a password with a salt (e.g., user email).
|
|
8
|
-
* @param plainPassword The plain text password to hash.
|
|
9
|
-
* @param salt The salt to use (e.g., user email).
|
|
10
|
-
* @param algorithm The hash algorithm (default: 'sha256').
|
|
11
|
-
* @returns The hashed password (hex encoded).
|
|
12
|
-
*/
|
|
13
5
|
export function hashPassword(
|
|
14
6
|
plainPassword: string,
|
|
15
7
|
salt: string,
|
|
@@ -18,24 +10,16 @@ export function hashPassword(
|
|
|
18
10
|
return crypto.createHash(algorithm).update(plainPassword + salt).digest("hex");
|
|
19
11
|
}
|
|
20
12
|
|
|
21
|
-
/**
|
|
22
|
-
* Verifies if a plain password (with salt) matches a given hashed password.
|
|
23
|
-
* @param user The user object containing email and userAuthProfiles.
|
|
24
|
-
* @param plainPassword The plain text password to verify.
|
|
25
|
-
* @returns True if the password matches, false otherwise.
|
|
26
|
-
*/
|
|
27
13
|
export function verifyPassword(
|
|
28
14
|
user: UserWithRelations,
|
|
29
15
|
plainPassword: string,
|
|
30
16
|
): boolean {
|
|
31
17
|
if(!user.email || !user.userAuthProfiles) {
|
|
32
|
-
// log.error(`User "${user._id}" email or userAuthProfiles missing for local auth's password verification.`);
|
|
33
18
|
return false;
|
|
34
19
|
}
|
|
35
20
|
|
|
36
21
|
const hashedPassword = user.userAuthProfiles.find((profile:any) => profile.provider === "local")?.password;
|
|
37
22
|
if(!hashedPassword) {
|
|
38
|
-
// log.error(`User "${user._id}" Local auth profile or password missing.`);
|
|
39
23
|
return false;
|
|
40
24
|
}
|
|
41
25
|
|
|
@@ -24,52 +24,7 @@ document.addEventListener("DOMContentLoaded", function () {
|
|
|
24
24
|
result.textContent = JSON.stringify(data, null, 2);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
/**
|
|
28
|
-
* Deletion is self-service and the server resolves the account from the token alone, so with no
|
|
29
|
-
* token there is nothing to delete: sending an empty `Bearer ` would only earn a bare 401 that
|
|
30
|
-
* reads like a server fault. Point at the login page instead.
|
|
31
|
-
*
|
|
32
|
-
* Both credentials are required — `Authentication.middleware` treats them as one requirement — so
|
|
33
|
-
* a half-populated store counts as "not signed in" rather than as an API call.
|
|
34
|
-
*
|
|
35
|
-
* Note this file is copied into a project once and never overwritten, so a project generated
|
|
36
|
-
* before these checks existed keeps the old behaviour until it is updated by hand.
|
|
37
|
-
*/
|
|
38
|
-
function signedIn() {
|
|
39
|
-
return !!localStorage.getItem("accessToken") && !!localStorage.getItem("accessTokenIndex");
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function notSignedIn() {
|
|
43
|
-
render({
|
|
44
|
-
status: 401,
|
|
45
|
-
error: "You are not signed in. Deletion is self-service and the server takes the account " +
|
|
46
|
-
"from your access token, so sign in first.",
|
|
47
|
-
signIn: "/login",
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* A 401 from the server means the stored credential was not accepted — expired, or already
|
|
53
|
-
* tombstoned. Deliberately does NOT clear it: the request may equally have failed for a reason
|
|
54
|
-
* that has nothing to do with the token, and dropping the session on any failure would sign the
|
|
55
|
-
* user out of a working account. Sign in again and retry; the login flow overwrites both tokens.
|
|
56
|
-
*/
|
|
57
|
-
function sessionRejected(outcome) {
|
|
58
|
-
render({
|
|
59
|
-
status: outcome.status,
|
|
60
|
-
error: "Your session was not accepted, so nothing was deleted. It may have expired — " +
|
|
61
|
-
"sign in again and retry.",
|
|
62
|
-
detail: outcome.body,
|
|
63
|
-
signIn: "/login",
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
|
|
67
27
|
button.addEventListener("click", function () {
|
|
68
|
-
if (!signedIn()) {
|
|
69
|
-
notSignedIn();
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
28
|
if (input.value !== "DELETE") {
|
|
74
29
|
render({ error: 'Type DELETE in the box to confirm.' });
|
|
75
30
|
return;
|
|
@@ -105,15 +60,6 @@ document.addEventListener("DOMContentLoaded", function () {
|
|
|
105
60
|
})
|
|
106
61
|
.then(function (outcome) {
|
|
107
62
|
if (!outcome.ok) {
|
|
108
|
-
// 401 means the credential was not accepted. Say what to do about it rather than
|
|
109
|
-
// printing a raw error body the user cannot act on — see sessionRejected for why
|
|
110
|
-
// the stored tokens are left alone.
|
|
111
|
-
if (outcome.status === 401) {
|
|
112
|
-
sessionRejected(outcome);
|
|
113
|
-
button.disabled = false;
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
63
|
render({ status: outcome.status, error: outcome.body });
|
|
118
64
|
button.disabled = false;
|
|
119
65
|
return;
|