@lenne.tech/nest-server 11.46.3 → 11.46.5
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/configurable-features.md +1 -1
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
- package/dist/core/common/helpers/byte-range.helper.js +76 -0
- package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
- package/dist/core/common/helpers/gridfs.helper.d.ts +7 -2
- package/dist/core/common/helpers/gridfs.helper.js +7 -4
- package/dist/core/common/helpers/gridfs.helper.js.map +1 -1
- package/dist/core/common/services/core-s3.service.d.ts +3 -0
- package/dist/core/common/services/core-s3.service.js +8 -1
- package/dist/core/common/services/core-s3.service.js.map +1 -1
- package/dist/core/modules/ai/core-ai.controller.js +8 -4
- package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +9 -0
- package/dist/core/modules/error-code/error-codes.js +8 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/file/core-file.controller.d.ts +6 -0
- package/dist/core/modules/file/core-file.controller.js +94 -26
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/core/modules/file/core-file.service.d.ts +2 -0
- package/dist/core/modules/file/core-file.service.js +17 -6
- package/dist/core/modules/file/core-file.service.js.map +1 -1
- package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
- package/dist/core/modules/file/filesystem-file.helper.js +2 -2
- package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
- package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
- package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
- package/dist/core/modules/file/s3-file.helper.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/dist/server/modules/error-code/error-codes.d.ts +1 -0
- package/dist/test/test.helper.d.ts +1 -0
- package/dist/test/test.helper.js +6 -0
- package/dist/test/test.helper.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -1
- package/docs/error-codes.md +14 -0
- package/docs/security-overrides.md +21 -6
- package/migration-guides/11.46.2-to-11.46.3.md +15 -3
- package/migration-guides/11.46.3-to-11.46.4.md +75 -0
- package/migration-guides/11.46.4-to-11.46.5.md +183 -0
- package/package.json +6 -6
- package/src/core/common/helpers/byte-range.helper.ts +144 -0
- package/src/core/common/helpers/gridfs.helper.ts +20 -6
- package/src/core/common/services/core-s3.service.ts +16 -2
- package/src/core/modules/ai/core-ai.controller.ts +12 -4
- package/src/core/modules/error-code/error-codes.ts +13 -0
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +17 -15
- package/src/core/modules/file/README.md +91 -3
- package/src/core/modules/file/core-file.controller.ts +202 -32
- package/src/core/modules/file/core-file.service.ts +33 -13
- package/src/core/modules/file/filesystem-file.helper.ts +8 -3
- package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
- package/src/core/modules/file/s3-file.helper.ts +3 -2
- package/src/index.ts +1 -0
- package/src/test/README.md +8 -4
- package/src/test/test.helper.ts +12 -0
|
@@ -168,7 +168,7 @@ JWT-based authentication for existing projects:
|
|
|
168
168
|
| Feature | Description |
|
|
169
169
|
|---------|-------------|
|
|
170
170
|
| **File Module** | Upload/download with MongoDB GridFS storage |
|
|
171
|
-
| **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific). Since 11.46.3 the download routes answer after the rights check: weak `ETag` + `If-None-Match` → `304` without a store read, `Cache-Control` per `file.downloadCaching`, `Content-Length`; the store request carries an abort signal (`downloadAbortSignal()`), delivery goes through `pipeFileToResponse()` (releases the source when the client goes), every stream is idle-guarded (`file.downloadIdleTimeoutMs`), and a store that gives no connection in time answers `503` + `Retry-After` |
|
|
171
|
+
| **REST Endpoints** | `GET /files/id/:id`, `GET /files/:filename` (core, gated by `file.downloadRoles`, default ADMIN); `POST /files/upload`, `DELETE /files/:id` (project-specific). Since 11.46.3 the download routes answer after the rights check: weak `ETag` + `If-None-Match` → `304` without a store read, `Cache-Control` per `file.downloadCaching`, `Content-Length`; the store request carries an abort signal (`downloadAbortSignal()`) and is opened through `openDownloadStream()` (exported since 11.46.4: a gone client is `RESPONSE_GONE`, never an error), delivery goes through `pipeFileToResponse()` (releases the source when the client goes), every stream is idle-guarded (`file.downloadIdleTimeoutMs`), and a store that gives no connection in time answers `503` + `Retry-After`. Since 11.46.5 a `Range` request is answered from every store with `206` + `Content-Range` (one range; `416` + `Content-Range: bytes */<length>` past the end; several ranges or `If-Range` get the whole file), through `resolveDownloadRange()` → `getFileStream(id, { range })` → `setDownloadRangeHeaders()`, which a project's own route uses the same way |
|
|
172
172
|
| **GraphQL Endpoints** | `getFileInfo` (`file.downloadRoles`), `uploadFile` / `uploadFiles` (`file.uploadRoles`), `deleteFile` (`file.deleteRoles`) — all default ADMIN |
|
|
173
173
|
| **File access control** | Roles are the coarse filter; per-file rules go in `CoreFileService.checkRights()` using metadata written at upload time. Cover BOTH the `id` and the `filename` branch — the filename route authorizes on the by-name lookup alone when presigned S3 downloads are on, and `deleteFileByName()` always does. Working reference: `src/server/modules/file/file.service.ts` (with `file.downloadRoles: [S_USER]` in `src/config.env.ts`, so the rule is actually reached). Both file classes carry `@SkipTenantCheck()` — GridFS is not tenant-scoped |
|
|
174
174
|
| **TUS Module** | Resumable uploads via tus.io protocol (creation, termination, expiration), gated by `tus.roles` (default `S_USER`); `OPTIONS` stays public for the CORS preflight. Records owner and, with `multiTenancy` only, the validated tenant at upload creation; a custom service plugs in via `TusModule.forRoot({ service })`. Configured by `TusModule.forRoot({ config })`, else the server config's `tus` key (11.42.9+). Switched-off `creation` / `termination` answer 501 (enforced by `CoreTusService`, not `@tus/server`); upload URLs follow the path the upload was created at. The response that completes an upload carries the stored file's ID as `X-File-Id` (11.42.13+, listed in `Access-Control-Expose-Headers`) — the last segment of the TUS URL is the upload id, not the file id |
|
package/docs/error-codes.md
CHANGED
|
@@ -446,6 +446,20 @@ All error codes follow the format: `#PREFIX_XXXX: Description`
|
|
|
446
446
|
|
|
447
447
|
---
|
|
448
448
|
|
|
449
|
+
### LTNS_0503: fileRangeNotSatisfiable
|
|
450
|
+
|
|
451
|
+
**Message:** Requested range not satisfiable
|
|
452
|
+
|
|
453
|
+
**Description:** Answered with HTTP 416 by the file download routes (and by `resolveDownloadRange()` in a project's own route) when the `Range` header asks for bytes that start at or past the end of the file, or for a suffix of length 0. The response carries `Content-Range: bytes */<length>` with the real size, so the client can ask again. Since 11.46.5.
|
|
454
|
+
|
|
455
|
+
**Solution:** Request a range inside the file (`bytes=0-` is always satisfiable for a non-empty file). An empty file has no satisfiable range — request it without `Range`.
|
|
456
|
+
|
|
457
|
+
**Translations:**
|
|
458
|
+
- DE: Der angeforderte Bereich liegt außerhalb der Datei.
|
|
459
|
+
- EN: The requested range lies outside the file.
|
|
460
|
+
|
|
461
|
+
---
|
|
462
|
+
|
|
449
463
|
## Internal Errors (LTNS_0900-LTNS_0999)
|
|
450
464
|
|
|
451
465
|
### LTNS_0900: internalError
|
|
@@ -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) | `@nestjs/graphql` 13.4.5 — the version this framework declares, and the newest 13.x — declares `"@graphql-tools/utils": "12.0.0"`, an **exact pin**. Only `@nestjs/graphql` 14.x moves it, so **this entry is load-bearing**. `@apollo/server` reaches it 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.0.3`, which needs Node >=22.15 — the framework's own floor since 11.42.10, which is why the snippet below targets 12.0.3 |
|
|
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.4.0, patched `>=2.5.0` (published 2026-10-23) | `@nestjs/platform-express` up to 11.2.5 declares `"multer": "2.2.0"` — an **exact pin**. A direct `multer` dependency does not move it: you get both copies, and FileInterceptor uses the vulnerable one. 11.2.6 to 11.2.8, the newest 11.x, pin `2.4.0`, which GHSA-q7qp-rjg7-q26m covers. No 11.x update reaches the fix, so **this entry is load-bearing again since 11.43.4** |
|
|
23
23
|
|
|
24
|
+
**Status since 11.46.5** (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` 13.4.5 (newest 13.x) exact-pins `8.21.3`, and the GraphQL WebSocket server
|
|
28
|
+
runs on that copy, so the `ws` dependency nest-server declares (`8.23.0` since 11.46.5) 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` and `@nestjs/platform-express` 11.2.10 (declared since 11.46.5) 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 11.42.4:** `@graphql-tools/utils` joins `js-yaml` as load-bearing — no `@nestjs/graphql`
|
|
25
36
|
13.x resolves past the exact pin. The 11.42.4 release also covers `proxy-addr` (GHSA-jqcg-44mw-7w3h,
|
|
26
37
|
critical: IP spoofing through an IPv4-mapped IPv6 address in a trusted subnet — it is what
|
|
@@ -46,11 +57,13 @@ Add this to your project's `pnpm-workspace.yaml` (pnpm 11+; in pnpm 10 and earli
|
|
|
46
57
|
|
|
47
58
|
```yaml
|
|
48
59
|
overrides:
|
|
49
|
-
# @nestjs/graphql exact-pins ws
|
|
60
|
+
# @nestjs/graphql 13 exact-pins ws (13.4.5: 8.21.3) — GHSA-37g9-w4hg-h9qr (high, patched 8.23.0 / 7.5.14).
|
|
50
61
|
# An exact pin cannot resolve forward — the override is the only fix.
|
|
51
|
-
# Keep the target in LOCKSTEP with
|
|
52
|
-
# Remove once @nestjs/graphql stops pinning it.
|
|
53
|
-
'ws@>=8.0.0 <8.
|
|
62
|
+
# Keep the target in LOCKSTEP with the ws version @lenne.tech/nest-server declares (8.23.0 since 11.46.5);
|
|
63
|
+
# key and target move together (see the note below). Remove once @nestjs/graphql stops pinning it.
|
|
64
|
+
'ws@>=8.0.0 <8.23.0': '8.23.0'
|
|
65
|
+
# The 7.x copy comes from @nestjs/graphql 13 > subscriptions-transport-ws.
|
|
66
|
+
'ws@>=7.0.0 <7.5.14': '7.5.14'
|
|
54
67
|
|
|
55
68
|
# @nestjs/swagger exact-pins js-yaml (11.4.7: 5.3.0) — GHSA-r3ph-w7gj-g6xm (moderate, patched >=5.4.1)
|
|
56
69
|
# and, for older swagger releases, GHSA-pm4m-ph32-ghv5 (high, patched >=5.2.2).
|
|
@@ -105,7 +118,7 @@ tree to `2.0.11` even though nothing needed help any more.
|
|
|
105
118
|
|
|
106
119
|
### The `ws` target must stay in lockstep with the declared `ws` version
|
|
107
120
|
|
|
108
|
-
`8.21.3` is not an arbitrary "latest patch" — it is the version `@lenne.tech/nest-server` declares as
|
|
121
|
+
`8.23.0` (since 11.46.5; `8.21.3` before) is not an arbitrary "latest patch" — it is the version `@lenne.tech/nest-server` declares as
|
|
109
122
|
an ordinary **dependency**, so it is already in your tree whether or not you list `ws` yourself.
|
|
110
123
|
The override target has to equal it.
|
|
111
124
|
|
|
@@ -117,7 +130,9 @@ when you read a manifest. The target was raised `8.21.1` → `8.21.3` on 2026-08
|
|
|
117
130
|
reason.
|
|
118
131
|
|
|
119
132
|
**Rule:** whenever the `ws` version declared by `@lenne.tech/nest-server` (or by your own
|
|
120
|
-
`package.json`, if you list it) moves, move this override target with it in the
|
|
133
|
+
`package.json`, if you list it) moves, move this override's target **and the upper bound of its key** with it in the
|
|
134
|
+
same commit — pnpm matches the key against the requested range, so a key that stays below an exact pin no longer
|
|
135
|
+
reaches it. The
|
|
121
136
|
same applies to any other override whose package also appears as a declared dependency.
|
|
122
137
|
|
|
123
138
|
Then:
|
|
@@ -79,16 +79,28 @@ package default); nest-server-starter follows.
|
|
|
79
79
|
|
|
80
80
|
## 3. Own download routes
|
|
81
81
|
|
|
82
|
-
Replace every `stream.pipe(res)` that delivers a file with `pipeFileToResponse(stream, res)`, and pass an abort signal
|
|
82
|
+
Replace every `stream.pipe(res)` that delivers a file with `pipeFileToResponse(stream, res)`, and pass an abort signal.
|
|
83
|
+
|
|
84
|
+
**Since 11.46.4, open the stream with `openDownloadStream()`** — see `migration-guides/11.46.3-to-11.46.4.md`. With the
|
|
85
|
+
abort signal alone, a client that leaves before S3 answers makes the store request reject with `AbortError`, and an
|
|
86
|
+
uncaught one is an ERROR with a stack trace per aborted download. On 11.46.3, catch it yourself:
|
|
83
87
|
|
|
84
88
|
```typescript
|
|
85
|
-
import { downloadAbortSignal, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
89
|
+
import { downloadAbortSignal, isResponseGone, pipeFileToResponse } from '@lenne.tech/nest-server';
|
|
86
90
|
|
|
87
91
|
@Get('image/:id')
|
|
88
92
|
async image(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
89
93
|
// Fires when the client goes (response or request close), so a store request waiting for a socket is dropped
|
|
90
94
|
const abortSignal = downloadAbortSignal(res);
|
|
91
|
-
|
|
95
|
+
let stream: Readable | null;
|
|
96
|
+
try {
|
|
97
|
+
stream = await this.fileService.getFileStream(id, { abortSignal, currentUser });
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (isResponseGone(res)) {
|
|
100
|
+
return res; // the client left; the aborted store request is not an error
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
92
104
|
if (!stream) {
|
|
93
105
|
throw new NotFoundException();
|
|
94
106
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Migration Guide: 11.46.3 → 11.46.4
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None |
|
|
8
|
+
| **New Features** | `openDownloadStream(res, open)` is exported — the function the framework's download routes open a file stream with |
|
|
9
|
+
| **Bugfixes** | The documented pattern for an own download route logged an ERROR with a stack trace for every client that left before S3 answered, and answered a busy store with 500 instead of 503 (§1) |
|
|
10
|
+
| **Migration Effort** | Projects with their OWN download route: open the stream with `openDownloadStream()` (§1). Everyone else: `pnpm run update` |
|
|
11
|
+
|
|
12
|
+
## Quick Migration
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @lenne.tech/nest-server@11.46.4
|
|
16
|
+
pnpm run update # nest-server-starter based projects
|
|
17
|
+
grep -rn "downloadAbortSignal(" src/ # own download routes: open the stream with openDownloadStream() (§1)
|
|
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. Own download routes
|
|
25
|
+
|
|
26
|
+
11.46.3 documented passing `downloadAbortSignal(res)` to `getFileStream()`, so an S3 request whose client has gone is
|
|
27
|
+
dropped while it waits for a socket. The aborted request then REJECTS with `AbortError`. Nothing in the documented
|
|
28
|
+
pattern caught it: every client that left before S3 answered became `ERROR [ExceptionsHandler] … AbortError` with a
|
|
29
|
+
stack trace and a `500` sent into a closed response — under exactly the load the `S3 socket pool exhausted:` line has
|
|
30
|
+
to stand out in. A store that handed out no connection in time (`TimeoutError`) reached Nest as a `500` instead of the
|
|
31
|
+
`503` with `Retry-After` the framework's routes answer.
|
|
32
|
+
|
|
33
|
+
The framework's routes were not affected: they open the stream through `openDownloadStream()`, which was a protected
|
|
34
|
+
controller method until now. It is exported since 11.46.4:
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { downloadAbortSignal, openDownloadStream, pipeFileToResponse, RESPONSE_GONE } from '@lenne.tech/nest-server';
|
|
38
|
+
|
|
39
|
+
@Get('image/:id')
|
|
40
|
+
async image(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
41
|
+
const stream = await openDownloadStream(res, () =>
|
|
42
|
+
this.fileService.getFileStream(id, { abortSignal: downloadAbortSignal(res), currentUser }),
|
|
43
|
+
);
|
|
44
|
+
if (stream === RESPONSE_GONE) {
|
|
45
|
+
return res; // nobody left to deliver to
|
|
46
|
+
}
|
|
47
|
+
if (!stream) {
|
|
48
|
+
throw new NotFoundException();
|
|
49
|
+
}
|
|
50
|
+
res.header('Content-Type', 'image/png');
|
|
51
|
+
return pipeFileToResponse(stream, res);
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`openDownloadStream()`:
|
|
56
|
+
|
|
57
|
+
- does not ask the store when the client has already gone,
|
|
58
|
+
- answers `RESPONSE_GONE` when the store request failed because the client left meanwhile,
|
|
59
|
+
- destroys a stream that arrives after the client left,
|
|
60
|
+
- answers `503` with `Retry-After: 5` for `TimeoutError`, and rethrows every other error,
|
|
61
|
+
- passes `null` (the service's rights check refused) on unchanged.
|
|
62
|
+
|
|
63
|
+
`open` may return any stream: `CoreS3Service.getObject()` callers pass `async () => (await s3.getObject(key, { abortSignal })).body`.
|
|
64
|
+
|
|
65
|
+
## Troubleshooting
|
|
66
|
+
|
|
67
|
+
| Symptom | Cause | Fix |
|
|
68
|
+
|---|---|---|
|
|
69
|
+
| `ERROR [ExceptionsHandler] … AbortError` with a stack trace, often in bursts under load | an own download route passes `downloadAbortSignal(res)` but opens the stream without `openDownloadStream()` | §1 |
|
|
70
|
+
| Own download route answers `500` while `S3 socket pool exhausted` is logged | the `TimeoutError` of a busy store is not turned into a `503` | §1 |
|
|
71
|
+
|
|
72
|
+
## Module Documentation
|
|
73
|
+
|
|
74
|
+
- `src/core/modules/file/README.md` — "Delivering a file from your own route"
|
|
75
|
+
- `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# Migration Guide: 11.46.4 → 11.46.5
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None in nest-server. NestJS 11.2.10, which `pnpm run update` installs, adds startup errors for configurations 11.2.7 ignored (§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 11.2.10 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@11.46.5
|
|
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 11.46.4 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 11.46.5 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 11.46.5 `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 11.2.10
|
|
130
|
+
|
|
131
|
+
11.46.5 declares NestJS 11.2.10 (`@nestjs/common`, `@nestjs/core`, `@nestjs/platform-express`, `@nestjs/testing` (dev); from 11.2.7) — three patch releases of the 11.2 line (11.2.8 – 11.2.10). Besides the two advisories below they bring behaviour a REST / GraphQL application on Express can meet: a global guard, interceptor or pipe that cannot run (a class given as the `useValue` of `APP_GUARD`, one without `canActivate` / `intercept` / `transform`, or a class enhancer whose dependencies are request-scoped) and an invalid `forRoutes()` / `exclude()` entry now stop the application at startup — 11.2.7 dropped them silently, so they never took effect: correct or remove them. Middleware given to `forRoutes()` is also mounted on routes excluded from the global prefix, and multipart requests are capped at 1000 parts by default (`limits.parts` raises it). 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 11.2.10 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 13.4.5 exact-pins at
|
|
148
|
+
8.21.3. 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 two `ws`
|
|
150
|
+
entries, `'ws@>=8.0.0 <8.21.3': 8.21.3` and `'ws@>=7.0.0 <7.5.13': 7.5.13`: **replace both** with the two below. Do not
|
|
151
|
+
only raise their targets — pnpm matches the key against the requested exact version, and a key whose upper bound stays
|
|
152
|
+
below it leaves the vulnerable copy in the tree. 7.5.13 is itself covered by the advisory (patched 7.5.14).
|
|
153
|
+
|
|
154
|
+
```yaml
|
|
155
|
+
overrides:
|
|
156
|
+
# GHSA-37g9-w4hg-h9qr (high): @nestjs/graphql 13.4.5 exact-pins ws 8.21.3. Keep key and target in lockstep
|
|
157
|
+
# with the ws version @lenne.tech/nest-server declares (8.23.0 since 11.46.5). Remove once @nestjs/graphql pins ws >= 8.23.0.
|
|
158
|
+
'ws@>=8.0.0 <8.23.0': '8.23.0'
|
|
159
|
+
# The 7.x copy comes from @nestjs/graphql 13 > subscriptions-transport-ws, same advisory.
|
|
160
|
+
'ws@>=7.0.0 <7.5.14': '7.5.14'
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`pnpm why ws` must then show a single `ws@8.23.0` (and `ws@7.5.14` for the legacy transport). Until GitHub's global advisory database lists the
|
|
164
|
+
advisory, `pnpm audit` does not report the vulnerable version. A vendor-mode project adds the same entry.
|
|
165
|
+
|
|
166
|
+
## Troubleshooting
|
|
167
|
+
|
|
168
|
+
| Symptom | Cause | Fix |
|
|
169
|
+
|---|---|---|
|
|
170
|
+
| `ERROR [CoreFileController] File download failed: aborted` with `socketCloseListener` in the stack, one per aborted download | 11.46.3 – 11.46.4 on S3 | Update to 11.46.5 (§4) |
|
|
171
|
+
| `pnpm why ws` lists `ws@8.21.3` 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` |
|
|
172
|
+
| 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 |
|
|
173
|
+
| `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 |
|
|
174
|
+
| `RangeError: Invalid byte range` | A `range` with `start > end`, a negative or fractional value reached `getFileStream()` / `getObject()` | Produce it with `resolveDownloadRange()` |
|
|
175
|
+
| `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 |
|
|
176
|
+
|
|
177
|
+
## Module Documentation
|
|
178
|
+
|
|
179
|
+
- `docs/security-overrides.md` — the `ws` entry and its lockstep rule
|
|
180
|
+
|
|
181
|
+
- `src/core/modules/file/README.md` — "Byte ranges: video, audio, resumed downloads (11.46.5)"
|
|
182
|
+
- `src/core/modules/file/INTEGRATION-CHECKLIST.md` — Common Mistakes
|
|
183
|
+
- `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": "11.46.
|
|
3
|
+
"version": "11.46.5",
|
|
4
4
|
"description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"node",
|
|
@@ -94,13 +94,13 @@
|
|
|
94
94
|
"@getbrevo/brevo": "6.2.0",
|
|
95
95
|
"@modelcontextprotocol/sdk": "1.32.1",
|
|
96
96
|
"@nestjs/apollo": "13.4.5",
|
|
97
|
-
"@nestjs/common": "11.2.
|
|
98
|
-
"@nestjs/core": "11.2.
|
|
97
|
+
"@nestjs/common": "11.2.10",
|
|
98
|
+
"@nestjs/core": "11.2.10",
|
|
99
99
|
"@nestjs/graphql": "13.4.5",
|
|
100
100
|
"@nestjs/jwt": "11.0.2",
|
|
101
101
|
"@nestjs/mongoose": "11.0.4",
|
|
102
102
|
"@nestjs/passport": "11.0.5",
|
|
103
|
-
"@nestjs/platform-express": "11.2.
|
|
103
|
+
"@nestjs/platform-express": "11.2.10",
|
|
104
104
|
"@nestjs/schedule": "6.1.3",
|
|
105
105
|
"@nestjs/swagger": "11.4.7",
|
|
106
106
|
"@nestjs/terminus": "11.1.1",
|
|
@@ -138,7 +138,7 @@
|
|
|
138
138
|
"supertest": "7.3.1",
|
|
139
139
|
"ts-morph": "28.0.0",
|
|
140
140
|
"undici": "7.30.2",
|
|
141
|
-
"ws": "8.
|
|
141
|
+
"ws": "8.23.0",
|
|
142
142
|
"yuml-diagram": "1.2.0"
|
|
143
143
|
},
|
|
144
144
|
"peerDependencies": {
|
|
@@ -190,7 +190,7 @@
|
|
|
190
190
|
"@compodoc/compodoc": "2.0.0",
|
|
191
191
|
"@nestjs/cli": "11.0.24",
|
|
192
192
|
"@nestjs/schematics": "11.1.0",
|
|
193
|
-
"@nestjs/testing": "11.2.
|
|
193
|
+
"@nestjs/testing": "11.2.10",
|
|
194
194
|
"@swc/cli": "0.8.1",
|
|
195
195
|
"@swc/core": "1.16.18",
|
|
196
196
|
"@tus/s3-store": "2.0.8",
|
|
@@ -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,5 +1,6 @@
|
|
|
1
1
|
import { mongo, Types } from 'mongoose';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
|
+
import type { ByteRange } from './byte-range.helper';
|
|
3
4
|
|
|
4
5
|
// Use Mongoose's MongoDB types to avoid BSON version conflicts
|
|
5
6
|
const ObjectId = Types.ObjectId;
|
|
@@ -279,18 +280,31 @@ export class GridFSHelper {
|
|
|
279
280
|
}
|
|
280
281
|
|
|
281
282
|
/**
|
|
282
|
-
* Open download stream by ID
|
|
283
|
+
* Open download stream by ID — with `range`, only those bytes (both inclusive). The range must lie inside the
|
|
284
|
+
* file: GridFS refuses a start or end past its length with an error on the stream.
|
|
283
285
|
*/
|
|
284
|
-
static openDownloadStream(
|
|
286
|
+
static openDownloadStream(
|
|
287
|
+
bucket: GridFSBucket,
|
|
288
|
+
id: string | Types.ObjectId,
|
|
289
|
+
range?: ByteRange,
|
|
290
|
+
): GridFSBucketReadStream {
|
|
285
291
|
const objectId = typeof id === 'string' ? new ObjectId(id) : id;
|
|
286
|
-
return bucket.openDownloadStream(objectId);
|
|
292
|
+
return bucket.openDownloadStream(objectId, GridFSHelper.streamRange(range));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Open download stream by name — with `range`, only those bytes (both inclusive)
|
|
297
|
+
*/
|
|
298
|
+
static openDownloadStreamByName(bucket: GridFSBucket, filename: string, range?: ByteRange): GridFSBucketReadStream {
|
|
299
|
+
return bucket.openDownloadStreamByName(filename, GridFSHelper.streamRange(range));
|
|
287
300
|
}
|
|
288
301
|
|
|
289
302
|
/**
|
|
290
|
-
*
|
|
303
|
+
* The GridFS stream options of a range. GridFS counts `end` EXCLUSIVE (the byte after the last one), HTTP and
|
|
304
|
+
* `ByteRange` count it inclusive — hence the `+ 1`.
|
|
291
305
|
*/
|
|
292
|
-
static
|
|
293
|
-
return
|
|
306
|
+
static streamRange(range?: ByteRange): undefined | { end: number; start: number } {
|
|
307
|
+
return range ? { end: range.end + 1, start: range.start } : undefined;
|
|
294
308
|
}
|
|
295
309
|
|
|
296
310
|
/**
|