@lenne.tech/nest-server 12.12.3 → 12.13.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/.claude/rules/better-auth.md +4 -1
- package/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/testing.md +3 -3
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
- package/dist/core/modules/file/core-file.controller.js +2 -1
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/core/modules/file/core-file.resolver.js +2 -1
- package/dist/core/modules/file/core-file.resolver.js.map +1 -1
- package/dist/core/modules/file/core-file.service.d.ts +12 -0
- package/dist/core/modules/file/core-file.service.js +44 -0
- package/dist/core/modules/file/core-file.service.js.map +1 -1
- package/dist/core/modules/file/file-access.helper.d.ts +1 -0
- package/dist/core/modules/file/file-access.helper.js +2 -2
- package/dist/core/modules/file/file-access.helper.js.map +1 -1
- package/dist/core/modules/file/s3-file.helper.d.ts +14 -0
- package/dist/core/modules/file/s3-file.helper.js +34 -1
- package/dist/core/modules/file/s3-file.helper.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant-selection.helper.d.ts +14 -0
- package/dist/core/modules/tenant/core-tenant-selection.helper.js +71 -0
- package/dist/core/modules/tenant/core-tenant-selection.helper.js.map +1 -0
- package/dist/core/modules/tenant/core-tenant.decorators.d.ts +2 -0
- package/dist/core/modules/tenant/core-tenant.decorators.js +2 -0
- package/dist/core/modules/tenant/core-tenant.decorators.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.d.ts +8 -0
- package/dist/core/modules/tenant/core-tenant.guard.js +108 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +2 -1
- package/migration-guides/12.12.x-to-12.13.x.md +161 -0
- package/package.json +19 -19
- package/src/core/common/interfaces/server-options.interface.ts +39 -0
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +6 -3
- package/src/core/modules/file/README.md +47 -9
- package/src/core/modules/file/core-file.controller.ts +9 -4
- package/src/core/modules/file/core-file.resolver.ts +2 -1
- package/src/core/modules/file/core-file.service.ts +73 -0
- package/src/core/modules/file/file-access.helper.ts +17 -4
- package/src/core/modules/file/s3-file.helper.ts +75 -2
- package/src/core/modules/tenant/README.md +39 -10
- package/src/core/modules/tenant/core-tenant-selection.helper.ts +135 -0
- package/src/core/modules/tenant/core-tenant.decorators.ts +26 -1
- package/src/core/modules/tenant/core-tenant.guard.ts +168 -1
- package/src/index.ts +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenne.tech/nest-server",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.13.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
|
|
6
6
|
"keywords": [
|
|
@@ -137,13 +137,13 @@
|
|
|
137
137
|
"graphql-upload": "17.1.0",
|
|
138
138
|
"graphql-ws": "6.4.3",
|
|
139
139
|
"http-errors": "2.0.1",
|
|
140
|
-
"jose": "6.2.
|
|
140
|
+
"jose": "6.2.19",
|
|
141
141
|
"js-sha256": "1.1.0",
|
|
142
142
|
"json-to-graphql-query": "2.3.0",
|
|
143
143
|
"lodash": "4.18.1",
|
|
144
144
|
"multer": "2.5.0",
|
|
145
145
|
"node-mailjet": "6.0.11",
|
|
146
|
-
"nodemailer": "10.6.
|
|
146
|
+
"nodemailer": "10.6.3",
|
|
147
147
|
"object-path": "0.11.8",
|
|
148
148
|
"passport": "0.7.0",
|
|
149
149
|
"passport-jwt": "4.0.1",
|
|
@@ -152,7 +152,7 @@
|
|
|
152
152
|
"rxjs": "7.8.2",
|
|
153
153
|
"supertest": "7.3.2",
|
|
154
154
|
"ts-morph": "28.0.0",
|
|
155
|
-
"undici": "7.30.
|
|
155
|
+
"undici": "7.30.5",
|
|
156
156
|
"ws": "8.23.0",
|
|
157
157
|
"yuml-diagram": "1.2.0"
|
|
158
158
|
},
|
|
@@ -173,9 +173,9 @@
|
|
|
173
173
|
"drizzle-orm": "1.0.0-rc.5",
|
|
174
174
|
"ioredis": ">=5.0.0 <7",
|
|
175
175
|
"kysely": ">=0.29.0 <0.30.0",
|
|
176
|
-
"mongodb": ">=7.
|
|
177
|
-
"mongoose": ">=9.
|
|
178
|
-
"mysql2": ">=3.
|
|
176
|
+
"mongodb": ">=7.9.1 <8",
|
|
177
|
+
"mongoose": ">=9.13.0 <10",
|
|
178
|
+
"mysql2": ">=3.25.0 <4",
|
|
179
179
|
"pg": ">=8.23.0 <9",
|
|
180
180
|
"typeorm": ">=1.1.0 <2"
|
|
181
181
|
},
|
|
@@ -245,9 +245,9 @@
|
|
|
245
245
|
}
|
|
246
246
|
},
|
|
247
247
|
"devDependencies": {
|
|
248
|
-
"@aws-sdk/client-s3": "3.
|
|
249
|
-
"@aws-sdk/lib-storage": "3.
|
|
250
|
-
"@aws-sdk/s3-request-presigner": "3.
|
|
248
|
+
"@aws-sdk/client-s3": "3.1184.0",
|
|
249
|
+
"@aws-sdk/lib-storage": "3.1184.0",
|
|
250
|
+
"@aws-sdk/s3-request-presigner": "3.1184.0",
|
|
251
251
|
"@better-auth/core": "1.7.29",
|
|
252
252
|
"@better-auth/passkey": "1.7.29",
|
|
253
253
|
"@compodoc/compodoc": "2.0.0",
|
|
@@ -275,31 +275,31 @@
|
|
|
275
275
|
"@types/passport": "1.0.17",
|
|
276
276
|
"@types/pg": "8.23.1",
|
|
277
277
|
"@vitest/coverage-v8": "5.1.2",
|
|
278
|
-
"ai": "7.0.
|
|
278
|
+
"ai": "7.0.188",
|
|
279
279
|
"better-auth": "1.7.29",
|
|
280
|
-
"bullmq": "6.7.
|
|
280
|
+
"bullmq": "6.7.12",
|
|
281
281
|
"cross-env": "10.1.0",
|
|
282
282
|
"drizzle-orm": "1.0.0-rc.5",
|
|
283
|
-
"ioredis": "6.1.
|
|
283
|
+
"ioredis": "6.1.1",
|
|
284
284
|
"kysely": "0.29.9",
|
|
285
285
|
"mongodb": "7.9.1",
|
|
286
|
-
"mongoose": "9.13.
|
|
287
|
-
"mysql2": "3.
|
|
286
|
+
"mongoose": "9.13.2",
|
|
287
|
+
"mysql2": "3.25.0",
|
|
288
288
|
"nodemon": "3.1.14",
|
|
289
289
|
"otpauth": "9.6.0",
|
|
290
290
|
"oxfmt": "0.80.0",
|
|
291
291
|
"oxlint": "1.95.0",
|
|
292
292
|
"oxlint-tsgolint": "7.0.2009",
|
|
293
293
|
"pg": "8.23.1",
|
|
294
|
-
"playwright-core": "1.65.
|
|
294
|
+
"playwright-core": "1.65.2",
|
|
295
295
|
"rimraf": "6.1.4",
|
|
296
|
-
"smtp-server": "3.21.
|
|
296
|
+
"smtp-server": "3.21.9",
|
|
297
297
|
"tsx": "4.23.15",
|
|
298
298
|
"tus-js-client": "4.3.1",
|
|
299
|
-
"typeorm": "1.1.
|
|
299
|
+
"typeorm": "1.1.4",
|
|
300
300
|
"typescript": "6.0.3",
|
|
301
301
|
"unplugin-swc": "2.0.0",
|
|
302
|
-
"vite": "8.4.
|
|
302
|
+
"vite": "8.4.1",
|
|
303
303
|
"vitest": "5.1.2",
|
|
304
304
|
"zod": "4.6.7"
|
|
305
305
|
},
|
|
@@ -1747,6 +1747,45 @@ export interface IMultiTenancy {
|
|
|
1747
1747
|
store: (modelName: string) => DataStore<any>;
|
|
1748
1748
|
},
|
|
1749
1749
|
) => boolean | Promise<boolean>;
|
|
1750
|
+
|
|
1751
|
+
/**
|
|
1752
|
+
* A cookie the API sets to remember the tenant a browser last selected, for requests that cannot
|
|
1753
|
+
* carry the tenant header: an `<img src>`, a download link, a form post to a file route.
|
|
1754
|
+
*
|
|
1755
|
+
* Boolean shorthand, absent = off (no cookie is written or read; nothing changes).
|
|
1756
|
+
* - `true` / `{}`: on, cookie `lt-tenant-id` (`__Host-lt-tenant-id` where cookies are `Secure`)
|
|
1757
|
+
* - `{ name }`: another base name (letters, digits, `-`, `_`); the `__Host-` prefix is added on its own
|
|
1758
|
+
* - `{ enabled: false }`: off
|
|
1759
|
+
*
|
|
1760
|
+
* Written whenever a request carries a tenant header the tenant guard VALIDATED (an active
|
|
1761
|
+
* membership, or an administrator under `adminBypass`); HttpOnly, SameSite=Lax, Path=/, no Domain,
|
|
1762
|
+
* a session cookie. `Secure` follows the auth cookies (`https://` `baseUrl`, production/staging).
|
|
1763
|
+
*
|
|
1764
|
+
* Read only on routes carrying `@ResolveTenantSelection()` — the framework's file routes — and only
|
|
1765
|
+
* when the request names no tenant in the header. The cookie is a SELECTION, never a right: the
|
|
1766
|
+
* membership is checked on every request, and a cookie naming a tenant the caller no longer belongs
|
|
1767
|
+
* to is ignored and cleared. Keep the default name apart from the app's own tenant cookie
|
|
1768
|
+
* (nuxt-extensions uses `lt-tenant`): with `apiProxy` both live on one host.
|
|
1769
|
+
*
|
|
1770
|
+
* @default undefined (off)
|
|
1771
|
+
* @since 12.13.0
|
|
1772
|
+
*/
|
|
1773
|
+
selectionCookie?: boolean | IMultiTenancySelectionCookie;
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/**
|
|
1777
|
+
* Options of `multiTenancy.selectionCookie`.
|
|
1778
|
+
* @since 12.13.0
|
|
1779
|
+
*/
|
|
1780
|
+
export interface IMultiTenancySelectionCookie {
|
|
1781
|
+
/** `false` switches the cookie off while keeping the settings. */
|
|
1782
|
+
enabled?: boolean;
|
|
1783
|
+
/**
|
|
1784
|
+
* Base name of the cookie. Letters, digits, `-` and `_` only; an invalid name falls back to the
|
|
1785
|
+
* default with a warning. `__Host-` is prepended where cookies are `Secure`.
|
|
1786
|
+
* @default 'lt-tenant-id'
|
|
1787
|
+
*/
|
|
1788
|
+
name?: string;
|
|
1750
1789
|
}
|
|
1751
1790
|
|
|
1752
1791
|
/**
|
|
@@ -132,10 +132,12 @@ What the presets do, and what they deliberately do not:
|
|
|
132
132
|
|
|
133
133
|
- `'owner'` / `'tenant'` read `metadata.ownerId` / `metadata.tenantId`, which `CoreFileService` **stamps
|
|
134
134
|
as it writes** once one of them is active — so an upload through the service is authorizable with no
|
|
135
|
-
project code. ADMIN is never locked out
|
|
135
|
+
project code. ADMIN is never locked out — except under `'tenant'` with `multiTenancy.adminBypass: false`,
|
|
136
|
+
where an administrator needs an active membership in the file's tenant (12.13.0) — writes fall through to the role gate (an upload has no owner
|
|
136
137
|
to compare against yet), a LISTING is refused, and a missing user or a missing owner field FAILS
|
|
137
138
|
CLOSED.
|
|
138
|
-
- **Files written before you enabled the preset carry no such metadata and are therefore ADMIN-only
|
|
139
|
+
- **Files written before you enabled the preset carry no such metadata and are therefore ADMIN-only**
|
|
140
|
+
(under `'tenant'` with `adminBypass: false`: readable by nobody).
|
|
139
141
|
That is the fail-closed direction; a one-off backfill fixes it.
|
|
140
142
|
- `'public'` / `'authenticated'` add no data rule at all. They exist so that "no per-file rule" is a
|
|
141
143
|
DECISION in `config.env.ts` rather than an omission — and that is what silences the boot warning.
|
|
@@ -198,7 +200,8 @@ personal or medical, a per-file rule is not optional.
|
|
|
198
200
|
tenant or not. Declaring `'public'` / `'authenticated'` is a valid answer; leaving it unset is
|
|
199
201
|
not
|
|
200
202
|
- [ ] **On `file.access: 'owner'` / `'tenant'`: is old data backfilled?** Files uploaded before the
|
|
201
|
-
preset was enabled carry no `ownerId` / `tenantId` and stay ADMIN-only until they do
|
|
203
|
+
preset was enabled carry no `ownerId` / `tenantId` and stay ADMIN-only until they do (readable by
|
|
204
|
+
nobody under `'tenant'` with `adminBypass: false`)
|
|
202
205
|
- [ ] **If you wrote your own rule, does it cover all four branches?** `'id'`, `'filename'`, `'filterArgs'` and the writes.
|
|
203
206
|
`'filename'` is not redundant (the presigned path authorizes on the by-name lookup alone, and
|
|
204
207
|
`deleteFileByName()` authorizes by name only), and `'filterArgs'` must be **refused** — a yes/no
|
|
@@ -160,6 +160,27 @@ Three consequences worth knowing about the merged read path:
|
|
|
160
160
|
`s3-files` and `filesystem-files` are created on their first WRITE, never on a read — a deployment
|
|
161
161
|
that only ever uses GridFS never grows them.
|
|
162
162
|
|
|
163
|
+
### Moving GridFS files to S3 under their ids (12.13.0)
|
|
164
|
+
|
|
165
|
+
Forward-only means nothing HAS to move. When the GridFS copies should go (one store to back up, no
|
|
166
|
+
MongoDB for bytes), `CoreFileService.importGridFsFilesToS3()` moves them, each under the id it already
|
|
167
|
+
has, so links and `{{fileUrl:<id>}}` placeholders in other records keep working. Filename, content type,
|
|
168
|
+
upload date and `metadata` (`ownerId`, `tenantId`) are taken over unchanged.
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
// a migration or script with an application context; s3 configured
|
|
172
|
+
const result = await app.get(FileService).importGridFsFilesToS3(); // check the result
|
|
173
|
+
const done = await app.get(FileService).importGridFsFilesToS3({ removeSource: true }); // then remove the copies
|
|
174
|
+
// { imported, skipped, removed, failed: [{ id, error }] }
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
It is idempotent (a file already in S3 is skipped and not read again) and reports a failed file instead
|
|
178
|
+
of stopping. `filter` narrows it to a GridFS `files` filter (`{ 'metadata.tenantId': id }`). Finish with
|
|
179
|
+
`removeSource: true`: reads find the S3 copy first, but a delete removes only the copy it finds first, so
|
|
180
|
+
a file deleted while its GridFS copy is still there becomes readable again. For files from another
|
|
181
|
+
system, `S3FileHelper.importFile(s3Service, collection, { _id, body, filename, … })` is the same step for
|
|
182
|
+
one file.
|
|
183
|
+
|
|
163
184
|
The boot log names the driver in use, so it never has to be inferred from where files stopped
|
|
164
185
|
appearing:
|
|
165
186
|
|
|
@@ -257,22 +278,35 @@ refuses it. Give the copy its own metadata or its own name.
|
|
|
257
278
|
The four common project shapes are presets, so the rule below is only needed for the fifth — a project
|
|
258
279
|
whose rights the framework cannot guess.
|
|
259
280
|
|
|
260
|
-
| `file.access` | project class
|
|
261
|
-
| -------------------- |
|
|
262
|
-
| `'public'` | open: anyone may read and write
|
|
263
|
-
| `'authenticated'` | login-restricted: every signed-in user
|
|
264
|
-
| `'owner'` | per-user: only the uploader (plus ADMIN)
|
|
265
|
-
| `'tenant'` | per-tenant: only the own validated tenant (plus ADMIN) | no |
|
|
266
|
-
| `'custom'` (default) | anything else — you write the rule
|
|
281
|
+
| `file.access` | project class | own `checkRights()`? |
|
|
282
|
+
| -------------------- | ------------------------------------------------------- | -------------------- |
|
|
283
|
+
| `'public'` | open: anyone may read and write | no |
|
|
284
|
+
| `'authenticated'` | login-restricted: every signed-in user | no |
|
|
285
|
+
| `'owner'` | per-user: only the uploader (plus ADMIN) | no |
|
|
286
|
+
| `'tenant'` | per-tenant: only the own validated tenant (plus ADMIN¹) | no |
|
|
287
|
+
| `'custom'` (default) | anything else — you write the rule | yes |
|
|
267
288
|
|
|
268
289
|
`'owner'` and `'tenant'` read `metadata.ownerId` / `metadata.tenantId` and `CoreFileService` **stamps
|
|
269
290
|
them as it writes** while the preset is active, so an upload through the service is authorizable without
|
|
270
|
-
project code. Files written before you enabled it carry no such metadata and stay ADMIN-only
|
|
271
|
-
fail-closed direction, fixable with a one-off backfill. Declaring the class never widens the role gate,
|
|
291
|
+
project code. Files written before you enabled it carry no such metadata and stay ADMIN-only (under
|
|
292
|
+
`'tenant'` with `adminBypass: false`: readable by nobody) — the fail-closed direction, fixable with a one-off backfill. Declaring the class never widens the role gate,
|
|
272
293
|
and it never overrides an explicit `checkRights()` override: the override IS the rule.
|
|
273
294
|
|
|
274
295
|
Everything the presets do is also the checklist for a hand-written rule, so read on either way.
|
|
275
296
|
|
|
297
|
+
¹ Under `multiTenancy.adminBypass: false` an administrator reads a tenant's files only as an active member of
|
|
298
|
+
that tenant, as everywhere else (12.13.0; until 12.12.3 the preset ignored the setting).
|
|
299
|
+
|
|
300
|
+
**Which tenant a file request is in (12.13.0).** The file routes carry `@SkipTenantCheck()` (the role gate
|
|
301
|
+
must not read membership roles) and `@ResolveTenantSelection()`: after the guards allowed the request, the
|
|
302
|
+
tenant guard establishes the tenant from the tenant header, else from the `multiTenancy.selectionCookie`, else
|
|
303
|
+
from the caller's only active membership — each through an active membership; a header naming a foreign
|
|
304
|
+
tenant answers 403. Several memberships and no selection: no tenant, so `'tenant'` answers 404. Before
|
|
305
|
+
12.13.0 these routes had no tenant at all, so `'tenant'` refused every member and an upload carried no
|
|
306
|
+
`tenantId`. An `<img src>` or a download link cannot send the header: switch on
|
|
307
|
+
`multiTenancy.selectionCookie`, and the API remembers the last validated header in an HttpOnly cookie on its
|
|
308
|
+
own host (`lt-tenant-id`, `__Host-lt-tenant-id` where cookies are `Secure`).
|
|
309
|
+
|
|
276
310
|
**Cover the `filterArgs` branch, and REFUSE it.** `findFileInfo()` consults the hook once for the whole
|
|
277
311
|
query, so no answer can mean "…but only their own files". Returning `true` — which the reference rule
|
|
278
312
|
used to do — hands a caller a full inventory of every upload: `CoreFileInfo` carries `filename`,
|
|
@@ -348,6 +382,10 @@ A markup-driven request cannot send an `Authorization` header, and a CORS prefli
|
|
|
348
382
|
credentials at all. So anything stricter than `S_EVERYONE` only works from markup when the session
|
|
349
383
|
travels as a **cookie** on a same-site request.
|
|
350
384
|
|
|
385
|
+
The same holds for the tenant header under multi-tenancy: with `file.access: 'tenant'`, switch on
|
|
386
|
+
`multiTenancy.selectionCookie` so the API knows the tenant of an `<img>` request (see "Which tenant a
|
|
387
|
+
file request is in" above).
|
|
388
|
+
|
|
351
389
|
If some files are genuinely public and others are not, the answer is not a role list — it is a
|
|
352
390
|
per-file rule. Record a visibility flag in the metadata at upload time and branch on it in
|
|
353
391
|
`checkRights()`, or expose a separate public route for exactly the files that are meant to be
|
|
@@ -21,7 +21,7 @@ import { buildContentDisposition } from '../../common/helpers/content-dispositio
|
|
|
21
21
|
import { StreamIdleTimeoutError } from '../../common/helpers/idle-stream.helper.js';
|
|
22
22
|
import { ConfigService } from '../../common/services/config.service.js';
|
|
23
23
|
import { ErrorCode } from '../error-code/error-codes.js';
|
|
24
|
-
import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
|
|
24
|
+
import { ResolveTenantSelection, SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
|
|
25
25
|
import { CoreFileService } from './core-file.service.js';
|
|
26
26
|
import type { FileServiceOptions } from './interfaces/file-service-options.interface.js';
|
|
27
27
|
|
|
@@ -497,13 +497,18 @@ export function setDownloadRangeHeaders(res: Response, range: ByteRange | undefi
|
|
|
497
497
|
* `'admin'` would be satisfied by any member whose MEMBERSHIP role is `admin` —
|
|
498
498
|
* a workspace admin of tenant A could then read tenant B's files.
|
|
499
499
|
*
|
|
500
|
-
* A genuinely tenant-aware policy therefore cannot be expressed by a role name
|
|
501
|
-
*
|
|
502
|
-
*
|
|
500
|
+
* A genuinely tenant-aware policy therefore cannot be expressed by a role name:
|
|
501
|
+
* `file.access: 'tenant'` (or an overridden `CoreFileService.checkRights()`) compares
|
|
502
|
+
* the `tenantId` stamped into the file metadata at upload time.
|
|
503
|
+
*
|
|
504
|
+
* `@ResolveTenantSelection()` gives these routes their tenant all the same (12.13.0):
|
|
505
|
+
* the tenant guard resolves it from the header, the `multiTenancy.selectionCookie` or
|
|
506
|
+
* the caller's only membership — an `<img src>` cannot send the header.
|
|
503
507
|
*/
|
|
504
508
|
@Controller('files')
|
|
505
509
|
@Roles(RoleEnum.ADMIN)
|
|
506
510
|
@SkipTenantCheck()
|
|
511
|
+
@ResolveTenantSelection()
|
|
507
512
|
export abstract class CoreFileController {
|
|
508
513
|
/**
|
|
509
514
|
* Include services
|
|
@@ -3,7 +3,7 @@ import { CurrentUser } from '../../common/decorators/current-user.decorator.js';
|
|
|
3
3
|
import { Roles } from '../../common/decorators/roles.decorator.js';
|
|
4
4
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
5
5
|
import { GraphQLUpload } from '../../common/scalars/upload.scalar.js';
|
|
6
|
-
import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
|
|
6
|
+
import { ResolveTenantSelection, SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
|
|
7
7
|
import { CoreFileInfo } from './core-file-info.model.js';
|
|
8
8
|
import { CoreFileService } from './core-file.service.js';
|
|
9
9
|
import type { FileUpload } from './interfaces/file-upload.interface.js';
|
|
@@ -33,6 +33,7 @@ import type { FileUpload } from './interfaces/file-upload.interface.js';
|
|
|
33
33
|
@Resolver()
|
|
34
34
|
@Roles(RoleEnum.ADMIN)
|
|
35
35
|
@SkipTenantCheck()
|
|
36
|
+
@ResolveTenantSelection()
|
|
36
37
|
export class CoreFileResolver {
|
|
37
38
|
/**
|
|
38
39
|
* Integrate services
|
|
@@ -776,6 +776,76 @@ export abstract class CoreFileService {
|
|
|
776
776
|
return fileInfo;
|
|
777
777
|
}
|
|
778
778
|
|
|
779
|
+
/**
|
|
780
|
+
* Move GridFS files into S3 storage under their EXISTING ids, for a migration of a project that
|
|
781
|
+
* switches `file.storage` to S3 (12.13.0).
|
|
782
|
+
*
|
|
783
|
+
* Every file keeps its id, filename, content type, upload date and `metadata` (owner, `tenantId`),
|
|
784
|
+
* so links, `{{fileUrl:<id>}}` placeholders and references in other records keep working. Runs
|
|
785
|
+
* per file through {@link S3FileHelper.importFile}: idempotent (a file already in S3 is skipped and
|
|
786
|
+
* not read again), and a failure of one file is reported, not thrown, so one run moves everything
|
|
787
|
+
* it can.
|
|
788
|
+
*
|
|
789
|
+
* `removeSource: true` deletes the GridFS copy once its S3 copy is verified, also for a file an
|
|
790
|
+
* earlier run already imported. Do it: reads find the S3 copy first, but a delete removes only the
|
|
791
|
+
* copy it finds first, so a file deleted while its GridFS copy is still there becomes readable again
|
|
792
|
+
* through that copy. Run once without `removeSource` to check the result, then again with it.
|
|
793
|
+
*
|
|
794
|
+
* A system operation: no rights check, no request context. Call it from a migration or a script,
|
|
795
|
+
* never from a route.
|
|
796
|
+
*
|
|
797
|
+
* @param options.filter a GridFS `files` filter, e.g. `{ 'metadata.tenantId': tenantId }`
|
|
798
|
+
* @since 12.13.0
|
|
799
|
+
*/
|
|
800
|
+
async importGridFsFilesToS3(options: { filter?: Record<string, any>; removeSource?: boolean } = {}): Promise<{
|
|
801
|
+
failed: { error: string; id: string }[];
|
|
802
|
+
imported: number;
|
|
803
|
+
removed: number;
|
|
804
|
+
skipped: number;
|
|
805
|
+
}> {
|
|
806
|
+
if (!this.files) {
|
|
807
|
+
throw new Error('importGridFsFilesToS3 needs GridFS, i.e. a MongoDB connection');
|
|
808
|
+
}
|
|
809
|
+
const s3Service = this.options?.s3Service;
|
|
810
|
+
if (!s3Service?.enabled) {
|
|
811
|
+
throw new Error('importGridFsFilesToS3 needs a configured s3 (CoreS3Service is not enabled)');
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const result = { failed: [] as { error: string; id: string }[], imported: 0, removed: 0, skipped: 0 };
|
|
815
|
+
const cursor = this.files.find(options.filter ?? {}, { sort: { _id: 1 } });
|
|
816
|
+
for await (const doc of cursor) {
|
|
817
|
+
const id = getStringIds(doc._id);
|
|
818
|
+
try {
|
|
819
|
+
const { imported } = await S3FileHelper.importFile(s3Service, this.s3Files, {
|
|
820
|
+
_id: id,
|
|
821
|
+
body: () => this.files.openDownloadStream(doc._id),
|
|
822
|
+
contentLength: doc.length,
|
|
823
|
+
contentType: (doc as any).contentType ?? doc.metadata?.contentType,
|
|
824
|
+
filename: doc.filename,
|
|
825
|
+
metadata: doc.metadata,
|
|
826
|
+
uploadDate: doc.uploadDate,
|
|
827
|
+
});
|
|
828
|
+
if (imported) {
|
|
829
|
+
result.imported++;
|
|
830
|
+
} else {
|
|
831
|
+
result.skipped++;
|
|
832
|
+
}
|
|
833
|
+
if (options.removeSource) {
|
|
834
|
+
// Only once the bytes are verifiably in S3 — for a skipped file that is not proven by the
|
|
835
|
+
// metadata alone, somebody may have removed the object since.
|
|
836
|
+
if (!(await s3Service.statObject(id))) {
|
|
837
|
+
throw new Error('S3 metadata exists but the object is missing; GridFS copy kept');
|
|
838
|
+
}
|
|
839
|
+
await this.files.delete(doc._id);
|
|
840
|
+
result.removed++;
|
|
841
|
+
}
|
|
842
|
+
} catch (error) {
|
|
843
|
+
result.failed.push({ error: error instanceof Error ? error.message : String(error), id });
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
return result;
|
|
847
|
+
}
|
|
848
|
+
|
|
779
849
|
/**
|
|
780
850
|
* Delete file reference of avatar
|
|
781
851
|
*/
|
|
@@ -1055,7 +1125,10 @@ export abstract class CoreFileService {
|
|
|
1055
1125
|
: await this.getRawFileInfoByName(input)
|
|
1056
1126
|
: undefined;
|
|
1057
1127
|
|
|
1128
|
+
const multiTenancy = ConfigService.configFastButReadOnly?.multiTenancy;
|
|
1058
1129
|
return decideFileAccess({
|
|
1130
|
+
// Only while multi-tenancy is active: without it there is no tenant authority to withhold.
|
|
1131
|
+
adminBypass: multiTenancy && multiTenancy.enabled !== false ? multiTenancy.adminBypass : undefined,
|
|
1059
1132
|
checkInputType: options?.checkInputType,
|
|
1060
1133
|
currentUser: options?.currentUser,
|
|
1061
1134
|
force: options?.force,
|
|
@@ -21,7 +21,10 @@
|
|
|
21
21
|
* | `'public'` | open: anyone may read and write, the role gate is the whole policy |
|
|
22
22
|
* | `'authenticated'` | login-restricted: every signed-in user may use every file |
|
|
23
23
|
* | `'owner'` | per-user: only the uploader (plus ADMIN) |
|
|
24
|
-
* | `'tenant'` | per-tenant: only within one's own validated tenant (plus ADMIN) |
|
|
24
|
+
* | `'tenant'` | per-tenant: only within one's own validated tenant (plus ADMIN*) |
|
|
25
|
+
*
|
|
26
|
+
* (*) Not under `multiTenancy.adminBypass: false` (12.13.0): an administrator then needs an active
|
|
27
|
+
* membership in the file's tenant, like everybody else.
|
|
25
28
|
*
|
|
26
29
|
* NOTHING CHANGES FOR AN EXISTING PROJECT. `'custom'` is the default and returns `true` for every
|
|
27
30
|
* input, which is byte-for-byte what `CoreFileService.checkRights()` did before. A project that
|
|
@@ -90,6 +93,12 @@ export function fileAccessNeedsRawDocument(preset: FileAccessPreset, checkInputT
|
|
|
90
93
|
* never a raw header — an unvalidated header would be worse than no tenant at all.
|
|
91
94
|
*/
|
|
92
95
|
export function decideFileAccess(options: {
|
|
96
|
+
/**
|
|
97
|
+
* `multiTenancy.adminBypass`. Only an explicit `false` counts: it withholds the ADMIN pass from the
|
|
98
|
+
* `'tenant'` preset, so a platform administrator reads a tenant's files only as an active member of
|
|
99
|
+
* that tenant — what `adminBypass: false` promises for every other tenant-scoped read.
|
|
100
|
+
*/
|
|
101
|
+
adminBypass?: boolean;
|
|
93
102
|
checkInputType?: CheckInputType;
|
|
94
103
|
currentUser?: { hasRole?: (roles: string[]) => boolean; id?: any };
|
|
95
104
|
force?: boolean;
|
|
@@ -97,7 +106,7 @@ export function decideFileAccess(options: {
|
|
|
97
106
|
raw?: null | Record<string, any>;
|
|
98
107
|
tenantId?: string;
|
|
99
108
|
}): boolean {
|
|
100
|
-
const { checkInputType, currentUser, force, preset, raw, tenantId } = options;
|
|
109
|
+
const { adminBypass, checkInputType, currentUser, force, preset, raw, tenantId } = options;
|
|
101
110
|
|
|
102
111
|
// A system caller says so explicitly. This is the documented alternative to the
|
|
103
112
|
// `if (!currentUser) return true` shortcut: the exemption is stated at the call site, in the diff,
|
|
@@ -117,8 +126,12 @@ export function decideFileAccess(options: {
|
|
|
117
126
|
return !!currentUser?.id;
|
|
118
127
|
}
|
|
119
128
|
|
|
120
|
-
// ADMIN is platform authority
|
|
121
|
-
|
|
129
|
+
// ADMIN is platform authority — the same union the role guards apply. Under
|
|
130
|
+
// `multiTenancy.adminBypass: false` that authority stops at tenant content: the `'tenant'` preset
|
|
131
|
+
// then asks an administrator the same question as everybody else (an active membership in the
|
|
132
|
+
// file's tenant). Until 12.12.3 the pass here ignored the setting, so the one tenant-scoped surface
|
|
133
|
+
// the framework decides outside Mongoose let administrators read every tenant's files.
|
|
134
|
+
if (currentUser?.hasRole?.([RoleEnum.ADMIN]) && !(preset === 'tenant' && adminBypass === false)) {
|
|
122
135
|
return true;
|
|
123
136
|
}
|
|
124
137
|
|
|
@@ -142,6 +142,70 @@ export class S3FileHelper {
|
|
|
142
142
|
});
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Import a file that already has an id elsewhere (GridFS, another system) into S3 storage under
|
|
147
|
+
* THAT id — so links, `{{fileUrl:<id>}}` placeholders and references in other records keep working.
|
|
148
|
+
*
|
|
149
|
+
* Idempotent: a file whose metadata already exists under this id is skipped (`imported: false`) and
|
|
150
|
+
* its source is not even opened, so a migration can simply run again after an interruption. An
|
|
151
|
+
* object left in the bucket by an interrupted run without its metadata is overwritten.
|
|
152
|
+
*
|
|
153
|
+
* `metadata` (owner, `tenantId`, anything else) and `uploadDate` are taken over unchanged; the
|
|
154
|
+
* object is verified with a HEAD before the metadata is written, as for every other S3 write.
|
|
155
|
+
*
|
|
156
|
+
* @param options.body the bytes — a stream, or a function opening one (called only when the file
|
|
157
|
+
* is actually imported); `buffer` instead for bytes already in memory
|
|
158
|
+
* @since 12.13.0
|
|
159
|
+
*/
|
|
160
|
+
static async importFile(
|
|
161
|
+
s3Service: CoreS3Service,
|
|
162
|
+
collection: FileCollection,
|
|
163
|
+
options: {
|
|
164
|
+
_id: string | Types.ObjectId;
|
|
165
|
+
body?: (() => Promise<Readable> | Readable) | Readable;
|
|
166
|
+
buffer?: Buffer;
|
|
167
|
+
contentLength?: number;
|
|
168
|
+
contentType?: string;
|
|
169
|
+
filename: string;
|
|
170
|
+
metadata?: Record<string, any>;
|
|
171
|
+
uploadDate?: Date;
|
|
172
|
+
},
|
|
173
|
+
): Promise<{ fileInfo: S3FileInfo; imported: boolean }> {
|
|
174
|
+
const hex = typeof options._id === 'string' ? options._id : options._id?.toHexString?.();
|
|
175
|
+
if (!hex || !/^[0-9a-f]{24}$/i.test(hex)) {
|
|
176
|
+
throw new Error('S3FileHelper.importFile needs the 24-hex id the file already has');
|
|
177
|
+
}
|
|
178
|
+
if (!s3Service?.enabled) {
|
|
179
|
+
throw new Error('S3FileHelper.importFile needs a configured s3 (CoreS3Service is not enabled)');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const existing = await findMetadataById(collection, hex);
|
|
183
|
+
if (existing) {
|
|
184
|
+
if (options.body && typeof options.body !== 'function') {
|
|
185
|
+
// A stream the caller opened in advance would otherwise hold its source (a GridFS cursor) open.
|
|
186
|
+
options.body.destroy();
|
|
187
|
+
}
|
|
188
|
+
return { fileInfo: existing, imported: false };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const body = typeof options.body === 'function' ? await options.body() : (options.body ?? options.buffer);
|
|
192
|
+
if (!body) {
|
|
193
|
+
throw new Error('S3FileHelper.importFile needs either a body stream or a buffer');
|
|
194
|
+
}
|
|
195
|
+
const contentLength = isKnownUploadSize(options.contentLength) ? options.contentLength : options.buffer?.length;
|
|
196
|
+
const _id = newObjectId(hex);
|
|
197
|
+
await s3Service.putObject(hex, body, options.contentType, contentLength);
|
|
198
|
+
|
|
199
|
+
const fileInfo = await S3FileHelper.recordFile(s3Service, collection, _id, {
|
|
200
|
+
contentType: options.contentType,
|
|
201
|
+
filename: options.filename,
|
|
202
|
+
length: contentLength,
|
|
203
|
+
metadata: options.metadata,
|
|
204
|
+
uploadDate: options.uploadDate,
|
|
205
|
+
});
|
|
206
|
+
return { fileInfo, imported: true };
|
|
207
|
+
}
|
|
208
|
+
|
|
145
209
|
/**
|
|
146
210
|
* Verify the object arrived and record its metadata.
|
|
147
211
|
*
|
|
@@ -152,7 +216,13 @@ export class S3FileHelper {
|
|
|
152
216
|
s3Service: CoreS3Service,
|
|
153
217
|
collection: FileCollection,
|
|
154
218
|
_id: Types.ObjectId,
|
|
155
|
-
options: {
|
|
219
|
+
options: {
|
|
220
|
+
contentType?: string;
|
|
221
|
+
filename: string;
|
|
222
|
+
length?: number;
|
|
223
|
+
metadata?: Record<string, any>;
|
|
224
|
+
uploadDate?: Date;
|
|
225
|
+
},
|
|
156
226
|
): Promise<S3FileInfo> {
|
|
157
227
|
// One HEAD answers both questions: whether the bytes arrived, and — for a stream whose length
|
|
158
228
|
// nobody knew up front — how many there are. The stored object is the authority on its size;
|
|
@@ -176,7 +246,10 @@ export class S3FileHelper {
|
|
|
176
246
|
// Records WHERE the bytes went, so a reader never has to probe all three
|
|
177
247
|
// stores to find out. Legacy documents lack it and are handled by probing.
|
|
178
248
|
storage: 's3',
|
|
179
|
-
uploadDate:
|
|
249
|
+
uploadDate:
|
|
250
|
+
options.uploadDate instanceof Date && !Number.isNaN(options.uploadDate.getTime())
|
|
251
|
+
? options.uploadDate
|
|
252
|
+
: new Date(),
|
|
180
253
|
};
|
|
181
254
|
await collection.insertOne(fileInfo);
|
|
182
255
|
return fileInfo;
|
|
@@ -76,16 +76,17 @@ projects whose users are per-tenant.
|
|
|
76
76
|
|
|
77
77
|
## Components
|
|
78
78
|
|
|
79
|
-
| Component
|
|
80
|
-
|
|
|
81
|
-
| `CoreTenantMemberModel`
|
|
82
|
-
| `CoreTenantGuard`
|
|
83
|
-
| `CoreTenantService`
|
|
84
|
-
| `@SkipTenantCheck()`
|
|
85
|
-
| `@
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
79
|
+
| Component | Purpose |
|
|
80
|
+
| --------------------------- | -------------------------------------------------------- |
|
|
81
|
+
| `CoreTenantMemberModel` | User-tenant membership (join table with role + status) |
|
|
82
|
+
| `CoreTenantGuard` | APP_GUARD validating tenant header + membership |
|
|
83
|
+
| `CoreTenantService` | Membership CRUD (add, remove, update role, find) |
|
|
84
|
+
| `@SkipTenantCheck()` | Method/class decorator to skip tenant validation |
|
|
85
|
+
| `@ResolveTenantSelection()` | Establish the tenant on a route without header (12.13.0) |
|
|
86
|
+
| `@CurrentTenant()` | Parameter decorator extracting validated tenant ID |
|
|
87
|
+
| `TenantMemberStatus` | Enum: ACTIVE, INVITED, SUSPENDED |
|
|
88
|
+
| `DefaultHR` | Type-safe constants for default hierarchy roles |
|
|
89
|
+
| `createHierarchyRoles()` | Generate type-safe constants from custom hierarchy |
|
|
89
90
|
|
|
90
91
|
## Usage
|
|
91
92
|
|
|
@@ -222,6 +223,32 @@ async listMyTenants() { ... }
|
|
|
222
223
|
Note: `@SkipTenantCheck()` with hierarchy roles still checks `user.roles` (no tenant context).
|
|
223
224
|
It also suppresses tenant membership validation for `S_USER`/`S_VERIFIED` system role paths — when set, these roles still enforce authentication/verification but skip the membership check even when a tenant header is present.
|
|
224
225
|
|
|
226
|
+
### Routes Without Tenant Header (`@ResolveTenantSelection()`, `selectionCookie`, 12.13.0)
|
|
227
|
+
|
|
228
|
+
A browser cannot send the tenant header with `<img src>`, a download link or a plain form post, and the
|
|
229
|
+
app's own tenant cookie lives on the app's host. A route carrying `@ResolveTenantSelection()` (the
|
|
230
|
+
framework's file controller and resolver do, also with `@SkipTenantCheck()`) gets its tenant after the
|
|
231
|
+
access decision, in this order:
|
|
232
|
+
|
|
233
|
+
1. the tenant header: an active membership; a foreign tenant answers 403 (on a public route: no tenant)
|
|
234
|
+
2. the selection cookie, when configured: an active membership; otherwise ignored and cleared
|
|
235
|
+
3. the caller's only active membership
|
|
236
|
+
|
|
237
|
+
Every candidate needs an active membership in an active tenant; an administrator under `adminBypass`
|
|
238
|
+
gets the named tenant or none. Several memberships and no selection: no tenant, never a guess.
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
multiTenancy: {
|
|
242
|
+
selectionCookie: true, // cookie lt-tenant-id, __Host-lt-tenant-id where cookies are Secure
|
|
243
|
+
// selectionCookie: { name: 'my-tenant' } // another base name; `{ enabled: false }` off
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
The guard writes the cookie whenever a request's tenant header passed its check (HttpOnly,
|
|
248
|
+
SameSite=Lax, Path=/, no Domain, session cookie; `Secure` like the auth cookies). It is a selection, not
|
|
249
|
+
a right. Keep its name apart from the app's tenant cookie (nuxt-extensions: `lt-tenant`): behind
|
|
250
|
+
`apiProxy` both live on one host.
|
|
251
|
+
|
|
225
252
|
### Admin Bypass
|
|
226
253
|
|
|
227
254
|
System admins (`RoleEnum.ADMIN`) bypass the membership check by default.
|
|
@@ -238,6 +265,8 @@ two paths that went around that promise follow it too:
|
|
|
238
265
|
`assertCredentialChangeAllowed()` to adjust.
|
|
239
266
|
- **AI tools** (chat and MCP): no ADMIN bypass in the tool registry; tenant-role tools need a
|
|
240
267
|
membership role like anyone's.
|
|
268
|
+
- **Files** (12.13.0): the `file.access: 'tenant'` preset no longer lets an administrator read another
|
|
269
|
+
tenant's files; an administrator reads them as an active member of that tenant.
|
|
241
270
|
|
|
242
271
|
### Deactivated Tenants (`isTenantActive`, since 11.42.0)
|
|
243
272
|
|