very-express 0.10.1 → 0.10.2
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/dist/index.js +1 -1
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +106 -4
- package/docs/architecture/databaseTargets.md +3 -0
- package/docs/features/dataIsolation.md +2 -0
- package/docs/features/tenantIsolation.md +13 -0
- package/docs/releaseNote/v0-10-2.md +54 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -978,7 +978,7 @@ export const {{documentName}}Model: Model<{{documentName}}Document> = model<{{do
|
|
|
978
978
|
*/
|
|
979
979
|
`}f6.getGenaratorHeaderComment=ihe;f6.defaultCompilerOptions={headerComment:ihe(),use_id:!1};f6.default={getGenaratorHeaderComment:ihe,defaultCompilerOptions:f6.defaultCompilerOptions}});var a9e=vs(Kg=>{"use strict";var eqr=Kg&&Kg.__createBinding||(Object.create?function(a,s,c,p){p===void 0&&(p=c);var f=Object.getOwnPropertyDescriptor(s,c);(!f||("get"in f?!s.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return s[c]}}),Object.defineProperty(a,p,f)}:function(a,s,c,p){p===void 0&&(p=c),a[p]=s[c]}),tqr=Kg&&Kg.__setModuleDefault||(Object.create?function(a,s){Object.defineProperty(a,"default",{enumerable:!0,value:s})}:function(a,s){a.default=s}),t9e=Kg&&Kg.__importStar||function(a){if(a&&a.__esModule)return a;var s={};if(a!=null)for(var c in a)c!=="default"&&Object.prototype.hasOwnProperty.call(a,c)&&eqr(s,a,c);return tqr(s,a),s},rqr=Kg&&Kg.__awaiter||function(a,s,c,p){function f(_){return _ instanceof c?_:new c(function(h){h(_)})}return new(c||(c=Promise))(function(_,h){function g(C){try{x(p.next(C))}catch(T){h(T)}}function v(C){try{x(p.throw(C))}catch(T){h(T)}}function x(C){C.done?_(C.value):f(C.value).then(g,v)}x((p=p.apply(a,s||[])).next())})},ohe=Kg&&Kg.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(Kg,"__esModule",{value:!0});Kg.compileFromFile=Kg.json2Mongoose=void 0;var nqr=t9e(require("util")),ZFe=t9e(require("fs")),iqr=ohe(XFe()),she=ohe(ahe()),aqr=ohe(rhe());function e9e(a){switch(a.toLocaleLowerCase()){case"unix":case"unixtime":case"unix-time":return"new Date().getTime()";case"date":return"new Date().toISOString().slice(0, 10)";case"time":return"new Date().toISOString().slice(11, 19)";case"datetime":case"date-time":return"new Date().toISOString()";default:return a}}function r9e(a,s){var c,p;let f={onCreate:{},onUpdate:{}},_=s.type==="object"?s.properties:((c=s.items)===null||c===void 0?void 0:c.type)==="object"?s.items.properties:s;return s.type==="object"||((p=s.items)===null||p===void 0?void 0:p.type)==="object"?Object.keys(_).forEach(h=>{let g=_[h],v=r9e(h,g);Object.keys(v.onCreate).forEach(x=>{let C=[a,x].filter(T=>T).join(".");f.onCreate[C]=v.onCreate[x]}),Object.keys(v.onUpdate).forEach(x=>{let C=[a,x].filter(T=>T).join(".");f.onUpdate[C]=v.onUpdate[x]})}):a&&(s["x-onCreateValue"]&&(f.onCreate[a]=e9e(s["x-onCreateValue"])),s["x-onUpdateValue"]&&(f.onUpdate[a]=e9e(s["x-onUpdateValue"]))),f}function n9e(a,s){var c;let p={},f=a.required||[],_=a.index||[];for(let h in a.properties){let g=a.properties[h];if(!s.use_id&&h==="_id"||typeof g.type!="string")continue;let v=C=>{switch(C.toLowerCase()){case"string":return"{{String}}";case"integer":case"float":case"number":return"{{Number}}";case"boolean":return"{{Boolean}}";case"null":return"{{null}}";default:throw new Error(`Unsupported type [${C}]`)}},x=(C,T,N)=>{let F={type:"String",index:N.index||!!N["x-foreignKey"]||_.includes(h)||!1,required:N.required||f.includes(h)||!1};switch(T.toLowerCase()){case"string":if(N["x-foreignKey"]){let P=N["x-format"]=="ObjectId"?"Schema.Types.ObjectId":"String";F.type=`{{${P}}}`}else F.type="{{String}}";break;case"integer":case"float":case"number":F.type="{{Number}}";break;case"boolean":F.type="{{Boolean}}";break;case"null":F.type="{{null}}";break;case"array":if(N.items)if(N.items.type=="object"){if(!N.items.properties)throw new Error(`"${C}" Array items as object must have properties defined !`);F.type=[x(C,N.items.type,N.items)]}else if(N.items["x-foreignKey"]){let P=N.items["x-format"]=="ObjectId"?"Schema.Types.ObjectId":"String";F.type=[`{{${P}}}`]}else F.type=[v(N.items.type)];break;case"object":F=n9e(N,s);break;default:throw new Error(`Unsupported type [${N.type}]`)}return F};p[h]=x(h,g.type,g),g.default&&(p[h].default=g.default),(g["x-foreignKey"]||!((c=g.items)===null||c===void 0)&&c["x-foreignKey"])&&(p[h].ref=g["x-foreignKey"]||g.items["x-foreignKey"])}return p}function i9e(a,s,c){if(!a["x-documentConfig"])throw new Error("( jsonSchema.x-documentConfig : object ) is required");let f=a["x-documentConfig"].documentName,_=n9e(a,c||she.default.defaultCompilerOptions),g=nqr.inspect(_,{depth:null}).replace(/'{{/g,"").replace(/}}'/g,"").replace(/"{{/g,"").replace(/}}"/g,""),v=r9e(void 0,a);return iqr.default.modelsTemplate(s,f,g,v,c||she.default.defaultCompilerOptions)}Kg.json2Mongoose=i9e;function sqr(a,s,c,p){return rqr(this,void 0,void 0,function*(){try{aqr.default.process(`Model : ${a} > ${c}`);let f=ZFe.readFileSync(a),_=JSON.parse(f.toString()),h=i9e(_,s,p||she.default.defaultCompilerOptions);return ZFe.writeFileSync(c,h),h}catch(f){throw new Error(`Processing File [${a}] :
|
|
980
980
|
${f.message||f}`)}})}Kg.compileFromFile=sqr});var p9e=vs(W7=>{"use strict";var oqr=W7&&W7.__createBinding||(Object.create?function(a,s,c,p){p===void 0&&(p=c);var f=Object.getOwnPropertyDescriptor(s,c);(!f||("get"in f?!s.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return s[c]}}),Object.defineProperty(a,p,f)}:function(a,s,c,p){p===void 0&&(p=c),a[p]=s[c]}),uqr=W7&&W7.__setModuleDefault||(Object.create?function(a,s){Object.defineProperty(a,"default",{enumerable:!0,value:s})}:function(a,s){a.default=s}),uhe=W7&&W7.__importStar||function(a){if(a&&a.__esModule)return a;var s={};if(a!=null)for(var c in a)c!=="default"&&Object.prototype.hasOwnProperty.call(a,c)&&oqr(s,a,c);return uqr(s,a),s},o9e=W7&&W7.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(W7,"__esModule",{value:!0});W7.genarate=void 0;var T5=uhe(require("fs")),u9e=uhe(WFe()),c9e=uhe(a9e()),cqr=o9e(require("path")),s9e=o9e(ahe()),lqr=(a,s)=>cqr.default.relative(a,s).replace(/\\/g,"/");function l9e(a,s,c,p){T5.readdir(a,(f,_)=>{if(f){console.log(f);return}T5.existsSync(s)&&T5.rmSync(s,{recursive:!0}),T5.mkdirSync(s),T5.existsSync(c)&&T5.rmSync(c,{recursive:!0}),T5.mkdirSync(c),_.forEach(h=>{var g;try{if(!h.endsWith(".json"))return;let v=T5.readFileSync(`${a}/${h}`),C=(g=JSON.parse(v.toString())["x-documentConfig"])===null||g===void 0?void 0:g.documentName;if(!C)throw new Error(`invalid "x-documentConfig.documentName" in ${a}/${h}`);u9e.compileFromFile(`${a}/${h}`,`${c}/${C}.ts`,p||s9e.default.defaultCompilerOptions),c9e.compileFromFile(`${a}/${h}`,`${lqr(s,c)}/${C}`,`${s}/${C}Model.ts`,p||s9e.default.defaultCompilerOptions)}catch(v){console.error("\x1B[31m%s\x1B[0m",`Processing File : ${a}/${h}
|
|
981
|
-
`,v)}})})}W7.genarate=l9e;W7.default={genarate:l9e,typesGen:u9e,modelsGen:c9e}});var zO=Nd(require("fs")),M9e=Nd(require("child_process")),q9e=Nd(m3e());var T3=Nd(require("fs")),P_=Nd(require("path"));var Q1=Nd(require("fs")),JE=Nd(require("path"));function NCr(a,...s){console.log("\x1B[34m%s\x1B[0m","[PROCESSING]",a,s.length>0?s:"")}function ICr(a,...s){console.log("\x1B[32m%s\x1B[0m","[WRITING]",a,s.length>0?s:"")}function BCr(a,...s){console.log("\x1B[36m%s\x1B[0m","[INFO]",a,s.length>0?s:"")}function LCr(a,...s){console.log("\x1B[33m%s\x1B[0m","[WARN]",a,s.length>0?s:"")}function RCr(a,...s){console.log("\x1B[41m%s\x1B[0m","[ERROR]",a,s.length>0?s:""),process.exit(1)}var s0={process:NCr,writing:ICr,info:BCr,warn:LCr,error:RCr};var n5={name:"very-express",version:"0.10.
|
|
981
|
+
`,v)}})})}W7.genarate=l9e;W7.default={genarate:l9e,typesGen:u9e,modelsGen:c9e}});var zO=Nd(require("fs")),M9e=Nd(require("child_process")),q9e=Nd(m3e());var T3=Nd(require("fs")),P_=Nd(require("path"));var Q1=Nd(require("fs")),JE=Nd(require("path"));function NCr(a,...s){console.log("\x1B[34m%s\x1B[0m","[PROCESSING]",a,s.length>0?s:"")}function ICr(a,...s){console.log("\x1B[32m%s\x1B[0m","[WRITING]",a,s.length>0?s:"")}function BCr(a,...s){console.log("\x1B[36m%s\x1B[0m","[INFO]",a,s.length>0?s:"")}function LCr(a,...s){console.log("\x1B[33m%s\x1B[0m","[WARN]",a,s.length>0?s:"")}function RCr(a,...s){console.log("\x1B[41m%s\x1B[0m","[ERROR]",a,s.length>0?s:""),process.exit(1)}var s0={process:NCr,writing:ICr,info:BCr,warn:LCr,error:RCr};var n5={name:"very-express",version:"0.10.2",description:"based on json schema and openapi, generate Express RestApi server with mongoDb ",author:"Justin26l",license:"MIT",main:"index.js",bin:{vex:"./dist/index.js"},scripts:{start:"node ./dist/index.js",dev:"npm run compile && npm run start",build:"npm run lint && npm run compile",lint:"eslint ./src --ext .ts --fix",compile:"node ./scripts/build.js && node ./scripts/copyTsTemplates.js",postversion:"npm run build && git push && git push --tags",test:"npm run compile && vitest run","test:watch":"vitest","test:update":"npm run compile && UPDATE_GOLDEN=1 vitest run","test:e2e":"npm run compile && VEX_E2E=1 vitest run test/e2e"},keywords:["jsonSchema","express","RestApi","mongoDb","mongoose","json2mongoose"],repository:{type:"git",url:"git+https://github.com/Justin26l/VeryExpress.git"},devDependencies:{"@types/js-yaml":"^4.0.9","@types/minimist":"^1.2.5","@types/ms":"^2.1.0","@types/node":"^20.19.39","@types/passport":"^1.0.16","@types/pg":"^8.20.0","@typescript-eslint/eslint-plugin":"^6.18.1","@typescript-eslint/parser":"^6.18.1","diff-match-patch":"^1.0.5",dotenv:"^16.3.1",esbuild:"0.23.0",eslint:"^8.57.1","js-yaml":"^4.1.0","json-schema-to-openapi-schema":"^0.4.0","json-schema-to-typescript":"^13.1.1",json2mongoose:"^0.4.8",knex:"^3.2.9",minimist:"^1.2.8",mongoose:"^8.7.1",mysql2:"^3.22.0",objection:"^3.1.5",pg:"^8.20.0","ts-node":"^10.9.2",typescript:"^5.3.3",vitest:"^2.1.9"}};function Ipe(a){return`/**
|
|
982
982
|
* Generated by veryExpress@${a}
|
|
983
983
|
* https://github.com/Justin26l/VeryExpress
|
|
984
984
|
*/
|
|
@@ -35,6 +35,18 @@ function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unk
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/** Deep-merge two nested `where` fragments; a scalar leaf replaces whatever was there. */
|
|
39
|
+
function mergeTerms(target: Record<string, unknown>, source: Record<string, unknown>): void {
|
|
40
|
+
for (const [key, value] of Object.entries(source)) {
|
|
41
|
+
const existing = target[key];
|
|
42
|
+
if (existing && typeof existing === "object" && value && typeof value === "object") {
|
|
43
|
+
mergeTerms(existing as Record<string, unknown>, value as Record<string, unknown>);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
target[key] = value;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
38
50
|
export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRepository<T> {
|
|
39
51
|
constructor(private repo: Repository<T>) {}
|
|
40
52
|
|
|
@@ -121,6 +133,93 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
121
133
|
return Object.keys(terms).length > 0 ? terms : null;
|
|
122
134
|
}
|
|
123
135
|
|
|
136
|
+
/**
|
|
137
|
+
* Tenant terms for one related entity, or null when it declares no tenant rule.
|
|
138
|
+
*
|
|
139
|
+
* Ownership rules (`user._id`) are not applied to a joined row: joining another user's
|
|
140
|
+
* profile is legitimate, joining another tenant's row is not.
|
|
141
|
+
*/
|
|
142
|
+
private getTenantJoinFilter(entityName: string): Record<string, unknown> | null {
|
|
143
|
+
const terms: Record<string, unknown> = {};
|
|
144
|
+
|
|
145
|
+
for (const rule of entityIsolation[entityName] ?? []) {
|
|
146
|
+
if (rule.source !== "user.tenantId") continue;
|
|
147
|
+
|
|
148
|
+
const value = UserContext.tenantId;
|
|
149
|
+
if (value === undefined) {
|
|
150
|
+
if (rule.onMissing === "deny") {
|
|
151
|
+
throw new VexResErr(403, undefined,
|
|
152
|
+
`${entityName} is isolated by ${rule.source} but the request carries no such value`);
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
terms[rule.field] = value;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return Object.keys(terms).length > 0 ? terms : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Nested `where` fragment scoping every joined row by its own entity's tenant rule.
|
|
165
|
+
*
|
|
166
|
+
* A nested term makes TypeORM constrain the join, so a row whose foreign key points at
|
|
167
|
+
* another tenant is not returned with the other tenant's columns.
|
|
168
|
+
*/
|
|
169
|
+
private getJoinIsolationFilter(join?: Join): Record<string, unknown> | null {
|
|
170
|
+
if (!join || join.length === 0) return null;
|
|
171
|
+
|
|
172
|
+
const out: Record<string, unknown> = {};
|
|
173
|
+
|
|
174
|
+
for (const path of join) {
|
|
175
|
+
const filter = this.joinPathFilter(path);
|
|
176
|
+
if (filter) mergeTerms(out, filter);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One join path as `{ hop: { … { field: tenantId } } }`, or null when no hop is tenant-isolated. */
|
|
183
|
+
private joinPathFilter(path: string): Record<string, unknown> | null {
|
|
184
|
+
const hops: { segment: string; entityName: string }[] = [];
|
|
185
|
+
let metadata = this.repo.metadata;
|
|
186
|
+
|
|
187
|
+
for (const segment of path.split(".")) {
|
|
188
|
+
const relation = metadata.relations.find(r => r.propertyName === segment);
|
|
189
|
+
if (!relation) return null;
|
|
190
|
+
|
|
191
|
+
const target = relation.inverseEntityMetadata;
|
|
192
|
+
// `metadata.name` is the class name the generated registry is keyed by, and stays
|
|
193
|
+
// correct when the entity was declared through `EntitySchema` (string target).
|
|
194
|
+
hops.push({ segment, entityName: target.name });
|
|
195
|
+
metadata = target;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let child: Record<string, unknown> | null = null;
|
|
199
|
+
|
|
200
|
+
for (let i = hops.length - 1; i >= 0; i--) {
|
|
201
|
+
const terms = this.getTenantJoinFilter(hops[i].entityName);
|
|
202
|
+
if (!terms && !child) continue;
|
|
203
|
+
child = { [hops[i].segment]: { ...(terms ?? {}), ...(child ?? {}) } };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return child;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** AND the join terms into the caller's where — every `$or` branch gets them. */
|
|
210
|
+
private withJoinIsolation(
|
|
211
|
+
where: Record<string, unknown> | Array<Record<string, unknown>>,
|
|
212
|
+
join?: Join,
|
|
213
|
+
): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
214
|
+
const joinFilter = this.getJoinIsolationFilter(join);
|
|
215
|
+
if (!joinFilter) return where;
|
|
216
|
+
|
|
217
|
+
if (where instanceof Array) {
|
|
218
|
+
return where.map(branch => ({ ...branch, ...joinFilter }));
|
|
219
|
+
}
|
|
220
|
+
return { ...where, ...joinFilter };
|
|
221
|
+
}
|
|
222
|
+
|
|
124
223
|
/**
|
|
125
224
|
* Remove isolation fields from caller-supplied data. A client must never be able to
|
|
126
225
|
* move a row under another owner or into another tenant.
|
|
@@ -240,7 +339,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
240
339
|
}
|
|
241
340
|
|
|
242
341
|
find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
243
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
342
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
244
343
|
const options: FindManyOptions<T> = {
|
|
245
344
|
select: select as any,
|
|
246
345
|
where,
|
|
@@ -263,7 +362,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
263
362
|
}
|
|
264
363
|
|
|
265
364
|
findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
266
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
365
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
267
366
|
return this.repo.findOne({
|
|
268
367
|
select,
|
|
269
368
|
where,
|
|
@@ -272,7 +371,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
272
371
|
}
|
|
273
372
|
|
|
274
373
|
findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
275
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
374
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
276
375
|
return this.repo.findOne({
|
|
277
376
|
select,
|
|
278
377
|
where,
|
|
@@ -391,7 +490,10 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
391
490
|
* filter still applies. Framework-internal — see VexRepository.
|
|
392
491
|
*/
|
|
393
492
|
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
394
|
-
const where = this.
|
|
493
|
+
const where = this.withJoinIsolation(
|
|
494
|
+
this.mergeFilter(filter, { includeSoftDeleted: true }),
|
|
495
|
+
join,
|
|
496
|
+
) as FindOptionsWhere<T>;
|
|
395
497
|
return this.repo.findOne({
|
|
396
498
|
select,
|
|
397
499
|
where,
|
|
@@ -103,6 +103,9 @@ Generation produces three pieces:
|
|
|
103
103
|
3. Both adapters resolve each rule from that scope and AND every term into the query. Tenant terms
|
|
104
104
|
fail closed (`onMissing: "deny"`); ownership terms keep their historical skip-when-unauthenticated
|
|
105
105
|
behaviour. Isolation fields are stripped from caller data and stamped on create.
|
|
106
|
+
4. The SQL adapter scopes a `join` by the joined entity's own tenant rule — one nested `where` term
|
|
107
|
+
per hop of the join path — so a row whose foreign key points at another tenant does not come back
|
|
108
|
+
with that row's columns. Ownership rules are not applied to joined rows.
|
|
106
109
|
|
|
107
110
|
Full guides: [`docs/features/dataIsolation.md`](../features/dataIsolation.md),
|
|
108
111
|
[`docs/features/tenantIsolation.md`](../features/tenantIsolation.md).
|
|
@@ -64,6 +64,8 @@ is equivalent to `{ "field": "ownerId", "source": "user._id", "onMissing": "skip
|
|
|
64
64
|
- **`skip`** — no value, no term. Used for ownership: public routes keep working.
|
|
65
65
|
- **`deny`** — no value, `403`. Used for tenancy: a document that declares a tenant rule is
|
|
66
66
|
unreachable without a tenant.
|
|
67
|
+
- **Joins** — the SQL adapter scopes a joined entity by that entity's own tenant rule, so a join
|
|
68
|
+
cannot return another tenant's row. Ownership rules are not applied to joined rows.
|
|
67
69
|
|
|
68
70
|
## Validation
|
|
69
71
|
|
|
@@ -123,6 +123,19 @@ to call `addUserTenant` or `linkUserTenant`.
|
|
|
123
123
|
`UserTenant` mapping instead of tombstoning the shared account; `auth.deleteAccount.deleteTables`
|
|
124
124
|
runs in both modes. See [`accountDeletion.md`](accountDeletion.md).
|
|
125
125
|
|
|
126
|
+
## Joins
|
|
127
|
+
|
|
128
|
+
A `join` is scoped by the joined document's own tenant rule, not only by the root document's. The
|
|
129
|
+
SQL adapter adds the rule as a nested `where` term for every hop of the path: `join=["menuItem"]`
|
|
130
|
+
filters `menuItem`, and `join=["menuItem.category"]` filters both `menuItem` and `category`.
|
|
131
|
+
|
|
132
|
+
A row whose foreign key points at another tenant's row is not returned with that row's columns; the
|
|
133
|
+
read comes back empty. A joined document with no tenant rule joins unchanged. A missing tenant with
|
|
134
|
+
`onMissing: "deny"` answers `403`, the same as the root document.
|
|
135
|
+
|
|
136
|
+
Ownership rules (`user._id`) are not applied to joined rows — joining another user's profile is
|
|
137
|
+
legitimate. The Mongoose adapter does not implement joins, so this applies to the SQL target only.
|
|
138
|
+
|
|
126
139
|
## Limits
|
|
127
140
|
|
|
128
141
|
- The claim is a snapshot. A revoked mapping stays usable until the access token expires; `refresh`
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# v0.10.2
|
|
2
|
+
|
|
3
|
+
## Joins are scoped by the joined document's tenant rule
|
|
4
|
+
|
|
5
|
+
A `join` used to filter the root document only. The joined rows came back unfiltered, so a row whose
|
|
6
|
+
foreign key pointed at another tenant's row returned that row's columns.
|
|
7
|
+
|
|
8
|
+
The SQL adapter now adds the tenant rule of every joined document as a nested `where` term:
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
repo.find({}, ["menuItem"]); // menuItem.tenantId = :tenantId
|
|
12
|
+
repo.find({}, ["menuItem.category"]); // menuItem.tenantId and category.tenantId
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- Applies to `find`, `findOne`, `findOneWhere` and `findOneWithDeleted`.
|
|
16
|
+
- The path is resolved hop by hop against the entity metadata, matching the hop-by-hop check in
|
|
17
|
+
`JoinWhitelistMiddleware`.
|
|
18
|
+
- A row whose foreign key points at another tenant is not returned with that row's columns. A
|
|
19
|
+
`findOne` by id returns `null`.
|
|
20
|
+
- A joined document that declares no tenant rule joins as before.
|
|
21
|
+
- A missing tenant with `onMissing: "deny"` answers `403`, the same as the root document.
|
|
22
|
+
|
|
23
|
+
Ownership rules (`user._id`) are not applied to joined rows. Joining another user's profile stays
|
|
24
|
+
allowed; only tenancy crosses a tenant boundary.
|
|
25
|
+
|
|
26
|
+
`select`, `pagination`, `$or`, `$and` and the operator DSL are unchanged: the read still goes
|
|
27
|
+
through `repo.find`, the join terms are merged into the existing `where`.
|
|
28
|
+
|
|
29
|
+
## Mongo target
|
|
30
|
+
|
|
31
|
+
The Mongoose adapter does not implement joins, so this change is SQL-only.
|
|
32
|
+
|
|
33
|
+
## Generated output
|
|
34
|
+
|
|
35
|
+
| File | Change |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `_services/TypeOrmRepositoryAdapter.gen.ts` | join isolation terms on the four read methods |
|
|
38
|
+
|
|
39
|
+
Every scenario's golden output changes: the adapter is a static template copied into every app. An
|
|
40
|
+
app with no `tenant.enable` and no isolation rule takes the same query path as before — the registry
|
|
41
|
+
lookup returns no rule, so the caller's `where` is passed through untouched.
|
|
42
|
+
|
|
43
|
+
## Migration
|
|
44
|
+
|
|
45
|
+
1. Re-run the generator.
|
|
46
|
+
2. No schema or config change. A request that joins a tenant-scoped document can now return fewer
|
|
47
|
+
rows when its data holds a foreign key across tenants.
|
|
48
|
+
|
|
49
|
+
## Tests
|
|
50
|
+
|
|
51
|
+
`npm test` covers the new adapter source and the regenerated goldens. The join scoping is checked
|
|
52
|
+
against a real PostgreSQL: same-tenant join, cross-tenant foreign key, nested path, missing tenant
|
|
53
|
+
under `deny`, and `$or` / pagination / `select` interaction. `npm run test:e2e` type-checks the
|
|
54
|
+
generated app for every config variant, including the tenant ones.
|