@lenne.tech/nest-server 12.6.11 → 12.6.12

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 (52) hide show
  1. package/.claude/rules/testing.md +4 -4
  2. package/FRAMEWORK-API.md +1 -1
  3. package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
  4. package/dist/core/common/helpers/byte-range.helper.js +71 -0
  5. package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
  6. package/dist/core/common/helpers/gridfs.helper.d.ts +7 -2
  7. package/dist/core/common/helpers/gridfs.helper.js +7 -4
  8. package/dist/core/common/helpers/gridfs.helper.js.map +1 -1
  9. package/dist/core/common/services/core-s3.service.d.ts +3 -0
  10. package/dist/core/common/services/core-s3.service.js +8 -1
  11. package/dist/core/common/services/core-s3.service.js.map +1 -1
  12. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  13. package/dist/core/modules/error-code/error-codes.js +8 -0
  14. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  15. package/dist/core/modules/file/core-file.controller.d.ts +5 -0
  16. package/dist/core/modules/file/core-file.controller.js +66 -4
  17. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  18. package/dist/core/modules/file/core-file.service.d.ts +2 -0
  19. package/dist/core/modules/file/core-file.service.js +17 -6
  20. package/dist/core/modules/file/core-file.service.js.map +1 -1
  21. package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
  22. package/dist/core/modules/file/filesystem-file.helper.js +2 -2
  23. package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
  24. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  25. package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
  26. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +1 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  31. package/dist/test/test.helper.d.ts +1 -0
  32. package/dist/test/test.helper.js +6 -0
  33. package/dist/test/test.helper.js.map +1 -1
  34. package/docs/REQUEST-LIFECYCLE.md +1 -1
  35. package/docs/error-codes.md +14 -0
  36. package/docs/security-overrides.md +31 -4
  37. package/migration-guides/12.6.11-to-12.6.12.md +180 -0
  38. package/package.json +6 -6
  39. package/src/core/common/helpers/byte-range.helper.ts +144 -0
  40. package/src/core/common/helpers/gridfs.helper.ts +20 -6
  41. package/src/core/common/services/core-s3.service.ts +16 -2
  42. package/src/core/modules/error-code/error-codes.ts +13 -0
  43. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +1 -0
  44. package/src/core/modules/file/README.md +74 -1
  45. package/src/core/modules/file/core-file.controller.ts +139 -3
  46. package/src/core/modules/file/core-file.service.ts +33 -13
  47. package/src/core/modules/file/filesystem-file.helper.ts +8 -3
  48. package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
  49. package/src/core/modules/file/s3-file.helper.ts +3 -2
  50. package/src/index.ts +1 -0
  51. package/src/test/README.md +8 -4
  52. package/src/test/test.helper.ts +12 -0
