@lenne.tech/nest-server 12.12.2 → 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.
Files changed (55) hide show
  1. package/.claude/rules/better-auth.md +4 -1
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/package-management.md +6 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  7. package/dist/core/common/persistence/sql/positional-placeholders.d.ts +7 -0
  8. package/dist/core/common/persistence/sql/positional-placeholders.js +18 -0
  9. package/dist/core/common/persistence/sql/positional-placeholders.js.map +1 -0
  10. package/dist/core/common/persistence/sql/sql-executor.factory.js +2 -1
  11. package/dist/core/common/persistence/sql/sql-executor.factory.js.map +1 -1
  12. package/dist/core/modules/file/core-file.controller.js +2 -1
  13. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  14. package/dist/core/modules/file/core-file.resolver.js +2 -1
  15. package/dist/core/modules/file/core-file.resolver.js.map +1 -1
  16. package/dist/core/modules/file/core-file.service.d.ts +12 -0
  17. package/dist/core/modules/file/core-file.service.js +44 -0
  18. package/dist/core/modules/file/core-file.service.js.map +1 -1
  19. package/dist/core/modules/file/file-access.helper.d.ts +1 -0
  20. package/dist/core/modules/file/file-access.helper.js +2 -2
  21. package/dist/core/modules/file/file-access.helper.js.map +1 -1
  22. package/dist/core/modules/file/s3-file.helper.d.ts +14 -0
  23. package/dist/core/modules/file/s3-file.helper.js +34 -1
  24. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  25. package/dist/core/modules/tenant/core-tenant-selection.helper.d.ts +14 -0
  26. package/dist/core/modules/tenant/core-tenant-selection.helper.js +71 -0
  27. package/dist/core/modules/tenant/core-tenant-selection.helper.js.map +1 -0
  28. package/dist/core/modules/tenant/core-tenant.decorators.d.ts +2 -0
  29. package/dist/core/modules/tenant/core-tenant.decorators.js +2 -0
  30. package/dist/core/modules/tenant/core-tenant.decorators.js.map +1 -1
  31. package/dist/core/modules/tenant/core-tenant.guard.d.ts +8 -0
  32. package/dist/core/modules/tenant/core-tenant.guard.js +108 -1
  33. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/index.js.map +1 -1
  37. package/docs/REQUEST-LIFECYCLE.md +2 -1
  38. package/migration-guides/12.12.2-to-12.12.3.md +73 -0
  39. package/migration-guides/12.12.x-to-12.13.x.md +161 -0
  40. package/package.json +19 -19
  41. package/src/core/common/interfaces/server-options.interface.ts +39 -0
  42. package/src/core/common/persistence/sql/positional-placeholders.ts +48 -0
  43. package/src/core/common/persistence/sql/sql-executor.factory.ts +4 -8
  44. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +6 -3
  45. package/src/core/modules/file/README.md +47 -9
  46. package/src/core/modules/file/core-file.controller.ts +9 -4
  47. package/src/core/modules/file/core-file.resolver.ts +2 -1
  48. package/src/core/modules/file/core-file.service.ts +73 -0
  49. package/src/core/modules/file/file-access.helper.ts +17 -4
  50. package/src/core/modules/file/s3-file.helper.ts +75 -2
  51. package/src/core/modules/tenant/README.md +39 -10
  52. package/src/core/modules/tenant/core-tenant-selection.helper.ts +135 -0
  53. package/src/core/modules/tenant/core-tenant.decorators.ts +26 -1
  54. package/src/core/modules/tenant/core-tenant.guard.ts +168 -1
  55. package/src/index.ts +1 -0
