@lenne.tech/nest-server 12.12.3 → 12.14.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 +2 -2
- package/.claude/rules/package-management.md +1 -1
- package/.claude/rules/testing.md +3 -3
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/helpers/meta.helper.d.ts +5 -0
- package/dist/core/common/helpers/meta.helper.js +16 -1
- package/dist/core/common/helpers/meta.helper.js.map +1 -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/health-check/core-health-check.service.d.ts +8 -0
- package/dist/core/modules/health-check/core-health-check.service.js +28 -4
- package/dist/core/modules/health-check/core-health-check.service.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/migration-guides/12.13.x-to-12.14.x.md +132 -0
- package/package.json +19 -19
- package/src/core/common/helpers/meta.helper.ts +62 -3
- package/src/core/common/interfaces/server-options.interface.ts +45 -1
- 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/health-check/core-health-check.service.ts +69 -12
- 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
|
@@ -11,7 +11,17 @@
|
|
|
11
11
|
* deployed together bake the SAME commit, but each reads its own at runtime — so
|
|
12
12
|
* comparing them detects a drifted / stale container after a partial rollout.
|
|
13
13
|
*
|
|
14
|
+
* For people there is a second value: the build number (default env
|
|
15
|
+
* `APP_VERSION_BUILD`, fed from the CI pipeline counter — lt-ship 1.3+ passes it,
|
|
16
|
+
* so does the lt-monorepo CI). It always increases and travels with the image
|
|
17
|
+
* through a promotion. With it, the version shown to people becomes
|
|
18
|
+
* `<Major>.<Minor>.<Build>`: Major.Minor from package.json / config (raised by
|
|
19
|
+
* hand), the build number in the patch position. Without it the version stays
|
|
20
|
+
* as configured. The commit remains the identity machines compare.
|
|
21
|
+
*
|
|
14
22
|
* @see getCommit
|
|
23
|
+
* @see getBuild
|
|
24
|
+
* @see composeVersion
|
|
15
25
|
* @see getBuildInfo
|
|
16
26
|
*/
|
|
17
27
|
|
|
@@ -21,6 +31,9 @@ import { join } from 'path';
|
|
|
21
31
|
/** Default environment variable the build commit SHA is baked into. */
|
|
22
32
|
export const DEFAULT_COMMIT_ENV = 'APP_VERSION_COMMIT';
|
|
23
33
|
|
|
34
|
+
/** Default environment variable the build number (CI pipeline counter) is baked into. */
|
|
35
|
+
export const DEFAULT_BUILD_ENV = 'APP_VERSION_BUILD';
|
|
36
|
+
|
|
24
37
|
/** Defined value returned when no commit could be resolved. */
|
|
25
38
|
export const UNKNOWN_COMMIT = 'unknown';
|
|
26
39
|
|
|
@@ -31,13 +44,19 @@ let cachedVersion: null | string | undefined;
|
|
|
31
44
|
* Build identity of the running process.
|
|
32
45
|
*/
|
|
33
46
|
export interface BuildInfo {
|
|
47
|
+
/** Build number (CI pipeline counter) the image was built in, if known. */
|
|
48
|
+
build?: string;
|
|
49
|
+
|
|
34
50
|
/** Git commit SHA the build was produced from, or `'unknown'`. */
|
|
35
51
|
commit: string;
|
|
36
52
|
|
|
37
53
|
/** Environment the process runs in (e.g. `'production'`), if provided. */
|
|
38
54
|
env?: string;
|
|
39
55
|
|
|
40
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* Version of the build for people: `<Major>.<Minor>.<Build>` when a build number is known,
|
|
58
|
+
* otherwise the configured / package.json version, or `'unknown'`.
|
|
59
|
+
*/
|
|
41
60
|
version?: string;
|
|
42
61
|
}
|
|
43
62
|
|
|
@@ -55,6 +74,39 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
|
|
|
55
74
|
return process.env[envName] || UNKNOWN_COMMIT;
|
|
56
75
|
}
|
|
57
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Resolve the build number (CI pipeline counter) the running build was produced in.
|
|
79
|
+
*
|
|
80
|
+
* Reads `process.env[envName]` (default `APP_VERSION_BUILD`). Returns `undefined` when the
|
|
81
|
+
* variable is unset or not a plain number — local builds and builds outside the lt pipelines
|
|
82
|
+
* have none, and the version then stays as configured.
|
|
83
|
+
*
|
|
84
|
+
* @param envName Name of the environment variable holding the build number.
|
|
85
|
+
*/
|
|
86
|
+
export function getBuild(envName: string = DEFAULT_BUILD_ENV): string | undefined {
|
|
87
|
+
const build = (process.env[envName] || '').trim();
|
|
88
|
+
return /^\d+$/.test(build) ? build : undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Compose the version shown to people: `<Major>.<Minor>.<Build>`.
|
|
93
|
+
*
|
|
94
|
+
* Major.Minor come from `version` (package.json or config, raised by hand); the build number
|
|
95
|
+
* takes the patch position. Returns `version` unchanged when the build number is missing or not
|
|
96
|
+
* numeric, and when `version` itself is not a `<major>.<minor>…` version (e.g. `'unknown'`).
|
|
97
|
+
*
|
|
98
|
+
* @param version Configured / package.json version, e.g. `'1.32.0'`.
|
|
99
|
+
* @param build Build number, e.g. `'1875'`.
|
|
100
|
+
*/
|
|
101
|
+
export function composeVersion(version: string, build?: null | string): string {
|
|
102
|
+
const buildNumber = (build ?? '').trim();
|
|
103
|
+
const match = /^(\d+)\.(\d+)/.exec(version);
|
|
104
|
+
if (!match || !/^\d+$/.test(buildNumber)) {
|
|
105
|
+
return version;
|
|
106
|
+
}
|
|
107
|
+
return `${match[1]}.${match[2]}.${buildNumber}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
58
110
|
/**
|
|
59
111
|
* Assemble the build identity of the running process.
|
|
60
112
|
*
|
|
@@ -62,15 +114,22 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
|
|
|
62
114
|
* `version` and `env`. Designed to be surfaced via a public meta / info endpoint
|
|
63
115
|
* and the health check so deployments can be compared at a glance.
|
|
64
116
|
*
|
|
117
|
+
* The `version` is composed with the build number (see {@link composeVersion}) when one is set.
|
|
118
|
+
*
|
|
119
|
+
* @param options.buildEnvName Override the env var the build number is read from.
|
|
65
120
|
* @param options.commitEnvName Override the env var the commit SHA is read from.
|
|
66
121
|
* @param options.env Environment label to include (e.g. from the config).
|
|
67
122
|
* @param options.version Semantic version to include (e.g. from package.json).
|
|
68
123
|
*/
|
|
69
|
-
export function getBuildInfo(
|
|
124
|
+
export function getBuildInfo(
|
|
125
|
+
options: { buildEnvName?: string; commitEnvName?: string; env?: string; version?: string } = {},
|
|
126
|
+
): BuildInfo {
|
|
127
|
+
const build = getBuild(options.buildEnvName);
|
|
70
128
|
return {
|
|
129
|
+
...(build ? { build } : {}),
|
|
71
130
|
commit: getCommit(options.commitEnvName),
|
|
72
131
|
env: options.env,
|
|
73
|
-
version: options.version || getVersion(),
|
|
132
|
+
version: composeVersion(options.version || getVersion(), build),
|
|
74
133
|
};
|
|
75
134
|
}
|
|
76
135
|
|
|
@@ -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
|
/**
|
|
@@ -3007,6 +3046,8 @@ export interface IServerOptions {
|
|
|
3007
3046
|
* Surfaced via the build-identity health indicator alongside the commit SHA.
|
|
3008
3047
|
* Unlike the commit (which uniquely pins the exact build), the version is a
|
|
3009
3048
|
* rarely-bumped semver and may legitimately differ between API and frontend.
|
|
3049
|
+
* When the image carries a build number (`APP_VERSION_BUILD`, since 12.14.0), its
|
|
3050
|
+
* Major.Minor are combined with it to `<Major>.<Minor>.<Build>`.
|
|
3010
3051
|
*
|
|
3011
3052
|
* @since 11.27.0
|
|
3012
3053
|
*/
|
|
@@ -3140,6 +3181,8 @@ export interface IServerOptions {
|
|
|
3140
3181
|
* drifted / stale container can be detected after a partial rollout. The
|
|
3141
3182
|
* commit is read from `process.env.APP_VERSION_COMMIT` (baked at build
|
|
3142
3183
|
* time from the CI commit SHA); `version` comes from {@link IServerOptions.version}.
|
|
3184
|
+
* With `process.env.APP_VERSION_BUILD` (the CI pipeline counter, since 12.14.0) the
|
|
3185
|
+
* indicator also reports `build`, and `version` becomes `<Major>.<Minor>.<Build>`.
|
|
3143
3186
|
*
|
|
3144
3187
|
* @since 11.27.0
|
|
3145
3188
|
*/
|
|
@@ -3165,7 +3208,8 @@ export interface IServerOptions {
|
|
|
3165
3208
|
key?: string;
|
|
3166
3209
|
|
|
3167
3210
|
/**
|
|
3168
|
-
* Database health check options
|
|
3211
|
+
* Database health check options. `timeout` (ms) applies to the MongoDB ping and to every SQL source;
|
|
3212
|
+
* default: 2000 (`DEFAULT_DATABASE_PING_TIMEOUT_MS`)
|
|
3169
3213
|
*/
|
|
3170
3214
|
options?: MongoosePingCheckSettings;
|
|
3171
3215
|
};
|
|
@@ -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;
|