@@ -21,6 +21,17 @@ used to **exact-pin**, to a vulnerable version:
21
21
  | `@graphql-tools/utils` | [GHSA-7mx3-vvmw-hjmv](https://github.com/advisories/GHSA-7mx3-vvmw-hjmv) — high: prototype pollution in `mergeDeep`, which runs while the GraphQL schema is assembled. Covers `<=12.0.0`, patched `>=12.0.1` (added 2026-10-06); [GHSA-c4qx-w738-7hr3](https://github.com/advisories/GHSA-c4qx-w738-7hr3) — high: prototype pollution in `mergeIncrementalResult` via non-primitive path segments. Covers `>=10.10.1 <=12.0.1`, patched `>=12.0.2` (published 2026-10-22) | `@nestjs/graphql` declares utils as an **exact pin**: 13.4.5 — the newest 13.x — `12.0.0`, and 14.0.3, the version this framework declares since 12.0.0, `12.0.1`. 12.0.1 clears the first advisory and is covered by the second, so **this entry is load-bearing on 13.x and on 14.0.x**. 14.1.0, the version this framework declares since 12.1.0, pins `12.1.0`, which clears both: there the entry is inert. `@apollo/server` reaches utils too, through `@graphql-tools/schema` / `merge` — and in a lockfile that still holds schema 10.0.x (resolved before 2026-08-12), as **utils 11.x**: vulnerable too, with no 11.x fix, and outside the override key. Lift it with `pnpm update --depth Infinity @graphql-tools/schema @graphql-tools/merge`; the current releases request utils `^12.1.0`, which needs Node >=22.15 — the framework's own floor since 11.42.10 |
22
22
  | `multer` | [GHSA-wc9g-mqfw-jrwm](https://github.com/advisories/GHSA-wc9g-mqfw-jrwm), [GHSA-535w-7cp7-47q4](https://github.com/advisories/GHSA-535w-7cp7-47q4), [GHSA-qfvm-cv95-jqjf](https://github.com/advisories/GHSA-qfvm-cv95-jqjf) — high: DoS via crafted multipart input; [GHSA-qvfw-j98x-7q72](https://github.com/advisories/GHSA-qvfw-j98x-7q72) — low: file size limit bypass. Patched `>=2.3.0`; [GHSA-q7qp-rjg7-q26m](https://github.com/advisories/GHSA-q7qp-rjg7-q26m) — high: DoS via a pending asynchronous `fileFilter` after request teardown. Covers `>=2.0.0 <2.5.0`, patched `>=2.5.0` (published 2026-10-22) | `@nestjs/platform-express` declares multer as an **exact pin**: up to 11.2.5 `2.2.0`, 11.2.6 / 11.2.7 `2.4.0`, and so does 12.2.0, the version this framework declared in 12.0.x. 2.4.0 is covered by GHSA-q7qp-rjg7-q26m, so **this entry is load-bearing up to @nestjs/platform-express 12.2.0**. 12.3.2, the version this framework declares since 12.1.0, pins `2.5.0`: there the entry is inert. A direct `multer` dependency does not move the pin: you get both copies, and FileInterceptor uses the vulnerable one |
23
23
 
24
+ **Status since 12.6.12** (verified 2026-11-14): **`ws` needs a new entry.**
25
+ [GHSA-37g9-w4hg-h9qr](https://github.com/websockets/ws/security/advisories/GHSA-37g9-w4hg-h9qr) — high: a client
26
+ floods ping frames without reading the replies, the server buffers the automatic pongs, and the process runs out of
27
+ memory, before any authentication. Patched in `ws` 8.23.0 (and 7.5.14). `@nestjs/graphql` 14.1.2, the version this line declares, exact-pins `8.22.0`, and the GraphQL WebSocket server
28
+ runs on that copy, so the `ws` dependency nest-server declares (`8.23.0` since 12.6.12) does not lift it. Use the
29
+ `ws` entry from "The fix" — and **replace** an existing `ws` 8.x entry rather than raising only its target: pnpm
30
+ matches the key against the requested exact version, so a key whose upper bound stays below it leaves the vulnerable
31
+ copy in the tree. Until GitHub's global advisory database lists the advisory, `pnpm audit` does not report it.
32
+ `@nestjs/common`, `core` and `platform-express` 12.5.0 (declared since 12.6.12) also close GHSA-jgpx-8x6j-fcpf and
33
+ GHSA-c8fr-c7pf-58pf (high, process crashes): raise your own `@nestjs/*` pins to them.
34
+
24
35
  **Status since 12.1.0** (verified 2026-10-29): with the `@nestjs/*` versions this framework declares, **no
25
36
  entry is needed**. `@nestjs/platform-express` 12.3.2 pins `multer` 2.5.0 and `@nestjs/graphql` 14.1.0 pins
26
37
  `@graphql-tools/utils` 12.1.0, both past their advisories, and nest-server's own `overrides:` block is empty:
@@ -62,7 +73,19 @@ entries. None of them is optional in practice.
62
73
  ## The fix
63
74
 
64
75
  Add this to your project's `pnpm-workspace.yaml` (pnpm 11+; in pnpm 10 and earlier it lives under
65
- `pnpm.overrides` in `package.json`). On nest-server **12.0.x** these two entries are all it takes — a fresh
76
+ `pnpm.overrides` in `package.json`).
77
+
78
+ **On nest-server 12.6.12 and later** this entry is needed (see "Status since 12.6.12"):
79
+
80
+ ```yaml
81
+ overrides:
82
+ # GHSA-37g9-w4hg-h9qr (high): @nestjs/graphql exact-pins ws (14.1.2: 8.22.0), and the GraphQL WebSocket server
83
+ # runs on that copy. Keep key and target in LOCKSTEP with the ws version @lenne.tech/nest-server declares
84
+ # (8.23.0 since 12.6.12). Remove once @nestjs/graphql pins ws >= 8.23.0.
85
+ 'ws@>=8.0.0 <8.23.0': '8.23.0'
86
+ ```
87
+
88
+ On nest-server **12.0.x** these two entries are all it takes — a fresh
66
89
  resolve of nest-server 12.0.0's own tree with and without every other former entry audits identically. On
67
90
  **12.1.x** neither is needed once your `@nestjs/*` pins match the framework's (see "Status since 12.1.0"):
68
91
 
@@ -108,7 +131,8 @@ way, and remove the entries once your consumers move to minimatch 11 / glob 14.
108
131
  `@nestjs/graphql` 13 and `@nestjs/swagger` 11 exact-pin vulnerable versions of these two; their 12.x
109
132
  successors pin patched ones (`ws` 8.22.0, `js-yaml` 5.5.0). On nest-server 12 remove both entries — an
110
133
  inert `ws` entry is not harmless there: pnpm rewrites `graphql-ws`'s `ws` peer range to the override
111
- target, so a target below 8.22.0 makes `pnpm peers check` report `unmet peer ws`.
134
+ target, so a target below 8.22.0 makes `pnpm peers check` report `unmet peer ws`. Since 12.6.12 nest-server 12
135
+ needs its own `ws` entry again, for GHSA-37g9-w4hg-h9qr: replace the 11.x entry with the one from "The fix".
112
136
 
113
137
  ```yaml
114
138
  # nest-server 11.x only (@nestjs/graphql 13 exact-pins ws; GHSA-96hv-2xvq-fx4p, patched >=8.21.0)
@@ -133,7 +157,8 @@ tree to `2.0.11` even though nothing needed help any more.
133
157
 
134
158
  ### The `ws` target must stay in lockstep with the declared `ws` version
135
159
 
136
- This applies while a project carries a `ws` entry at all, i.e. on nest-server 11.x. `8.22.0` (since 12.0.0;
160
+ This applies while a project carries a `ws` entry at all: on nest-server 11.x, and on 12.6.12 and later. `8.23.0`
161
+ (since 12.6.12; `8.22.0` since 12.0.0,
137
162
  `8.21.3` before) is not an arbitrary "latest patch" — it is the version
138
163
  `@lenne.tech/nest-server` declares as an ordinary **dependency**, so it is already in your tree whether
139
164
  or not you list `ws` yourself. The override target has to equal it.
@@ -146,7 +171,9 @@ when you read a manifest. The target was raised `8.21.1` → `8.21.3` on 2026-08
146
171
  reason, and to `8.22.0` with nest-server 12.0.0.
147
172
 
148
173
  **Rule:** whenever the `ws` version declared by `@lenne.tech/nest-server` (or by your own
149
- `package.json`, if you list it) moves, move this override target with it in the same commit. The
174
+ `package.json`, if you list it) moves, move this override's target **and the upper bound of its key** with it in the
175
+ same commit — pnpm matches the key against the requested range, so a key that stays below an exact pin no longer
176
+ reaches it. The
150
177
  same applies to any other override whose package also appears as a declared dependency.
151
178
 
152
179
  Then:
@@ -0,0 +1,180 @@
1
+ # Migration Guide: 12.6.11 → 12.6.12
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None in nest-server. NestJS 12.5.0, which `pnpm run update` installs, adds startup errors for configurations it used to ignore (§5) |
8
+ | **New Features** | Byte ranges from every file store: `getFileStream(id, { range })`, `CoreS3Service.getObject(key, { range })`, `resolveDownloadRange()`, `setDownloadRangeHeaders()`, `parseRangeHeader()`; `TestDownloadOptions.headers` |
9
+ | **Bugfixes** | `GET /files/id/:id` and `GET /files/:filename` answered every `Range` request with `200` and the whole file — Safari does not play a video from such a server (§1) |
10
+ | **Security** | NestJS 12.5.0 closes GHSA-c8fr-c7pf-58pf and GHSA-jgpx-8x6j-fcpf (high, process crashes; §5). `ws` GHSA-37g9-w4hg-h9qr (high, unauthenticated memory-exhaustion DoS through the GraphQL WebSocket) — one override in your `pnpm-workspace.yaml` (§6) |
11
+ | **Also fixed** | Every S3 download the client aborted logged `ERROR File download failed: aborted` (§4) |
12
+ | **Migration Effort** | Projects with their OWN route for video, audio or large downloads: answer `Range` (§2). Everyone: `pnpm run update` and the `ws` override (§6) |
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@12.6.12
18
+ pnpm run update # nest-server-starter based projects
19
+ # replace the ws 8.x override in pnpm-workspace.yaml with the one from §6, then: pnpm install
20
+ grep -rn "pipeFileToResponse(" src/ # own download routes: serve ranges where media is delivered (§2)
21
+ pnpm run build
22
+ pnpm test
23
+ ```
24
+
25
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
26
+
27
+ ## 1. The framework's download routes answer ranges
28
+
29
+ Safari refuses to play a video, and stalls audio, from a server that answers a `Range` request with `200` and the
30
+ whole file. Chrome plays it anyway, so the problem showed neither locally nor in a Chromium-based Playwright run — it
31
+ showed on the first iPhone. Until 12.6.11 the core could not read a byte range at all: `CoreS3Service.getObject()` sent
32
+ no `Range`, and `getFileStream()` always opened the whole file. A project could serve ranges from GridFS and the
33
+ filesystem with its own code, but not from S3, which every deployed stage with `s3` configured uses.
34
+
35
+ Since 12.6.12 both download routes answer ranges on every store, without any change in the project:
36
+
37
+ | Request | Answer |
38
+ |---|---|
39
+ | `Range: bytes=0-1` (one range inside the file) | `206`, `Content-Range: bytes 0-1/<length>`, `Content-Length: 2`, only those bytes |
40
+ | `Range: bytes=1000-` / `bytes=-500` | `206` with the rest of the file / its last 500 bytes |
41
+ | A range starting at or past the end of the file | `416`, `Content-Range: bytes */<length>`, `#LTNS_0503` |
42
+ | Several ranges, an invalid header, `If-Range` | `200` with the whole file, as before |
43
+ | No `Range` | `200` as before, now with `Accept-Ranges: bytes` |
44
+
45
+ The rights check runs first, as before: a refused or unknown file is `404` whatever the `Range` says. A `206` carries
46
+ `no-transform` in `Cache-Control` (`private, no-store, no-transform` by default), which keeps a `compression`
47
+ middleware from gzipping the partial body.
48
+
49
+ ## 2. Own download routes
50
+
51
+ A route of your own that delivers media (or large files a client may resume) answers ranges with three calls:
52
+
53
+ ```typescript
54
+ import {
55
+ downloadAbortSignal,
56
+ openDownloadStream,
57
+ pipeFileToResponse,
58
+ resolveDownloadRange,
59
+ RESPONSE_GONE,
60
+ setDownloadRangeHeaders,
61
+ } from '@lenne.tech/nest-server';
62
+
63
+ @Get('video/:id')
64
+ async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
65
+ const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
66
+ const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
67
+ if (!resolved) {
68
+ throw new NotFoundException();
69
+ }
70
+ const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
71
+ const stream = await openDownloadStream(res, () =>
72
+ this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
73
+ );
74
+ if (stream === RESPONSE_GONE) {
75
+ return res;
76
+ }
77
+ if (!stream) {
78
+ throw new NotFoundException();
79
+ }
80
+ res.header('Content-Type', resolved.info.contentType || 'video/mp4');
81
+ res.header('Cache-Control', 'private, no-store');
82
+ setDownloadRangeHeaders(res, range, resolved.info.length); // 206 + Content-Range, or Accept-Ranges only
83
+ return pipeFileToResponse(stream, res);
84
+ }
85
+ ```
86
+
87
+ - `resolveDownloadRange()` must run AFTER the rights check: a `416` confirms that the file exists.
88
+ - `setDownloadRangeHeaders()` goes after your own headers — it replaces `Content-Length` with the length of the range
89
+ and appends `no-transform` to `Cache-Control`.
90
+ - The range reaches every store: S3 with a ranged `GetObject`, GridFS from the chunk holding the first byte, the
91
+ filesystem from that offset — with the same idle guard and abort signal as a whole file, so an aborted range
92
+ releases its S3 socket at once.
93
+
94
+ **A project that reads ranges itself** (GridFS `openDownloadStream(id, { start, end })`, `createReadStream({ start,
95
+ end })`, a hand-written Range parser) can switch to these functions and drop its own code — and gets S3, which such
96
+ code could not reach. Mind the end: `range.end` is INCLUSIVE, like HTTP and `createReadStream()`; GridFS counts it
97
+ exclusive, which `getFileStream()` translates.
98
+
99
+ Lower-level pieces, for code that does not go through `CoreFileService`:
100
+
101
+ - `CoreS3Service.getObject(key, { range: { start, end } })` — the result carries `contentRange` (S3's
102
+ `bytes <start>-<end>/<total>`) and the range's `contentLength`.
103
+ - `parseRangeHeader(header, length)` — the pure parser (`{ start, end }`, `'unsatisfiable'` or `undefined`), for a
104
+ route that decides `If-Range` with a strong validator of its own.
105
+ - A malformed range (`start > end`, negative, not an integer) throws a `RangeError` before any store is asked.
106
+
107
+ ## 3. Tests
108
+
109
+ `testHelper.download()` / `downloadBuffer()` take request headers:
110
+
111
+ ```typescript
112
+ const res = await testHelper.download(`/files/id/${id}`, { headers: { Range: 'bytes=0-1' }, token });
113
+ expect(res.statusCode).toBe(206);
114
+ expect(res.headers['content-range']).toBe(`bytes 0-1/${length}`);
115
+ ```
116
+
117
+ ## 4. No ERROR for downloads the client aborts
118
+
119
+ A client that leaves while an S3 download is still streaming is normal traffic — a video player aborts the running
120
+ range on every seek. Each of them logged `ERROR [CoreFileController] File download failed: aborted` with a stack trace,
121
+ through the framework's download routes and every project route that delivers with `pipeFileToResponse()`.
122
+ `downloadAbortSignal(res)` registers its listeners first, aborts the S3 request when the client goes, and the SDK fails
123
+ the body inside that same dispatch — before `pipeFileToResponse()` saw the client leave.
124
+
125
+ Since 12.6.12 `pipeFileToResponse()` reads a stream error while the client is gone as the end of an aborted download:
126
+ nothing is sent, one debug line is logged. A store error while the client is still connected is an ERROR as before.
127
+ Nothing to change in a project.
128
+
129
+ ## 5. Security: NestJS 12.5.0
130
+
131
+ 12.6.12 declares NestJS 12.5.0 (`@nestjs/common`, `@nestjs/core`, `@nestjs/platform-express`, `@nestjs/testing` (dev); from 12.3.2) — two NestJS minors. 12.4.0 is fixes only. 12.5.0 adds startup errors for configurations it used to ignore: a guard, interceptor or pipe that cannot run (an abstract class as token, a class given as the `useValue` of `APP_GUARD`) and an invalid `forRoutes()` / `exclude()` entry stop the application at startup — they never took effect, so correct or remove them. It also mounts `forRoutes()` middleware on routes excluded from the global prefix, caps multipart requests at 1000 parts (`limits.parts` raises it), answers a status-less `SyntaxError` / `URIError` from an `app.use()` middleware with 500 instead of 400, fails the consumer of an `@Optional()` dependency that exists but cannot be built, and gives a limit set to `NaN` its default ([release notes](https://github.com/nestjs/nest/releases/tag/v12.5.0)). Boot the application once after the update. `pnpm run update` raises your pins to it.
132
+ NestJS's advisories of 2026-11-12 include two high ones for an application on Express that this release closes:
133
+
134
+ | Advisory | Package | What |
135
+ |---|---|---|
136
+ | [GHSA-c8fr-c7pf-58pf](https://github.com/nestjs/nest/security/advisories/GHSA-c8fr-c7pf-58pf) | `@nestjs/platform-express` | Process crash via a multipart request with many fields |
137
+ | [GHSA-jgpx-8x6j-fcpf](https://github.com/nestjs/nest/security/advisories/GHSA-jgpx-8x6j-fcpf) | `@nestjs/common` | Process crash via many files validated at once by `ParseFilePipe` |
138
+
139
+ They were not in GitHub's global advisory database on 2026-11-14, so `pnpm audit` does not report them yet. A project
140
+ that pins `@nestjs/*` itself below 12.5.0 stays affected whatever nest-server version it runs.
141
+
142
+ ## 6. Security: one override for `ws`
143
+
144
+ [GHSA-37g9-w4hg-h9qr](https://github.com/websockets/ws/security/advisories/GHSA-37g9-w4hg-h9qr) (high): a client floods
145
+ ping frames without reading the replies, the server buffers the automatic pongs, and the process runs out of memory —
146
+ before any authentication, through the WebSocket every application with GraphQL subscriptions accepts. Patched in `ws`
147
+ 8.23.0 (and 7.5.14). The GraphQL WebSocket server runs on `@nestjs/graphql`'s own `ws`, which 14.1.2 exact-pins at
148
+ 8.22.0. nest-server's own `overrides:` do not reach your install (`docs/security-overrides.md`), so put the entry into
149
+ your project's `pnpm-workspace.yaml` and run `pnpm install`. A nest-server-starter based project already has a `ws` 8.x
150
+ entry: **replace** it, do not only raise its target — pnpm matches the key against the requested exact version, and a
151
+ key whose upper bound stays below it leaves the vulnerable copy in the tree.
152
+
153
+ ```yaml
154
+ overrides:
155
+ # GHSA-37g9-w4hg-h9qr (high): @nestjs/graphql 14.1.2 exact-pins ws 8.22.0. Keep key and target in lockstep
156
+ # with the ws version @lenne.tech/nest-server declares (8.23.0 since 12.6.12). Remove once @nestjs/graphql pins ws >= 8.23.0.
157
+ 'ws@>=8.0.0 <8.23.0': '8.23.0'
158
+ ```
159
+
160
+ `pnpm why ws` must then show a single `ws@8.23.0`. Until GitHub's global advisory database lists the
161
+ advisory, `pnpm audit` does not report the vulnerable version. A vendor-mode project adds the same entry.
162
+
163
+ ## Troubleshooting
164
+
165
+ | Symptom | Cause | Fix |
166
+ |---|---|---|
167
+ | `ERROR [CoreFileController] File download failed: aborted` with `socketCloseListener` in the stack, one per aborted download | 12.6.10 – 12.6.11 on S3 | Update to 12.6.12 (§4) |
168
+ | `pnpm why ws` lists `ws@8.22.0` under `@nestjs/graphql` | The override from §6 is missing, or an older `ws` 8.x key was kept with only its target raised | Use exactly `'ws@>=8.0.0 <8.23.0': '8.23.0'`, `pnpm install` |
169
+ | A video plays in Chrome but not in Safari (iPhone, macOS) | The route answers `Range` with `200` and the whole file | Framework routes: update. Own route: §2 |
170
+ | `416` with `#LTNS_0503` | The client asked for bytes past the end of the file; `Content-Range: bytes */<length>` names the real size | Usually a player with a cached, outdated length — reload |
171
+ | `RangeError: Invalid byte range` | A `range` with `start > end`, a negative or fractional value reached `getFileStream()` / `getObject()` | Produce it with `resolveDownloadRange()` |
172
+ | `InvalidRange` from S3, or a GridFS stream error `Stream end (…) must not be more than the length of the file` | A `range` past the end of the file reached the store | Resolve it against the file's `length` with `resolveDownloadRange()`, which cuts it at the last byte |
173
+
174
+ ## Module Documentation
175
+
176
+ - `docs/security-overrides.md` — the `ws` entry and its lockstep rule
177
+
178
+ - `src/core/modules/file/README.md` — "Byte ranges: video, audio, resumed downloads (12.6.12)"
179
+ - `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
180
+ - `docs/error-codes.md` — `LTNS_0503`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.6.11",
3
+ "version": "12.6.12",
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": [
@@ -106,12 +106,12 @@
106
106
  "@getbrevo/brevo": "6.2.0",
107
107
  "@modelcontextprotocol/sdk": "1.32.2",
108
108
  "@nestjs/apollo": "14.1.2",
109
- "@nestjs/common": "12.3.2",
110
- "@nestjs/core": "12.3.2",
109
+ "@nestjs/common": "12.5.0",
110
+ "@nestjs/core": "12.5.0",
111
111
  "@nestjs/graphql": "14.1.2",
112
112
  "@nestjs/jwt": "12.0.3",
113
113
  "@nestjs/passport": "12.0.0",
114
- "@nestjs/platform-express": "12.3.2",
114
+ "@nestjs/platform-express": "12.5.0",
115
115
  "@nestjs/schedule": "12.0.2",
116
116
  "@nestjs/swagger": "12.1.0",
117
117
  "@nestjs/terminus": "12.1.0",
@@ -147,7 +147,7 @@
147
147
  "supertest": "7.3.1",
148
148
  "ts-morph": "28.0.0",
149
149
  "undici": "7.30.2",
150
- "ws": "8.22.0",
150
+ "ws": "8.23.0",
151
151
  "yuml-diagram": "1.2.0"
152
152
  },
153
153
  "peerDependencies": {
@@ -236,7 +236,7 @@
236
236
  "@nestjs/cli": "12.0.11",
237
237
  "@nestjs/mongoose": "12.0.0",
238
238
  "@nestjs/schematics": "12.0.12",
239
- "@nestjs/testing": "12.3.2",
239
+ "@nestjs/testing": "12.5.0",
240
240
  "@swc/cli": "0.8.2",
241
241
  "@swc/core": "1.16.21",
242
242
  "@tus/s3-store": "2.1.0",
@@ -0,0 +1,144 @@
1
+ /**
2
+ * A byte range of a file: the bytes `start` through `end`, both INCLUSIVE — the way HTTP counts them
3
+ * (`Range: bytes=0-1` is two bytes) and `fs.createReadStream()` takes them.
4
+ *
5
+ * Read with `CoreFileService.getFileStream(id, { range })` / `getFileStreamByName()` or
6
+ * `CoreS3Service.getObject(key, { range })`. The range must lie inside the file (`end` below its
7
+ * length); {@link parseRangeHeader} / `resolveDownloadRange()` produce such a range from a request.
8
+ */
9
+ export interface ByteRange {
10
+ /** Last byte, inclusive */
11
+ end: number;
12
+ /** First byte, counted from 0 */
13
+ start: number;
14
+ }
15
+
16
+ /**
17
+ * What {@link parseRangeHeader} decided about a `Range` header:
18
+ * - a {@link ByteRange} — deliver these bytes (`206 Partial Content`);
19
+ * - `'unsatisfiable'` — the range starts at or past the end of the file (`416 Range Not Satisfiable`);
20
+ * - `undefined` — deliver the whole file (`200`), the header asks for nothing this server serves.
21
+ */
22
+ export type RangeHeaderDecision = 'unsatisfiable' | ByteRange | undefined;
23
+
24
+ /**
25
+ * Longest `Range` header that is parsed at all. A single byte range of a file the size of any store's limit is
26
+ * well below 100 characters; a longer header is a list of ranges or garbage, and both are answered with the whole
27
+ * file anyway.
28
+ */
29
+ const MAX_RANGE_HEADER_LENGTH = 200;
30
+
31
+ /** One range of the set, `first-last`, `first-` or `-suffix`. Anchored and without nested quantifiers. */
32
+ const RANGE_SPEC = /^(\d*)[ \t]*-[ \t]*(\d*)$/;
33
+
34
+ /** The unit and the range set: `bytes=<set>`, the unit case-insensitive (RFC 9110 §14.1) */
35
+ const RANGE_UNIT = /^[ \t]*bytes[ \t]*=(.*)$/i;
36
+
37
+ /**
38
+ * Decide what a `Range` request header asks for, against a file of `length` bytes (RFC 9110 §14.1.2, §14.2).
39
+ *
40
+ * Only ONE range is served. The whole file (`undefined`) is the answer to:
41
+ * - no header, an empty one, or a unit other than `bytes`;
42
+ * - an invalid header (`bytes=5-2`, `bytes=abc`, `bytes=-`) — RFC 9110 lets a server ignore it, and the whole file
43
+ * is what a client that sent garbage can still use;
44
+ * - SEVERAL ranges (`bytes=0-1,5-9`): a `multipart/byteranges` answer is not served, the way Express's `send` does
45
+ * it. Media players and download managers ask for one range at a time;
46
+ * - a file whose length is unknown (`undefined`, negative, not an integer): a `206` must name the total length.
47
+ *
48
+ * `'unsatisfiable'` is the answer to a single range that starts at or past the end of the file, or a suffix range
49
+ * of length 0 — and to every range of an EMPTY file, which has no byte to start at.
50
+ *
51
+ * A range that ends past the file is cut at its last byte, and a suffix longer than the file is the whole file —
52
+ * both are satisfiable by definition, so a client may ask for `bytes=0-` or `bytes=0-999999999` without knowing
53
+ * the size.
54
+ *
55
+ * Pure function, no I/O — the HTTP glue (`resolveDownloadRange()`, `setDownloadRangeHeaders()`) lives next to
56
+ * `pipeFileToResponse()` in the file module.
57
+ */
58
+ export function parseRangeHeader(
59
+ header: string | string[] | undefined,
60
+ length: number | undefined,
61
+ ): RangeHeaderDecision {
62
+ if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {
63
+ return undefined;
64
+ }
65
+ // Node joins repeated headers with ', ' — a repeated Range header is a list of ranges, answered with the whole file
66
+ const value = Array.isArray(header) ? header.join(',') : header;
67
+ if (typeof value !== 'string' || !value || value.length > MAX_RANGE_HEADER_LENGTH) {
68
+ return undefined;
69
+ }
70
+ const unit = RANGE_UNIT.exec(value);
71
+ if (!unit) {
72
+ return undefined;
73
+ }
74
+ // Empty list elements are allowed and ignored (RFC 9110 §5.6.1)
75
+ const specs = unit[1]
76
+ .split(',')
77
+ .map((spec) => spec.trim())
78
+ .filter(Boolean);
79
+ if (specs.length !== 1) {
80
+ return undefined;
81
+ }
82
+ const match = RANGE_SPEC.exec(specs[0]);
83
+ if (!match) {
84
+ return undefined;
85
+ }
86
+ const [, first, last] = match;
87
+ if (!first && !last) {
88
+ return undefined;
89
+ }
90
+ if (!first) {
91
+ // Suffix range: the last N bytes
92
+ const suffix = toSafeInteger(last);
93
+ if (suffix === undefined) {
94
+ return undefined;
95
+ }
96
+ if (suffix === 0 || length === 0) {
97
+ return 'unsatisfiable';
98
+ }
99
+ return { end: length - 1, start: Math.max(0, length - suffix) };
100
+ }
101
+ const start = toSafeInteger(first);
102
+ const end = last ? toSafeInteger(last) : length - 1;
103
+ if (start === undefined || end === undefined) {
104
+ return undefined;
105
+ }
106
+ if (last && end < start) {
107
+ // `bytes=5-2` is invalid, not unsatisfiable — ignored
108
+ return undefined;
109
+ }
110
+ if (start >= length) {
111
+ return 'unsatisfiable';
112
+ }
113
+ return { end: Math.min(end, length - 1), start };
114
+ }
115
+
116
+ /**
117
+ * Check a range handed to a store read: two safe integers, `0 <= start <= end`. Returns it unchanged, `undefined`
118
+ * for no range, and throws a `RangeError` for anything else — the same answer from every store, before any of them
119
+ * is asked (each would otherwise fail in its own way: S3 with `InvalidRange`, GridFS with a driver error on the
120
+ * stream, the filesystem with a silently empty stream).
121
+ */
122
+ export function assertByteRange(range: unknown): ByteRange | undefined {
123
+ if (range === undefined || range === null) {
124
+ return undefined;
125
+ }
126
+ const { end, start } = range as { end: number; start: number };
127
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
128
+ throw new RangeError(
129
+ `Invalid byte range { start: ${String(start)}, end: ${String(end)} }: start and end must be integers with 0 <= start <= end (end inclusive)`,
130
+ );
131
+ }
132
+ return { end, start };
133
+ }
134
+
135
+ /** The `Content-Range` value of a range of a file with `length` bytes: `bytes 0-1/1234` */
136
+ export function contentRangeValue(range: ByteRange, length: number): string {
137
+ return `bytes ${range.start}-${range.end}/${length}`;
138
+ }
139
+
140
+ /** Digits as a safe integer, `undefined` when they exceed what a Number holds exactly */
141
+ function toSafeInteger(digits: string): number | undefined {
142
+ const value = Number(digits);
143
+ return Number.isSafeInteger(value) ? value : undefined;
144
+ }
@@ -1,6 +1,7 @@
1
1
  import type { mongo, Types } from 'mongoose';
2
2
  import { Readable } from 'stream';
3
3
  import { newObjectId } from '../persistence/mongo/mongoose-compat.js';
4
+ import type { ByteRange } from './byte-range.helper.js';
4
5
 
5
6
  // Use Mongoose's MongoDB types to avoid BSON version conflicts
6
7
 
@@ -298,18 +299,31 @@ export class GridFSHelper {
298
299
  }
299
300
 
300
301
  /**
301
- * Open download stream by ID
302
+ * Open download stream by ID — with `range`, only those bytes (both inclusive). The range must lie inside the
303
+ * file: GridFS refuses a start or end past its length with an error on the stream.
302
304
  */
303
- static openDownloadStream(bucket: GridFSBucket, id: string | Types.ObjectId): GridFSBucketReadStream {
305
+ static openDownloadStream(
306
+ bucket: GridFSBucket,
307
+ id: string | Types.ObjectId,
308
+ range?: ByteRange,
309
+ ): GridFSBucketReadStream {
304
310
  const objectId = typeof id === 'string' ? newObjectId(id) : id;
305
- return bucket.openDownloadStream(objectId);
311
+ return bucket.openDownloadStream(objectId, GridFSHelper.streamRange(range));
312
+ }
313
+
314
+ /**
315
+ * Open download stream by name — with `range`, only those bytes (both inclusive)
316
+ */
317
+ static openDownloadStreamByName(bucket: GridFSBucket, filename: string, range?: ByteRange): GridFSBucketReadStream {
318
+ return bucket.openDownloadStreamByName(filename, GridFSHelper.streamRange(range));
306
319
  }
307
320
 
308
321
  /**
309
- * Open download stream by name
322
+ * The GridFS stream options of a range. GridFS counts `end` EXCLUSIVE (the byte after the last one), HTTP and
323
+ * `ByteRange` count it inclusive — hence the `+ 1`.
310
324
  */
311
- static openDownloadStreamByName(bucket: GridFSBucket, filename: string): GridFSBucketReadStream {
312
- return bucket.openDownloadStreamByName(filename);
325
+ static streamRange(range?: ByteRange): undefined | { end: number; start: number } {
326
+ return range ? { end: range.end + 1, start: range.start } : undefined;
313
327
  }
314
328
 
315
329
  /**
@@ -4,6 +4,7 @@ import { Agent as HttpsAgent } from 'https';
4
4
  import { PassThrough } from 'stream';
5
5
 
6
6
  import { buildContentDisposition } from '../helpers/content-disposition.helper.js';
7
+ import { assertByteRange, type ByteRange } from '../helpers/byte-range.helper.js';
7
8
  import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper.js';
8
9
  import { ConfigService } from './config.service.js';
9
10
 
@@ -701,6 +702,11 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
701
702
  /**
702
703
  * Get an object stream (plus metadata) from the main bucket.
703
704
  * Throws the SDK's NoSuchKey error when the object does not exist.
705
+ *
706
+ * With `range`, only those bytes are read (`Range: bytes=<start>-<end>`, end inclusive): `contentLength` is then
707
+ * the length of the range and `contentRange` S3's `bytes <start>-<end>/<total>`. The range must lie inside the
708
+ * object — a range starting past its end is refused by S3 with `InvalidRange`; `resolveDownloadRange()` produces a
709
+ * valid one from a request's `Range` header. A malformed range throws a `RangeError` before S3 is asked.
704
710
  */
705
711
  async getObject(
706
712
  key: string,
@@ -712,14 +718,21 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
712
718
  * its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
713
719
  */
714
720
  idleTimeoutMs?: false | number;
721
+ /** Read only these bytes (both inclusive). Since 12.6.12. */
722
+ range?: ByteRange;
715
723
  },
716
- ): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
724
+ ): Promise<{ body: Readable; contentLength?: number; contentRange?: string; contentType?: string }> {
717
725
  const { client, config, sdk } = this.requireInit();
726
+ const range = assertByteRange(options?.range);
718
727
  // `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
719
728
  // otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
720
729
  const idleMs = options?.idleTimeoutMs;
721
730
  const result = await client.send(
722
- new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }),
731
+ new sdk.GetObjectCommand({
732
+ Bucket: config.bucket,
733
+ Key: key,
734
+ ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
735
+ }),
723
736
  options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
724
737
  );
725
738
  return {
@@ -734,6 +747,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
734
747
  },
735
748
  }),
736
749
  contentLength: result.ContentLength,
750
+ ...(result.ContentRange ? { contentRange: result.ContentRange } : {}),
737
751
  contentType: result.ContentType,
738
752
  };
739
753
  }