@@ -0,0 +1,73 @@
1
+ # Migration Guide: 12.12.2 → 12.12.3
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Drizzle engine: a `$<digits>` inside a quoted name, a literal, a dollar-quoted body or a comment is no longer bound as a parameter. A role name such as `app$7` no longer stops the boot, and a `$<digits>` inside a comment or literal of a hand-written `runSqlMigration(…, { engine: 'drizzle' })` statement no longer fails the migration (§1) |
10
+ | **Security** | None for the package. GHSA-c859-jr93-m5j4 (minimatch, moderate) is declared as a residual in this repository's dev tooling; a project that reports it through nodemon or `@swc/cli` can do the same (§2) |
11
+ | **Migration Effort** | None |
12
+
13
+ ## Quick Migration
14
+
15
+ ```bash
16
+ pnpm add @lenne.tech/nest-server@12.12.3
17
+ pnpm run update # nest-server-starter based projects
18
+ pnpm run build
19
+ pnpm test
20
+ ```
21
+
22
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
23
+
24
+ ## 1. Bugfix: positional parameters on the Drizzle engine
25
+
26
+ **No action needed.** Only projects with `database.sqlEngine: 'drizzle'` on PostgreSQL are affected; TypeORM and
27
+ Kysely hand a statement to the server unchanged and never had the problem.
28
+
29
+ The Drizzle engine turns the positional placeholders of a statement (`$1`, `$2`, …) back into bound parameters. Up to
30
+ 12.12.2 it did that for every `$<digits>` in the text, also where PostgreSQL reads plain text:
31
+
32
+ | Where the `$<digits>` stood | What happened |
33
+ |---|---|
34
+ | A quoted name: the application role `app$7` (allowed since 12.12.2) | The schema GRANT went out as `TO "app$1"` with a stray value, and the boot stopped |
35
+ | A literal: a column default such as `'Price $5'` | The schema change failed at boot |
36
+ | A comment or literal in a hand-written statement of `runSqlMigration(…, { engine: 'drizzle' })` (`-- replaces $1`, `'Price $5'`) | It was bound as a parameter, and the migration failed with a parameter error |
37
+
38
+ Since 12.12.3 the engine reads placeholders the way the server does: never inside a quoted name, a literal (`'…'`,
39
+ `E'…'`), a dollar-quoted body (`$tag$ … $tag$`) or a comment (`-- …`, `/* … */`). A nested block comment ends at its
40
+ first `*/` there; keep placeholders out of nested comments.
41
+
42
+ ## 2. Under the hood: GHSA-c859-jr93-m5j4 (minimatch)
43
+
44
+ The advisory (minimatch `>= 7.4.0 <= 11.0.7`: the output of `minimatch.escape()` matches more or less than the literal)
45
+ reached GitHub's global advisory database on 2026-12-01. It is fixed only in minimatch 11.0.8, and nodemon 3.1.14 and
46
+ `@swc/cli` 0.8.2, both on their newest release, still depend on minimatch 10 and 9. Neither calls
47
+ `minimatch.escape()`. Nothing of it reaches the published package.
48
+
49
+ A project whose `pnpm audit` reports it through these tools can declare the same residual in `pnpm-workspace.yaml`
50
+ (nest-server-starter does), with the consumers its own lockfile names:
51
+
52
+ ```yaml
53
+ auditConfig:
54
+ ignoreGhsas:
55
+ - GHSA-c859-jr93-m5j4
56
+ unusableFixConsumers:
57
+ GHSA-c859-jr93-m5j4: '@swc/cli@0.8.2 + nodemon@3.1.14 cannot use 11.0.8'
58
+ ```
59
+
60
+ Do not override minimatch across the major for these tools: an override target stays inside its major, and
61
+ minimatch 11 removed `makeRe()` and `Minimatch#regexp`.
62
+
63
+ ## Troubleshooting
64
+
65
+ | Symptom | Cause | Fix |
66
+ |---|---|---|
67
+ | Boot on the Drizzle engine stops at a GRANT or a schema change with a parameter error (`bind message supplies …`, `could not determine data type of parameter …`) | A role name or a default with `$<digits>`, or a `$<digits>` in a comment or literal of a Drizzle migration, on 12.12.2 or earlier | Update to 12.12.3 |
68
+ | `pnpm audit` reports GHSA-c859-jr93-m5j4 via nodemon or `@swc/cli` | No release of these tools uses minimatch 11.0.8 yet | Declare it as in §2 |
69
+
70
+ ## Module Documentation
71
+
72
+ - `docs/choosing-a-database.md` — SQL engines and PostgreSQL roles
73
+ - `.claude/rules/package-management.md` — suppressions and `unusableFixConsumers`
@@ -0,0 +1,161 @@
1
+ # Migration Guide: 12.12.x → 12.13.x
2
+
3
+ **12.13.0 contains changes a multi-tenant project has to check** (§1, §2). A project without
4
+ `multiTenancy`, or with `file.access` other than `'tenant'` and no client that sends a foreign tenant
5
+ header to the file routes, sees no difference in behaviour; it only raises its dependencies (§5, §6).
6
+
7
+ ## Overview
8
+
9
+ | Category | Details |
10
+ |---|---|
11
+ | **Breaking Changes** | Under `multiTenancy.adminBypass: false` the `file.access: 'tenant'` preset no longer lets administrators read every tenant's files (§1). The file routes validate the tenant header: a tenant the caller does not belong to answers 403 (§2) |
12
+ | **New Features** | The file routes establish the request's tenant also without header: `multiTenancy.selectionCookie` and the caller's only membership (§2, §3). `CoreFileService.importGridFsFilesToS3()` and `S3FileHelper.importFile()` move files to S3 under their ids (§4) |
13
+ | **Bugfixes** | `file.access: 'tenant'` answered every member's download with 404, and a multipart upload carried no `tenantId` (§2) |
14
+ | **Security** | Peer ranges start at `mongoose` 9.13.0, `mongodb` 7.9.1 and `mysql2` 3.25.0 (§5); `undici` 7.30.5 and `nodemailer` 10.6.3 close repository advisories `pnpm audit` does not report yet (§6) |
15
+ | **Migration Effort** | None without multi-tenancy. With it: check §1 and §2; switch on `selectionCookie` where browsers load tenant files through `<img>` or links. A project that installs with `--frozen-lockfile` before 2026-12-05 13:05 UTC: §6 |
16
+
17
+ ## Quick Migration
18
+
19
+ ```bash
20
+ pnpm add @lenne.tech/nest-server@12.13.0
21
+ pnpm run update # nest-server-starter based projects
22
+ pnpm run build
23
+ pnpm test
24
+ ```
25
+
26
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
27
+
28
+ ## 1. Breaking: `adminBypass: false` now reaches the `'tenant'` file preset
29
+
30
+ `multiTenancy.adminBypass: false` promises that a platform administrator has no way into tenant
31
+ content. The Mongoose tenant plugin, the tenant guard, the credential check and the AI tool registry
32
+ kept it; the `file.access: 'tenant'` preset did not and let every ADMIN read every tenant's files.
33
+
34
+ Since 12.13.0 an administrator reads a file under that setting only as an active member of the file's
35
+ tenant, like everybody else. Nothing changes with `adminBypass` unset or `true`, with another preset, or
36
+ with an own `checkRights()`.
37
+
38
+ **Check:** a support or back-office flow in which administrators open tenant files. Under
39
+ `adminBypass: false` it needs a membership in that tenant, or a route of the project's own that calls
40
+ the service with `force: true` after its own decision.
41
+
42
+ ## 2. Breaking: the file routes establish the tenant
43
+
44
+ The file controller and resolver carry `@SkipTenantCheck()`, so the tenant guard used to return before
45
+ it set a tenant. With `file.access: 'tenant'` that meant: every download of a member answered 404, and
46
+ an upload was stored without `tenantId`. Since 12.13.0 both carry `@ResolveTenantSelection()`, and after
47
+ the role check the tenant guard establishes the tenant:
48
+
49
+ | Source | Rule |
50
+ |---|---|
51
+ | Tenant header | An active membership in an active tenant. A tenant the caller does not belong to answers **403** (`#LTNS_0103`); before 12.13.0 these routes ignored the header |
52
+ | `multiTenancy.selectionCookie` (§3) | Only when configured and no header was sent. An active membership; otherwise ignored and cleared |
53
+ | The caller's only active membership | Only without header and cookie. Several memberships: no tenant, never a guess |
54
+
55
+ An administrator under `adminBypass` gets the named tenant without membership, or no tenant. An API
56
+ token gets its tenant from the header (or its restriction) only, never from the cookie or the only
57
+ membership.
58
+
59
+ **Check:** a client that sends a tenant header to the file routes the user is not a member of (a stale
60
+ selection, a hard-coded id) now gets 403 instead of an answer without tenant. With
61
+ `file.access: 'custom'` an own `checkRights()` now finds `RequestContext.tenantId` set on these routes,
62
+ and uploads through `CoreFileService` get `metadata.tenantId` stamped while the `'tenant'` preset is
63
+ active. A subclass of `CoreFileController` / `CoreFileResolver` inherits the decorator.
64
+
65
+ ## 3. New: `multiTenancy.selectionCookie`
66
+
67
+ An `<img src>`, a download link or a plain form post cannot send the tenant header, and the app's own
68
+ tenant cookie (nuxt-extensions: `lt-tenant`) lives on the app's host. With the selection cookie the API
69
+ remembers the tenant of the last request whose header it validated, on its own host:
70
+
71
+ ```typescript
72
+ multiTenancy: {
73
+ selectionCookie: true, // or { name: 'my-tenant' }; { enabled: false } keeps the settings and switches it off
74
+ }
75
+ ```
76
+
77
+ | Property | Value |
78
+ |---|---|
79
+ | Name | `lt-tenant-id`; `__Host-lt-tenant-id` where cookies are `Secure` (an `https://` `baseUrl`, production, staging) |
80
+ | Attributes | HttpOnly, SameSite=Lax, Path=/, no Domain, session cookie |
81
+ | Written | When a request's tenant header passed the tenant guard (any route); not for API tokens |
82
+ | Read | Only on routes with `@ResolveTenantSelection()`, only without header, always through an active membership |
83
+
84
+ The cookie is a selection, never a right. App and API on sibling subdomains of one site send it with an
85
+ `<img>` (SameSite=Lax); a project whose API lives on another site still needs the header. Do not name it
86
+ `lt-tenant`: behind `apiProxy` app and API share one host.
87
+
88
+ ## 4. New: move GridFS files to S3 under their ids
89
+
90
+ ```typescript
91
+ // a migration or script with an application context, s3 configured
92
+ const fileService = app.get(FileService);
93
+ console.log(await fileService.importGridFsFilesToS3()); // check the result first
94
+ console.log(await fileService.importGridFsFilesToS3({ removeSource: true })); // then remove the GridFS copies
95
+ // { imported, skipped, removed, failed: [{ id, error }] }
96
+ ```
97
+
98
+ Every file keeps its id, filename, content type, upload date and `metadata` (`ownerId`, `tenantId`), so
99
+ links and `{{fileUrl:<id>}}` placeholders keep working. The run is idempotent and reports a failed file
100
+ instead of stopping; `filter` narrows it (`{ 'metadata.tenantId': tenantId }`). **Finish with
101
+ `removeSource: true`**: reads find the S3 copy first, but a delete removes only the copy it finds first,
102
+ so a file deleted while its GridFS copy still exists becomes readable again. `S3FileHelper.importFile()`
103
+ is the same step for one file from another source.
104
+
105
+ ## 5. Security: peer ranges of `mongoose`, `mongodb` and `mysql2`
106
+
107
+ | Peer | Range | Why |
108
+ |---|---|---|
109
+ | `mongoose` | `>=9.13.0 <10` | Below 9.12.2: GHSA-xfcm-rmv3-crmq (high: `sanitizeProjection` can be bypassed to return fields deselected with `select: false`) and GHSA-25v4-hrwm-qj9f (moderate: `sanitizeFilter` lets internal top-level operators through); nest-server sets neither option itself. 9.12.x pins `mongodb ~7.8`, so the `mongodb` floor below needs 9.13 |
110
+ | `mongodb` | `>=7.9.1 <8` | GHSA-779g-w5r4-wr2x (moderate: the connection string, password included, unmasked in a parse error) and GHSA-prmg-mvj2-c4f7 (moderate: identity smuggling through a NUL byte in SASL PLAIN) |
111
+ | `mysql2` | `>=3.25.0 <4` | GHSA-f763-mv98-7rv9 (high: SQL injection under `NO_BACKSLASH_ESCAPES`; the framework's own session sets backslash escapes) |
112
+
113
+ A project below one of them gets a peer warning: `pnpm run update` (nest-server-starter based projects raise
114
+ the optional peers to the framework's versions: mongoose 9.13.2, mongodb 7.9.1, mysql2 3.25.0), or raise the
115
+ pins by hand. mongoose and mongodb move together: mongoose 9.13 with a `mongodb` pin below 7.9 installs two
116
+ driver copies, and Better-Auth's MongoDB adapter then fails its `ObjectId` check (sign-in answers 401).
117
+
118
+ **Do not raise `mysql2` to 3.26 on its own yet.** 3.26.0 closes two moderate advisories (GHSA-mccj-fxgw-vqw2,
119
+ GHSA-cc6q-ch5m-cffx) by refusing to fetch the server's RSA key over a connection without TLS. On MySQL 8.4, whose
120
+ default `caching_sha2_password` needs that key for the first sign-in of an account after a server start, every
121
+ connection without TLS then fails with `PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED` until something else has signed that
122
+ account in. Connect over TLS (`?ssl=…` in the URL), or accept the risk on a trusted network with
123
+ `?allowPublicKeyRetrieval=true`, before you take 3.26. MariaDB is not affected.
124
+
125
+ ## 6. Dependencies
126
+
127
+ | Package | Version | Note |
128
+ |---|---|---|
129
+ | `undici` | 7.30.2 → 7.30.5 | 13 advisories from 2026-12-04 cover 7.30.2, seven of them high (e.g. GHSA-fgj4-8x8v-fqhm: TLS servername reused on cross-origin redirects; GHSA-h5rf-4xrf-76mc: a parser assertion ends the process from `request()` / `fetch()`). The framework uses it for `outboundFetch()`, the guarded fetch for user-entered URLs. Repository advisories, not yet in GitHub's global database: `pnpm audit` does not report them |
130
+ | `nodemailer` | 10.6.1 → 10.6.3 | GHSA-w5r8-mmxv-957g (moderate: `attachDataUrls` leaks inline images into later messages). Repository advisory |
131
+
132
+ `@apollo/server` stays on 5.5.1: 5.5.2 to 5.5.4 bring back `@graphql-tools/utils` 12.0.1 (GHSA-c4qx-w738-7hr3,
133
+ high). The new GHSA-xf7q-mfv9-cvhx (high, fixed in 5.5.4) affects `startStandaloneServer` only, which neither
134
+ nest-server nor the starter calls; do not pin a newer `@apollo/server` in a project either.
135
+
136
+ **undici 7.30.5 is younger than pnpm's default release-age window (24 hours) until 2026-12-05 13:05 UTC.** An
137
+ install that resolves anew (`pnpm add`, `pnpm run update`) warns and continues. An install with
138
+ `--frozen-lockfile` (CI, Docker) refuses it until then; add the exact version to `pnpm-workspace.yaml` and remove
139
+ the entry after that time:
140
+
141
+ ```yaml
142
+ minimumReleaseAgeExclude:
143
+ - 'undici@7.30.5' # nest-server 12.13.0, undici advisories of 2026-12-04; remove after 2026-12-05 13:05 UTC
144
+ ```
145
+
146
+ ## Troubleshooting
147
+
148
+ | Symptom | Cause | Fix |
149
+ |---|---|---|
150
+ | `403 #LTNS_0103` on `GET /files/id/:id` with a tenant header | The caller is no active member of that tenant (§2) | Send the tenant the user selected, or no header |
151
+ | Administrator gets 404 for a tenant file | `adminBypass: false` with `file.access: 'tenant'` (§1) | A membership in that tenant, or a project route with `force: true` |
152
+ | `<img>` of a tenant file answers 404 for a user with several tenants | No header and no selection (§2) | `multiTenancy.selectionCookie: true`; the app's next API request with the header sets it |
153
+ | A deleted file is still downloadable after the S3 move | Its GridFS copy was kept (§4) | `importGridFsFilesToS3({ removeSource: true })` |
154
+ | `ERR_PNPM_NO_MATURE_MATCHING_VERSION` for `undici@7.30.5` | `--frozen-lockfile` install inside the 24-hour window (§6) | `minimumReleaseAgeExclude: ['undici@7.30.5']`, removed after 2026-12-05 13:05 UTC |
155
+ | Peer warning for `mongoose`, `mongodb` or `mysql2` | Pin below the new floor (§5) | `pnpm run update`, or raise mongoose and mongodb together |
156
+
157
+ ## Module Documentation
158
+
159
+ - `src/core/modules/file/README.md` — "Before you write a rule", "Moving GridFS files to S3 under their ids"
160
+ - `src/core/modules/tenant/README.md` — "Routes Without Tenant Header", "Admin Bypass"
161
+ - `.claude/rules/configurable-features.md` — Multi-Tenancy row
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.12.2",
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.18",
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.1",
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.2",
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.8.0 <8",
177
- "mongoose": ">=9.12.0 <10",
178
- "mysql2": ">=3.24.6 <4",
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.1179.0",
249
- "@aws-sdk/lib-storage": "3.1179.0",
250
- "@aws-sdk/s3-request-presigner": "3.1179.0",
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.184",
278
+ "ai": "7.0.188",
279
279
  "better-auth": "1.7.29",
280
- "bullmq": "6.7.10",
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.0",
283
+ "ioredis": "6.1.1",
284
284
  "kysely": "0.29.9",
285
285
  "mongodb": "7.9.1",
286
- "mongoose": "9.13.1",
287
- "mysql2": "3.24.6",
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.1",
294
+ "playwright-core": "1.65.2",
295
295
  "rimraf": "6.1.4",
296
- "smtp-server": "3.21.7",
296
+ "smtp-server": "3.21.9",
297
297
  "tsx": "4.23.15",
298
298
  "tus-js-client": "4.3.1",
299
- "typeorm": "1.1.3",
299
+ "typeorm": "1.1.4",
300
300
  "typescript": "6.0.3",
301
301
  "unplugin-swc": "2.0.0",
302
- "vite": "8.4.0",
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
  /**
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Positional placeholders (`$1`, `$2`, …) of a PostgreSQL statement, found the way the server finds them: never inside
3
+ * a quoted identifier (`"app$7"`), a string literal (`'…'`, `E'…'`), a dollar-quoted body (`$lt$ … $lt$`) or a
4
+ * comment (`-- …`, `/* … *\/`; a nested block comment ends at its first `*\/` here).
5
+ *
6
+ * pg, TypeORM and Kysely hand a statement to the server as it is, so the server's parser decides. Drizzle needs each
7
+ * placeholder turned back into a bound parameter, and a split on every `$<digits>` also cut a role name such as
8
+ * `app$7` (allowed since 12.12.2) or a column default such as `'Price $5'` in two, with a parameter in between.
9
+ * Comments count because the statements of `runSqlMigration({ engine: 'drizzle' })` are hand-written: the apostrophe
10
+ * in `-- don't` must not open a literal that swallows the placeholders behind it.
11
+ */
12
+ const QUOTED_OR_PLACEHOLDER =
13
+ /("(?:[^"]|"")*"|[Ee]'(?:[^'\\]|\\[\s\S]|'')*'|'(?:[^']|'')*'|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\2\$|--[^\n]*|\/\*[\s\S]*?\*\/)|\$(\d+)/g;
14
+
15
+ /** The statement as raw text and 1-based parameter numbers, in order; quoted text stays inside the raw parts. */
16
+ export function splitPositionalPlaceholders(text: string): Array<number | string> {
17
+ const parts: Array<number | string> = [];
18
+ let rawStart = 0;
19
+ for (const match of text.matchAll(QUOTED_OR_PLACEHOLDER)) {
20
+ if (match[3] === undefined) {
21
+ continue;
22
+ }
23
+ parts.push(text.slice(rawStart, match.index), Number(match[3]));
24
+ rawStart = match.index + match[0].length;
25
+ }
26
+ parts.push(text.slice(rawStart));
27
+ return parts;
28
+ }
29
+
30
+ /** The subset of drizzle-orm's `sql` tag this module uses; the package is an optional peer and loaded lazily. */
31
+ export interface DrizzleSqlTag {
32
+ join(chunks: unknown[], separator: unknown): unknown;
33
+ param(value: unknown): unknown;
34
+ raw(text: string): unknown;
35
+ }
36
+
37
+ /**
38
+ * A positional statement as Drizzle SQL with the values bound as parameters again. `sql.param()`, not
39
+ * `sql\`${value}\``: the template expands an array into a list of parameters, which turns a `text[]` into a row.
40
+ */
41
+ export function toDrizzleSql(sql: DrizzleSqlTag, text: string, params: readonly unknown[]): unknown {
42
+ return sql.join(
43
+ splitPositionalPlaceholders(text).map((part) =>
44
+ typeof part === 'number' ? sql.param(params[part - 1]) : sql.raw(part),
45
+ ),
46
+ sql.raw(''),
47
+ );
48
+ }
@@ -7,6 +7,7 @@ import type {
7
7
  SqlTransaction,
8
8
  } from './sql-executor.interface.js';
9
9
  import { createMysqlExecutor } from './mysql/mysql-executor.js';
10
+ import { toDrizzleSql } from './positional-placeholders.js';
10
11
  import { APPLY_SCOPE_SQL, guardPool, runInOwnTransaction, scopeParams } from './sql-session.js';
11
12
 
12
13
  /**
@@ -245,14 +246,9 @@ async function createDrizzleExecutor(options: SqlExecutorOptions): Promise<SqlEx
245
246
  const pool = await createPgPool(options);
246
247
  const db = drizzlePg.drizzle({ client: pool });
247
248
 
248
- // Positional statement → Drizzle SQL with the values bound as parameters again. Only `$<digits>` placeholders
249
- // are split, and the framework's compilers never emit one inside a literal. `sql.param()`, not `sql\`${value}\``:
250
- // the template expands an array into a list of parameters, which turns a `text[]` into a row.
251
- const toSql = (text: string, params: readonly unknown[]) =>
252
- sql.join(
253
- text.split(/\$(\d+)/).map((part, index) => (index % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))),
254
- sql.raw(''),
255
- );
249
+ // Positional statement → Drizzle SQL with the values bound as parameters again. A `$<digits>` inside a quoted
250
+ // identifier, a literal or a dollar-quoted body is text, as on the server (`positional-placeholders.ts`).
251
+ const toSql = (text: string, params: readonly unknown[]) => toDrizzleSql(sql, text, params);
256
252
 
257
253
  return {
258
254
  close: () => pool.end(),
@@ -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, writes fall through to the role gate (an upload has no owner
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 | own `checkRights()`? |
261
- | -------------------- | ------------------------------------------------------ | -------------------- |
262
- | `'public'` | open: anyone may read and write | no |
263
- | `'authenticated'` | login-restricted: every signed-in user | no |
264
- | `'owner'` | per-user: only the uploader (plus ADMIN) | no |
265
- | `'tenant'` | per-tenant: only the own validated tenant (plus ADMIN) | no |
266
- | `'custom'` (default) | anything else — you write the rule | yes |
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 — the
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
- * Write `tenantId` into the file metadata at upload time and compare it in an
502
- * overridden `CoreFileService.checkRights()`.
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