@lenne.tech/nest-server 12.6.11 → 12.6.13
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/package-management.md +7 -7
- package/.claude/rules/role-system.md +10 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +4 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
- package/dist/core/common/helpers/byte-range.helper.js +71 -0
- package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +9 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +29 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +220 -0
- package/dist/core/common/helpers/graphql-upload.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/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.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/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.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 +5 -0
- package/dist/core/modules/file/core-file.controller.js +66 -4
- 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/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -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/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +31 -9
- package/docs/error-codes.md +14 -0
- package/docs/security-overrides.md +34 -6
- package/migration-guides/12.6.11-to-12.6.12.md +180 -0
- package/migration-guides/12.6.12-to-12.6.13.md +162 -0
- package/package.json +15 -8
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +9 -0
- package/src/core/common/helpers/byte-range.helper.ts +144 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +78 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +482 -0
- package/src/core/common/helpers/gridfs.helper.ts +20 -6
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/services/core-s3.service.ts +16 -2
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/error-code/error-codes.ts +13 -0
- package/src/core/modules/file/INTEGRATION-CHECKLIST.md +1 -0
- package/src/core/modules/file/README.md +74 -1
- package/src/core/modules/file/core-file.controller.ts +139 -3
- 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/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +2 -0
- package/src/test/README.md +8 -4
- package/src/test/test.helper.ts +12 -0
- package/src/types/graphql-upload.d.ts +34 -2
|
@@ -10,7 +10,11 @@ import {
|
|
|
10
10
|
import { ModuleRef, Reflector } from '@nestjs/core';
|
|
11
11
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
isAgentCallContext,
|
|
15
|
+
resolveAgentCallRequest,
|
|
16
|
+
resolveGuardRequest,
|
|
17
|
+
} from '../../../common/helpers/execution-context-request.helper.js';
|
|
14
18
|
import { firstValueFrom, isObservable } from 'rxjs';
|
|
15
19
|
|
|
16
20
|
import { RoleEnum } from '../../../common/enums/role.enum.js';
|
|
@@ -147,6 +151,19 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
147
151
|
throw new ForbiddenException(ErrorCode.ACCESS_DENIED);
|
|
148
152
|
}
|
|
149
153
|
|
|
154
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
155
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
156
|
+
// where the route is public. Kept in sync with BetterAuthRolesGuard (nestjs-ai plan §1).
|
|
157
|
+
if (isAgentCallContext(context) && !this.getRequest(context)) {
|
|
158
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
159
|
+
// S_EVERYONE does not open a method that asks for S_USER
|
|
160
|
+
const effective = reflectorRoles?.[0]?.some((value) => !!value) ? reflectorRoles[0] : roles;
|
|
161
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
165
|
+
}
|
|
166
|
+
|
|
150
167
|
// API tokens are decided BEFORE the public-route shortcut below: a token is denied on every route
|
|
151
168
|
// that does not declare @ApiTokenScopes(), public ones included (see core-api-token.helpers).
|
|
152
169
|
// A tenant token is fully decided there. A user token was authenticated by CoreApiTokenMiddleware,
|
|
@@ -289,6 +306,11 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
289
306
|
cookies?: Record<string, string>;
|
|
290
307
|
headers?: Record<string, string | string[] | undefined>;
|
|
291
308
|
} {
|
|
309
|
+
// An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
|
|
310
|
+
if (isAgentCallContext(context)) {
|
|
311
|
+
return resolveAgentCallRequest(context) ?? null;
|
|
312
|
+
}
|
|
313
|
+
|
|
292
314
|
// Try GraphQL context first
|
|
293
315
|
try {
|
|
294
316
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -8,7 +8,11 @@ import {
|
|
|
8
8
|
} from '@nestjs/common';
|
|
9
9
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
agentCallOf,
|
|
13
|
+
isAgentCallContext,
|
|
14
|
+
resolveGuardRequest,
|
|
15
|
+
} from '../../common/helpers/execution-context-request.helper.js';
|
|
12
16
|
|
|
13
17
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
14
18
|
import { ApiTokenKind } from '../api-token/core-api-token.constants.js';
|
|
@@ -103,6 +107,20 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
103
107
|
// that does not declare @ApiTokenScopes(), public ones included. A tenant token is fully decided
|
|
104
108
|
// there; a user token continues through the ordinary checks as its user (see core-api-token.helpers).
|
|
105
109
|
const request = this.getRequest(context);
|
|
110
|
+
|
|
111
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
112
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
113
|
+
// where the route is public. Kept in sync with RolesGuard (nestjs-ai plan §1).
|
|
114
|
+
if (isAgentCallContext(context) && !request) {
|
|
115
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
116
|
+
// S_EVERYONE does not open a method that asks for S_USER. Kept in sync with RolesGuard.
|
|
117
|
+
const effective = handlerRoles?.some((value) => !!value) ? handlerRoles : roles;
|
|
118
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
122
|
+
}
|
|
123
|
+
|
|
106
124
|
const apiTokenKind = enforceApiTokenRoute({
|
|
107
125
|
controllerClass: context.getClass(),
|
|
108
126
|
handler: context.getHandler(),
|
|
@@ -205,6 +223,16 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
205
223
|
* Get target ID from context for S_SELF checks
|
|
206
224
|
*/
|
|
207
225
|
private getTargetId(context: ExecutionContext): null | string {
|
|
226
|
+
// An agent function / MCP call: its arguments are the target, as a resolver's args are on GraphQL. Never the HTTP
|
|
227
|
+
// fallback below, which would read the same arguments as if they were a request with `params`.
|
|
228
|
+
if (isAgentCallContext(context)) {
|
|
229
|
+
if (!agentCallOf(context)) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const input = context.getArgByIndex(0);
|
|
233
|
+
return typeof input?.id === 'string' ? input.id : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
// Try GraphQL args
|
|
209
237
|
try {
|
|
210
238
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -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 |
|
|
@@ -11,6 +11,9 @@ File upload and download functionality with MongoDB GridFS storage.
|
|
|
11
11
|
| GET | `/files/id/:id` | Download file by ID | `downloadRoles` |
|
|
12
12
|
| GET | `/files/:filename` | Download file by filename | `downloadRoles` |
|
|
13
13
|
|
|
14
|
+
Both answer a `Range` request with `206 Partial Content` (12.6.12+) — see
|
|
15
|
+
[Byte ranges](#byte-ranges-video-audio-resumed-downloads-1293).
|
|
16
|
+
|
|
14
17
|
### GraphQL members (via CoreFileResolver)
|
|
15
18
|
|
|
16
19
|
| Member | Kind | Gated by |
|
|
@@ -487,7 +490,8 @@ export class FileController extends CoreFileController {
|
|
|
487
490
|
The mid-stream failure case is handled by `pipeFileToResponse()`. Without it the stream error would
|
|
488
491
|
go unhandled, Node would destroy the socket, and a reverse proxy would report **502 Bad Gateway** —
|
|
489
492
|
i.e. "the server is down", while every other route keeps answering. On the error path the headers
|
|
490
|
-
describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag
|
|
493
|
+
describing the file (`Content-Type`, `Content-Disposition`, `Cache-Control`, `ETag`, and since 12.6.12 `Content-Range`
|
|
494
|
+
and `Accept-Ranges`) are removed, so
|
|
491
495
|
the JSON body is not labelled as the image it failed to deliver. The error itself is logged
|
|
492
496
|
server-side even though the client answer stays deliberately generic.
|
|
493
497
|
|
|
@@ -499,6 +503,9 @@ on the controller rather than the exported function of the same name.
|
|
|
499
503
|
| `If-None-Match` names the file's weak `ETag` (`W/"<id>"`), after the rights check | `304` | No body; the store is not read |
|
|
500
504
|
| The store hands out no connection within 3 attempts of `s3.connectionTimeoutMs` (pool busy) | `503` | `Retry-After: 5`; the store is busy, not broken |
|
|
501
505
|
| The client left before the stream was handed over | — | Nothing is sent; the stream is destroyed at once, a pending S3 request aborted |
|
|
506
|
+
| The client left mid-transfer and the store reports the abort (S3: `aborted`) (12.6.12+) | — | Nothing is sent; logged at debug, never as ERROR |
|
|
507
|
+
| `Range` names one range inside the file (12.6.12+) | `206` | `Content-Range: bytes <start>-<end>/<length>`, only those bytes |
|
|
508
|
+
| `Range` starts at or past the end of the file (12.6.12+) | `416` | `Content-Range: bytes */<length>`, `ErrorCode.FILE_RANGE_NOT_SATISFIABLE` |
|
|
502
509
|
|
|
503
510
|
### Delivering a file from your own route (12.6.10)
|
|
504
511
|
|
|
@@ -551,6 +558,72 @@ Layers below it, each effective on its own:
|
|
|
551
558
|
waits for a socket instead of taking one later. The framework's routes do this.
|
|
552
559
|
- `s3.presignedDownloads` moves the bytes off the API entirely (a `302` to S3) — consider it for public files.
|
|
553
560
|
|
|
561
|
+
### Byte ranges: video, audio, resumed downloads (12.6.12)
|
|
562
|
+
|
|
563
|
+
Safari refuses to play a video — and stalls audio — from a server that answers a `Range` request with `200` and the
|
|
564
|
+
whole file. Chrome plays it anyway, so the problem does not show locally or in a Chromium-based Playwright run. Media
|
|
565
|
+
players seek with ranges, download managers resume with them.
|
|
566
|
+
|
|
567
|
+
The framework's download routes answer ranges on every store. For a route of your own, three pieces:
|
|
568
|
+
|
|
569
|
+
| Piece | What it does |
|
|
570
|
+
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
571
|
+
| `resolveDownloadRange(res, length)` | Reads `Range` from the request. Returns the range (`{ start, end }`, both inclusive) or `undefined` for the whole file; THROWS `416` with `Content-Range: bytes */<length>` for a range past the end. Call it after the rights check — a 416 confirms that the file exists |
|
|
572
|
+
| `getFileStream(id, { range })` | Reads only those bytes: S3 with a ranged `GetObject`, GridFS from the chunk holding the first byte, the filesystem from that offset. Same idle guard and abort signal as a whole file; `getFileStreamByName()` and `CoreS3Service.getObject(key, { range })` take it too |
|
|
573
|
+
| `setDownloadRangeHeaders(res, range, length)` | `Accept-Ranges: bytes`; for a range `206`, `Content-Range`, the range's `Content-Length` and `no-transform` in `Cache-Control`. Call it after your own headers, right before `pipeFileToResponse()` |
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
import {
|
|
577
|
+
downloadAbortSignal,
|
|
578
|
+
openDownloadStream,
|
|
579
|
+
pipeFileToResponse,
|
|
580
|
+
resolveDownloadRange,
|
|
581
|
+
RESPONSE_GONE,
|
|
582
|
+
setDownloadRangeHeaders,
|
|
583
|
+
} from '@lenne.tech/nest-server';
|
|
584
|
+
|
|
585
|
+
@Get('video/:id')
|
|
586
|
+
async video(@Param('id') id: string, @Res() res: Response, @CurrentUser() currentUser) {
|
|
587
|
+
const serviceOptions = { abortSignal: downloadAbortSignal(res), currentUser };
|
|
588
|
+
const resolved = await this.fileService.resolveFile(id, serviceOptions); // rights check, length, store
|
|
589
|
+
if (!resolved) {
|
|
590
|
+
throw new NotFoundException();
|
|
591
|
+
}
|
|
592
|
+
const range = resolveDownloadRange(res, resolved.info.length); // throws 416 past the end
|
|
593
|
+
const stream = await openDownloadStream(res, () =>
|
|
594
|
+
this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
|
|
595
|
+
);
|
|
596
|
+
if (stream === RESPONSE_GONE) {
|
|
597
|
+
return res;
|
|
598
|
+
}
|
|
599
|
+
if (!stream) {
|
|
600
|
+
throw new NotFoundException();
|
|
601
|
+
}
|
|
602
|
+
res.header('Content-Type', resolved.info.contentType || 'video/mp4');
|
|
603
|
+
res.header('Cache-Control', 'private, no-store');
|
|
604
|
+
setDownloadRangeHeaders(res, range, resolved.info.length);
|
|
605
|
+
return pipeFileToResponse(stream, res);
|
|
606
|
+
}
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
What is served, and why:
|
|
610
|
+
|
|
611
|
+
- **One range per request.** Several ranges (`bytes=0-1,5-9`) get the whole file with `200` — a `multipart/byteranges`
|
|
612
|
+
answer is not built, the way Express's `send` handles it. Every media player asks for one range at a time.
|
|
613
|
+
- **A range past the end is cut at the last byte** (`bytes=0-999999999` is the whole file), a suffix longer than the
|
|
614
|
+
file is the whole file. Only a range STARTING at or past the end is `416`, and every range of an empty file.
|
|
615
|
+
- **An invalid header** (`bytes=5-2`, another unit) is ignored: the whole file with `200`, which every client can use.
|
|
616
|
+
- **`If-Range` gets the whole file.** The routes' validator is a weak `ETag`, which `If-Range` never matches
|
|
617
|
+
(RFC 9110 §13.1.5). A route with a strong validator can decide `If-Range` itself and call `parseRangeHeader()`.
|
|
618
|
+
- **`no-transform` on a `206`** keeps `compression` away: a gzipped partial body would no longer match the offsets in
|
|
619
|
+
its `Content-Range`. A whole file is compressed as before (when its type is compressible).
|
|
620
|
+
- **`range` on the service must lie inside the file** — `resolveDownloadRange()` guarantees it. A malformed range
|
|
621
|
+
(negative, not an integer, `start > end`) throws a `RangeError` before any store is asked; a range reaching past the
|
|
622
|
+
end of the file is not checked by the service and fails per store (GridFS: an error on the stream, S3: `InvalidRange`
|
|
623
|
+
for a start past the end).
|
|
624
|
+
- **Presigned downloads** (`s3.presignedDownloads`) redirect before any of this: the browser sends its `Range` to S3,
|
|
625
|
+
which answers it itself.
|
|
626
|
+
|
|
554
627
|
### Upload filtering
|
|
555
628
|
|
|
556
629
|
Upload endpoints are project-specific, but the filter they install comes from the framework
|
|
@@ -2,6 +2,8 @@ import {
|
|
|
2
2
|
BadRequestException,
|
|
3
3
|
Controller,
|
|
4
4
|
Get,
|
|
5
|
+
HttpException,
|
|
6
|
+
HttpStatus,
|
|
5
7
|
Logger,
|
|
6
8
|
NotFoundException,
|
|
7
9
|
Param,
|
|
@@ -14,6 +16,7 @@ import type { Readable } from 'stream';
|
|
|
14
16
|
import { CurrentUser } from '../../common/decorators/current-user.decorator.js';
|
|
15
17
|
import { Roles } from '../../common/decorators/roles.decorator.js';
|
|
16
18
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
19
|
+
import { type ByteRange, contentRangeValue, parseRangeHeader } from '../../common/helpers/byte-range.helper.js';
|
|
17
20
|
import { buildContentDisposition } from '../../common/helpers/content-disposition.helper.js';
|
|
18
21
|
import { StreamIdleTimeoutError } from '../../common/helpers/idle-stream.helper.js';
|
|
19
22
|
import { ConfigService } from '../../common/services/config.service.js';
|
|
@@ -141,7 +144,15 @@ export const RESPONSE_GONE = Symbol('lt.responseGone');
|
|
|
141
144
|
* ofetch/`$fetch` client picks its parser from that header and hands the caller a
|
|
142
145
|
* Blob instead of the error message.
|
|
143
146
|
*/
|
|
144
|
-
const FILE_DELIVERY_HEADERS = [
|
|
147
|
+
const FILE_DELIVERY_HEADERS = [
|
|
148
|
+
'Accept-Ranges',
|
|
149
|
+
'Cache-Control',
|
|
150
|
+
'Content-Disposition',
|
|
151
|
+
'Content-Length',
|
|
152
|
+
'Content-Range',
|
|
153
|
+
'Content-Type',
|
|
154
|
+
'ETag',
|
|
155
|
+
];
|
|
145
156
|
|
|
146
157
|
/**
|
|
147
158
|
* Re-exported from the leaf it now lives in, so no import path broke.
|
|
@@ -222,6 +233,23 @@ export function pipeFileToResponse(stream: Readable, res: Response): Response {
|
|
|
222
233
|
.json({ error: 'Service Unavailable', message: 'File storage is busy, please retry', statusCode: 503 });
|
|
223
234
|
return;
|
|
224
235
|
}
|
|
236
|
+
// The client has gone, and the store reports the abort that followed. Not a server error: nobody receives an
|
|
237
|
+
// answer any more, so no ERROR line per aborted download and no status. The order is the reason this cannot be
|
|
238
|
+
// left to the release listeners above: `downloadAbortSignal()` registers its listeners first (it must, the client
|
|
239
|
+
// may leave during the rights check), so on the event that reports the client gone it aborts the S3 request
|
|
240
|
+
// BEFORE this function's own listener runs, and the SDK fails the body with `aborted` inside that same dispatch.
|
|
241
|
+
// Measured through the Nest route (a GET whose request is not read to its end, so its `close` reports the
|
|
242
|
+
// abort): every aborted S3 download logged `File download failed: aborted` — one ERROR per seek of a video
|
|
243
|
+
// player, burying the `S3 socket pool exhausted:` line. A store error while the client is still there stays an
|
|
244
|
+
// ERROR below.
|
|
245
|
+
if (state.responseClosed || state.clientGoneSignal || isResponseGone(res)) {
|
|
246
|
+
state.clientGoneSignal ||= 'store error after the client left';
|
|
247
|
+
fileStreamLogger.debug(`File download ended after the client left: ${err.message}`);
|
|
248
|
+
if (!res.destroyed) {
|
|
249
|
+
res.destroy();
|
|
250
|
+
}
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
225
253
|
// The answer to the CLIENT stays deliberately indistinguishable from an
|
|
226
254
|
// unknown id, but the server must not lose the event: a files document
|
|
227
255
|
// without its chunks is data corruption, and an error silently converted
|
|
@@ -370,6 +398,92 @@ export async function openDownloadStream<T extends null | Readable | undefined>(
|
|
|
370
398
|
return stream;
|
|
371
399
|
}
|
|
372
400
|
|
|
401
|
+
/**
|
|
402
|
+
* Which bytes of a file a download request asks for — the `Range` header, resolved against the file's `length`.
|
|
403
|
+
*
|
|
404
|
+
* WHY: a server that answers a `Range` request with `200` and the whole file works in Chrome and fails in Safari,
|
|
405
|
+
* which refuses to play a video (and stalls audio) from a server that does not answer ranges with `206 Partial
|
|
406
|
+
* Content`. Media players seek with ranges, download managers resume with them.
|
|
407
|
+
*
|
|
408
|
+
* Returns the range to read (pass it as `range` to `getFileStream()` / `getFileStreamByName()`, then call
|
|
409
|
+
* {@link setDownloadRangeHeaders}), or `undefined` for the whole file: no `Range` header, an invalid one, several
|
|
410
|
+
* ranges, a unit other than `bytes`, an unknown `length`, or an `If-Range` precondition — the framework's file
|
|
411
|
+
* validator is a weak `ETag`, which `If-Range` never matches (RFC 9110 §13.1.5), so such a request gets the whole
|
|
412
|
+
* file, which is always correct. See `parseRangeHeader()` for every rule.
|
|
413
|
+
*
|
|
414
|
+
* A range that starts at or past the end of the file THROWS `416 Range Not Satisfiable` with
|
|
415
|
+
* `Content-Range: bytes *\/<length>` and `#LTNS_0503`. Call it only AFTER the file was resolved with the rights
|
|
416
|
+
* check, like {@link CoreFileController.answerNotModified}: a 416 confirms that the file exists.
|
|
417
|
+
*
|
|
418
|
+
* ```typescript
|
|
419
|
+
* const resolved = await this.fileService.resolveFile(id, serviceOptions);
|
|
420
|
+
* if (!resolved) throw new NotFoundException();
|
|
421
|
+
* const range = resolveDownloadRange(res, resolved.info.length);
|
|
422
|
+
* const stream = await openDownloadStream(res, () =>
|
|
423
|
+
* this.fileService.getFileStream(id, { ...serviceOptions, range }, resolved.store),
|
|
424
|
+
* );
|
|
425
|
+
* // RESPONSE_GONE / null as in openDownloadStream()
|
|
426
|
+
* res.header('Content-Type', resolved.info.contentType);
|
|
427
|
+
* setDownloadRangeHeaders(res, range, resolved.info.length);
|
|
428
|
+
* return pipeFileToResponse(stream, res);
|
|
429
|
+
* ```
|
|
430
|
+
*/
|
|
431
|
+
export function resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
|
|
432
|
+
const headers = (res as Response & { req?: { headers?: Record<string, string | string[] | undefined> } }).req
|
|
433
|
+
?.headers;
|
|
434
|
+
const header = headers?.range;
|
|
435
|
+
if (!header) {
|
|
436
|
+
return undefined;
|
|
437
|
+
}
|
|
438
|
+
// `If-Range` asks for the range only if the file is still the one the client holds part of. The only validator these
|
|
439
|
+
// routes send is a WEAK `ETag`, and `If-Range` compares strongly — it never matches, so the Range is ignored and the
|
|
440
|
+
// whole file sent (RFC 9110 §13.1.5). A project route with a strong validator decides `If-Range` itself.
|
|
441
|
+
if (headers['if-range'] !== undefined) {
|
|
442
|
+
return undefined;
|
|
443
|
+
}
|
|
444
|
+
const decision = parseRangeHeader(header, length);
|
|
445
|
+
if (decision === 'unsatisfiable') {
|
|
446
|
+
res.setHeader('Content-Range', `bytes */${length}`);
|
|
447
|
+
res.setHeader('Accept-Ranges', 'bytes');
|
|
448
|
+
throw new HttpException(ErrorCode.FILE_RANGE_NOT_SATISFIABLE, HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
|
|
449
|
+
}
|
|
450
|
+
return decision;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* The headers of a ranged (or rangeable) file response — call it after the stream was opened, right before
|
|
455
|
+
* {@link pipeFileToResponse}, AFTER the project's own `Content-Length` (it overrides it for a range):
|
|
456
|
+
*
|
|
457
|
+
* - always (with a known `length`): `Accept-Ranges: bytes`, so a client knows it may ask for ranges;
|
|
458
|
+
* - with a range: status `206`, `Content-Range: bytes <start>-<end>/<length>`, `Content-Length` of the range, and
|
|
459
|
+
* `no-transform` added to `Cache-Control`. The last one keeps a `compression` middleware from gzipping a partial
|
|
460
|
+
* body: `compression` skips a response marked `no-transform`, and a compressed range would no longer match the
|
|
461
|
+
* byte positions its `Content-Range` names. It also tells proxies not to transform it.
|
|
462
|
+
*
|
|
463
|
+
* Without a range and without a known `length` it does nothing.
|
|
464
|
+
*/
|
|
465
|
+
export function setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
|
|
466
|
+
const knownLength = typeof length === 'number' && Number.isSafeInteger(length) && length >= 0;
|
|
467
|
+
if (knownLength) {
|
|
468
|
+
res.setHeader('Accept-Ranges', 'bytes');
|
|
469
|
+
}
|
|
470
|
+
if (!range) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
res.status(HttpStatus.PARTIAL_CONTENT);
|
|
474
|
+
// A 206 must carry Content-Range; `*` stands for a complete length nobody knows (RFC 9110 §14.4)
|
|
475
|
+
res.setHeader(
|
|
476
|
+
'Content-Range',
|
|
477
|
+
knownLength ? contentRangeValue(range, length) : `bytes ${range.start}-${range.end}/*`,
|
|
478
|
+
);
|
|
479
|
+
res.setHeader('Content-Length', String(range.end - range.start + 1));
|
|
480
|
+
const cacheControl = res.getHeader?.('Cache-Control');
|
|
481
|
+
const directives = Array.isArray(cacheControl) ? cacheControl.join(', ') : String(cacheControl ?? '');
|
|
482
|
+
if (!/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(directives)) {
|
|
483
|
+
res.setHeader('Cache-Control', directives.trim() ? `${directives}, no-transform` : 'no-transform');
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
373
487
|
/**
|
|
374
488
|
* File controller
|
|
375
489
|
*
|
|
@@ -502,8 +616,11 @@ export abstract class CoreFileController {
|
|
|
502
616
|
res.redirect(302, url);
|
|
503
617
|
return res;
|
|
504
618
|
}
|
|
619
|
+
// A `Range` request (Safari's video player, a resumed download) reads only those bytes — decided after the rights
|
|
620
|
+
// check and the 304, because a 416 confirms that the file exists
|
|
621
|
+
const range = this.resolveDownloadRange(res, file.length);
|
|
505
622
|
const filestream = await this.openDownloadStream(res, () =>
|
|
506
|
-
this.fileService.getFileStream(id, serviceOptions, resolved.store),
|
|
623
|
+
this.fileService.getFileStream(id, range ? { ...serviceOptions, range } : serviceOptions, resolved.store),
|
|
507
624
|
);
|
|
508
625
|
if (filestream === RESPONSE_GONE) {
|
|
509
626
|
return res;
|
|
@@ -514,6 +631,7 @@ export abstract class CoreFileController {
|
|
|
514
631
|
throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
|
|
515
632
|
}
|
|
516
633
|
this.setFileHeaders(res, file);
|
|
634
|
+
this.setDownloadRangeHeaders(res, range, file.length);
|
|
517
635
|
return this.pipeFileToResponse(filestream, res);
|
|
518
636
|
}
|
|
519
637
|
|
|
@@ -555,8 +673,9 @@ export abstract class CoreFileController {
|
|
|
555
673
|
res.redirect(302, url);
|
|
556
674
|
return res;
|
|
557
675
|
}
|
|
676
|
+
const range = this.resolveDownloadRange(res, file.length);
|
|
558
677
|
const filestream = await this.openDownloadStream(res, () =>
|
|
559
|
-
this.fileService.getFileStream(file.id, serviceOptions),
|
|
678
|
+
this.fileService.getFileStream(file.id, range ? { ...serviceOptions, range } : serviceOptions),
|
|
560
679
|
);
|
|
561
680
|
if (filestream === RESPONSE_GONE) {
|
|
562
681
|
return res;
|
|
@@ -565,6 +684,7 @@ export abstract class CoreFileController {
|
|
|
565
684
|
throw new NotFoundException(ErrorCode.FILE_NOT_FOUND);
|
|
566
685
|
}
|
|
567
686
|
this.setFileHeaders(res, file);
|
|
687
|
+
this.setDownloadRangeHeaders(res, range, file.length);
|
|
568
688
|
return this.pipeFileToResponse(filestream, res);
|
|
569
689
|
}
|
|
570
690
|
|
|
@@ -587,6 +707,22 @@ export abstract class CoreFileController {
|
|
|
587
707
|
return openDownloadStream(res, open);
|
|
588
708
|
}
|
|
589
709
|
|
|
710
|
+
/**
|
|
711
|
+
* The byte range a download request asks for — see the exported {@link resolveDownloadRange}. Throws `416` for an
|
|
712
|
+
* unsatisfiable range. Override it to serve ranges differently (or not at all: return `undefined`).
|
|
713
|
+
*/
|
|
714
|
+
protected resolveDownloadRange(res: Response, length: number | undefined): ByteRange | undefined {
|
|
715
|
+
return resolveDownloadRange(res, length);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* `Accept-Ranges`, and for a range `206` with `Content-Range` — see the exported {@link setDownloadRangeHeaders}.
|
|
720
|
+
* Called after {@link setFileHeaders}, whose `Content-Length` it replaces for a range.
|
|
721
|
+
*/
|
|
722
|
+
protected setDownloadRangeHeaders(res: Response, range: ByteRange | undefined, length: number | undefined): void {
|
|
723
|
+
setDownloadRangeHeaders(res, range, length);
|
|
724
|
+
}
|
|
725
|
+
|
|
590
726
|
/**
|
|
591
727
|
* Set the response headers that describe the file being delivered.
|
|
592
728
|
*
|
|
@@ -4,6 +4,7 @@ import type { mongo, Types } from 'mongoose';
|
|
|
4
4
|
import { Readable } from 'stream';
|
|
5
5
|
|
|
6
6
|
import { FilterArgs } from '../../common/args/filter.args.js';
|
|
7
|
+
import { assertByteRange } from '../../common/helpers/byte-range.helper.js';
|
|
7
8
|
import { accessDeniedException } from '../../common/exceptions/access-denied.exception.js';
|
|
8
9
|
import { getObjectIds, getStringIds } from '../../common/helpers/db.helper.js';
|
|
9
10
|
import { convertFilterArgsToQuery } from '../../common/helpers/filter.helper.js';
|
|
@@ -484,6 +485,10 @@ export abstract class CoreFileService {
|
|
|
484
485
|
|
|
485
486
|
/**
|
|
486
487
|
* Get file stream (for big files) via file ID
|
|
488
|
+
*
|
|
489
|
+
* With `serviceOptions.range`, only those bytes (both inclusive) — from every store: S3 with a ranged
|
|
490
|
+
* `GetObject`, GridFS from the chunk that holds the first byte, the filesystem from that offset. See
|
|
491
|
+
* {@link FileServiceOptions.range} for the contract and `resolveDownloadRange()` for producing one from a request.
|
|
487
492
|
*/
|
|
488
493
|
async getFileStream(
|
|
489
494
|
id: string | Types.ObjectId,
|
|
@@ -493,6 +498,8 @@ export abstract class CoreFileService {
|
|
|
493
498
|
if (this.isMalformedFileId(id)) {
|
|
494
499
|
return null;
|
|
495
500
|
}
|
|
501
|
+
// Checked before anything is asked: a malformed range is a caller's bug, answered the same for every store
|
|
502
|
+
assertByteRange(serviceOptions?.range);
|
|
496
503
|
if (!(await this.checkRights(id, { ...serviceOptions, checkInputType: 'id' }))) {
|
|
497
504
|
return null;
|
|
498
505
|
}
|
|
@@ -502,6 +509,19 @@ export abstract class CoreFileService {
|
|
|
502
509
|
// the same one-to-three metadata round trips are not repeated per download.
|
|
503
510
|
// Omitting it keeps the previous behaviour exactly.
|
|
504
511
|
const store = knownStore ?? (await this.locateFile(id));
|
|
512
|
+
return this.openStoreStream(store, id, serviceOptions);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Open the download stream of a file in the store that holds it — the whole file, or `serviceOptions.range` —
|
|
517
|
+
* guarded against a caller that stops reading. The rights check is the caller's: this only reads bytes.
|
|
518
|
+
*/
|
|
519
|
+
protected async openStoreStream(
|
|
520
|
+
store: FileStorageDriver,
|
|
521
|
+
id: string | Types.ObjectId,
|
|
522
|
+
serviceOptions?: FileServiceOptions,
|
|
523
|
+
): Promise<Readable> {
|
|
524
|
+
const range = assertByteRange(serviceOptions?.range);
|
|
505
525
|
if (store === 's3') {
|
|
506
526
|
return this.guardDownloadStream(
|
|
507
527
|
await S3FileHelper.getStream(this.options.s3Service, id, this.s3StreamOptions(serviceOptions)),
|
|
@@ -509,10 +529,10 @@ export abstract class CoreFileService {
|
|
|
509
529
|
);
|
|
510
530
|
}
|
|
511
531
|
if (store === 'filesystem') {
|
|
512
|
-
return this.guardDownloadStream(FilesystemFileHelper.getStream(this.filesystemDir, id), serviceOptions);
|
|
532
|
+
return this.guardDownloadStream(FilesystemFileHelper.getStream(this.filesystemDir, id, range), serviceOptions);
|
|
513
533
|
}
|
|
514
534
|
return this.guardDownloadStream(
|
|
515
|
-
GridFSHelper.openDownloadStream(this.files, getObjectIds(id)) as mongo.GridFSBucketReadStream,
|
|
535
|
+
GridFSHelper.openDownloadStream(this.files, getObjectIds(id), range) as mongo.GridFSBucketReadStream,
|
|
516
536
|
serviceOptions,
|
|
517
537
|
);
|
|
518
538
|
}
|
|
@@ -535,12 +555,17 @@ export abstract class CoreFileService {
|
|
|
535
555
|
});
|
|
536
556
|
}
|
|
537
557
|
|
|
538
|
-
/** Options for the S3 stream of a download: the caller's abort signal and
|
|
558
|
+
/** Options for the S3 stream of a download: the caller's abort signal, idle time and byte range. */
|
|
539
559
|
protected s3StreamOptions(serviceOptions?: FileServiceOptions): {
|
|
540
560
|
abortSignal?: AbortSignal;
|
|
541
561
|
idleTimeoutMs?: false | number;
|
|
562
|
+
range?: FileServiceOptions['range'];
|
|
542
563
|
} {
|
|
543
|
-
return {
|
|
564
|
+
return {
|
|
565
|
+
abortSignal: serviceOptions?.abortSignal,
|
|
566
|
+
idleTimeoutMs: serviceOptions?.downloadIdleTimeoutMs,
|
|
567
|
+
...(serviceOptions?.range ? { range: serviceOptions.range } : {}),
|
|
568
|
+
};
|
|
544
569
|
}
|
|
545
570
|
|
|
546
571
|
/**
|
|
@@ -648,22 +673,17 @@ export abstract class CoreFileService {
|
|
|
648
673
|
* unchanged; what changed is that the document authorization inspected is the one being served.
|
|
649
674
|
*/
|
|
650
675
|
async getFileStreamByName(filename: string, serviceOptions?: FileServiceOptions): Promise<Readable> {
|
|
676
|
+
assertByteRange(serviceOptions?.range);
|
|
651
677
|
if (!(await this.checkRights(filename, { ...serviceOptions, checkInputType: 'filename' }))) {
|
|
652
678
|
return null;
|
|
653
679
|
}
|
|
654
680
|
const s3FileInfo = await this.findS3FileByName(filename);
|
|
655
681
|
if (s3FileInfo) {
|
|
656
|
-
return this.
|
|
657
|
-
await S3FileHelper.getStream(this.options.s3Service, s3FileInfo._id, this.s3StreamOptions(serviceOptions)),
|
|
658
|
-
serviceOptions,
|
|
659
|
-
);
|
|
682
|
+
return this.openStoreStream('s3', s3FileInfo._id, serviceOptions);
|
|
660
683
|
}
|
|
661
684
|
const fsFileInfo = await this.findFilesystemFileByName(filename);
|
|
662
685
|
if (fsFileInfo) {
|
|
663
|
-
return this.
|
|
664
|
-
FilesystemFileHelper.getStream(this.filesystemDir, fsFileInfo._id),
|
|
665
|
-
serviceOptions,
|
|
666
|
-
);
|
|
686
|
+
return this.openStoreStream('filesystem', fsFileInfo._id, serviceOptions);
|
|
667
687
|
}
|
|
668
688
|
const gridFsInfo = await GridFSHelper.findFileByName(this.files, filename);
|
|
669
689
|
if (!gridFsInfo) {
|
|
@@ -671,7 +691,7 @@ export abstract class CoreFileService {
|
|
|
671
691
|
// itself, asynchronously on the stream, which the controller turns into a 404.
|
|
672
692
|
return this.guardDownloadStream(GridFSHelper.openDownloadStreamByName(this.files, filename), serviceOptions);
|
|
673
693
|
}
|
|
674
|
-
return this.
|
|
694
|
+
return this.openStoreStream('gridfs', gridFsInfo._id, serviceOptions);
|
|
675
695
|
}
|
|
676
696
|
|
|
677
697
|
/**
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
findMetadataByName,
|
|
15
15
|
} from './file-metadata.helper.js';
|
|
16
16
|
import { streamToBuffer } from './s3-file.helper.js';
|
|
17
|
+
import type { ByteRange } from '../../common/helpers/byte-range.helper.js';
|
|
17
18
|
import { newObjectId } from '../../common/persistence/mongo/mongoose-compat.js';
|
|
18
19
|
|
|
19
20
|
/** Metadata collection for files stored on the local filesystem (on a SQL source: the table `filesystem_files`) */
|
|
@@ -172,10 +173,14 @@ export class FilesystemFileHelper {
|
|
|
172
173
|
}
|
|
173
174
|
|
|
174
175
|
/**
|
|
175
|
-
* Get the download stream of a file
|
|
176
|
+
* Get the download stream of a file — with `range`, only those bytes (both inclusive, as `createReadStream()`
|
|
177
|
+
* counts them)
|
|
176
178
|
*/
|
|
177
|
-
static getStream(directory: string, id: string | Types.ObjectId): Readable {
|
|
178
|
-
return createReadStream(
|
|
179
|
+
static getStream(directory: string, id: string | Types.ObjectId, range?: ByteRange): Readable {
|
|
180
|
+
return createReadStream(
|
|
181
|
+
FilesystemFileHelper.filePath(directory, id),
|
|
182
|
+
range ? { end: range.end, start: range.start } : undefined,
|
|
183
|
+
);
|
|
179
184
|
}
|
|
180
185
|
|
|
181
186
|
/**
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { ByteRange } from '../../../common/helpers/byte-range.helper.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Interface for service options in file services
|
|
3
5
|
*/
|
|
@@ -40,5 +42,16 @@ export interface FileServiceOptions {
|
|
|
40
42
|
*/
|
|
41
43
|
metadata?: Record<string, any>;
|
|
42
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Read only these bytes of the file (both inclusive) — `getFileStream()` / `getFileStreamByName()`, every store.
|
|
47
|
+
*
|
|
48
|
+
* What a route needs to answer a `Range` request with `206 Partial Content` (video and audio in Safari and every
|
|
49
|
+
* media player, resumed downloads). The range must lie inside the file (`end` below its `length`): produce it with
|
|
50
|
+
* `resolveDownloadRange(res, file.length)`, which also answers an unsatisfiable range with `416`. A malformed range
|
|
51
|
+
* (negative, not an integer, `start > end`) throws a `RangeError` before any store is asked. The rights check runs
|
|
52
|
+
* first, as for a whole file. Since 12.6.12.
|
|
53
|
+
*/
|
|
54
|
+
range?: ByteRange;
|
|
55
|
+
|
|
43
56
|
roles?: string | string[];
|
|
44
57
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Types } from 'mongoose';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
3
|
|
|
4
|
+
import type { ByteRange } from '../../common/helpers/byte-range.helper.js';
|
|
4
5
|
import { CoreS3Service } from '../../common/services/core-s3.service.js';
|
|
5
6
|
import {
|
|
6
7
|
ensureFilenameIndex,
|
|
@@ -216,12 +217,12 @@ export class S3FileHelper {
|
|
|
216
217
|
}
|
|
217
218
|
|
|
218
219
|
/**
|
|
219
|
-
* Get the download stream of a file
|
|
220
|
+
* Get the download stream of a file — with `range`, only those bytes (both inclusive)
|
|
220
221
|
*/
|
|
221
222
|
static async getStream(
|
|
222
223
|
s3Service: CoreS3Service,
|
|
223
224
|
id: string | Types.ObjectId,
|
|
224
|
-
options?: { abortSignal?: AbortSignal; idleTimeoutMs?: false | number },
|
|
225
|
+
options?: { abortSignal?: AbortSignal; idleTimeoutMs?: false | number; range?: ByteRange },
|
|
225
226
|
): Promise<Readable> {
|
|
226
227
|
const objectId = typeof id === 'string' ? newObjectId(id) : id;
|
|
227
228
|
return (await s3Service.getObject(objectId.toHexString(), options)).body;
|
|
@@ -17,7 +17,7 @@ import { firstValueFrom, isObservable } from 'rxjs';
|
|
|
17
17
|
|
|
18
18
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
19
19
|
import { ROLE_GUARD } from '../auth/guards/role-guard.token.js';
|
|
20
|
-
import { resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
20
|
+
import { isAgentCallContext, resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
21
21
|
import {
|
|
22
22
|
revalidateAllWsConnections,
|
|
23
23
|
revalidateWsConnectionsForTenant,
|
|
@@ -431,6 +431,18 @@ export class CoreTenantGuard implements CanActivate, OnApplicationBootstrap, OnM
|
|
|
431
431
|
|
|
432
432
|
const request = this.getRequest(context);
|
|
433
433
|
if (!request) {
|
|
434
|
+
// An agent function / MCP call without a request is anonymous (nestjs-ai plan §1). "No request" is never
|
|
435
|
+
// permission there: only a public method runs, every other one is refused like an unauthenticated request.
|
|
436
|
+
if (isAgentCallContext(context)) {
|
|
437
|
+
const rolesMetadata = this.reflector.getAll<string[][]>('roles', [context.getHandler(), context.getClass()]);
|
|
438
|
+
const roles = mergeRolesMetadata(rolesMetadata);
|
|
439
|
+
// The method's own roles win over the class's (as `systemCheckRoles` below): a class-level S_EVERYONE does
|
|
440
|
+
// not open a method that asks for S_USER or a tenant role
|
|
441
|
+
const effective = rolesMetadata?.[0]?.some((role) => !!role) ? rolesMetadata[0] : roles;
|
|
442
|
+
if (effective?.some((role) => !!role) && !effective.includes(RoleEnum.S_EVERYONE)) {
|
|
443
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
434
446
|
return true;
|
|
435
447
|
}
|
|
436
448
|
|