@@ -565,6 +565,19 @@ export const LtnsErrors = {
565
565
  },
566
566
  },
567
567
 
568
+ /**
569
+ * A download asked for a byte range that starts at or past the end of the file (`Range` header, HTTP 416). The
570
+ * response carries `Content-Range: bytes * /<length>` (without the space), so the client learns the real size.
571
+ */
572
+ FILE_RANGE_NOT_SATISFIABLE: {
573
+ code: 'LTNS_0503',
574
+ message: 'Requested range not satisfiable',
575
+ translations: {
576
+ de: 'Der angeforderte Bereich liegt außerhalb der Datei.',
577
+ en: 'The requested range lies outside the file.',
578
+ },
579
+ },
580
+
568
581
  // =====================================================
569
582
  // Internal Errors (LTNS_0900-LTNS_0999)
570
583
  // =====================================================
@@ -240,5 +240,6 @@ personal or medical, a per-file rule is not optional.
240
240
  | `super(connection)` in `FileService` with `file.storage: 's3'` | Boot fails: "that storage is not available" | Forward `{ configService, s3Service }` — step 6 |
241
241
  | Own download route with `stream.pipe(res)` | After enough aborted downloads every S3 request hangs; health check stays green | `pipeFileToResponse(stream, res)` — it destroys the source when the response closes (README, "Delivering a file from your own route") |
242
242
  | Own download route passing `downloadAbortSignal(res)` to `getFileStream()` without `openDownloadStream()` | Every client that leaves before S3 answers logs `ERROR [ExceptionsHandler] … AbortError` with a stack trace; a busy store answers 500 instead of 503 | Open the stream with `openDownloadStream(res, () => getFileStream(…))` and end the route with `return res` on `RESPONSE_GONE` (12.6.11+) |
243
+ | Own video/audio route that ignores `Range` | Plays in Chrome, not in Safari (no `206` for `Range`); seeking reloads the whole file | `resolveDownloadRange()` + `getFileStream(id, { range })` + `setDownloadRangeHeaders()` (12.6.12+, README "Byte ranges") |
243
244
  | S3 packages in `devDependencies` | Production image cannot load S3 | Move them to `dependencies` — step 6 |
244
245
  | A quota aggregating only `fs.files` | Reads 0 on the S3 / filesystem driver | Aggregate `fs.files`, `filesystem-files` and `s3-files` — step 6 |