Repository navigation
Expand file tree
/
Copy pathroute.ts
More file actions
767 lines (701 loc) · 26.5 KB
/
Copy pathroute.ts
File metadata and controls
767 lines (701 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
import type { Principal } from '@sim/auth/principal'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { fileServeParamsSchema, fileServeQuerySchema } from '@/lib/api/contracts/storage-transfer'
import {
concealCrossTenantResourceError,
InternalUnauthenticatedError,
internalSessionAuth,
} from '@/lib/api/server/routes'
import { AuthType, checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { assertKnownSizeWithinLimit, isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { CopilotFiles, isUsingCloudStorage } from '@/lib/uploads'
import type { StorageContext } from '@/lib/uploads/config'
import { readOrganizationChatAttachment } from '@/lib/uploads/contexts/organization-assistant/application'
import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace'
import { parseWorkspaceFileKey } from '@/lib/uploads/contexts/workspace/file-manager'
import { downloadFile } from '@/lib/uploads/core/storage-service'
import { resolveServableDocBytes } from '@/lib/uploads/documents/compile'
import { DocCompileUserError } from '@/lib/uploads/documents/compile-error'
import { FILE_CACHE_CONTROL, workspaceFileCacheControl } from '@/lib/uploads/server/delivery'
import { resolveServableImageBytes } from '@/lib/uploads/server/image-derivative'
import { resolveStoredFileContext } from '@/lib/uploads/server/metadata'
import { MAX_BUFFERED_TRANSFER_BYTES } from '@/lib/uploads/shared/types'
import { inferContextFromKey, resolveEffectiveMimeType } from '@/lib/uploads/utils/file'
import { internalWorkspaceFileServeAuth } from '@/lib/workspace-files/api'
import { fetchAuthorizedServableWorkspaceFileBuffer } from '@/lib/workspace-files/application/fetch-servable-workspace-file-buffer'
import { finishFileDelivery } from '@/lib/workspace-files/application/finish-file-delivery'
import {
readWorkspaceFileContentByKey,
readWorkspaceFileRecordByKey,
} from '@/lib/workspace-files/application/read-workspace-file-content-by-key'
import { isSimPageSource, SIM_PAGE_CONTENT_TYPE } from '@/lib/workspace-files/page-compile'
import { renderSimPageDocumentWithAssets } from '@/lib/workspace-files/page-document.server'
import { type KnowledgeFileAccess, verifyFileAccess } from '@/app/api/files/authorization'
import {
createConditionalFileResponse,
createFileErrorResponse,
createFileResponse,
FileNotFoundError,
type FileResponse,
findLocalFile,
getContentType,
readLocalFileWithinLimit,
} from '@/app/api/files/utils'
const logger = createLogger('FilesServeAPI')
/**
* Records a failed serve at a level that matches whose fault it is.
*
* A file that is not there is an ordinary answer rather than a server fault: a
* workspace file is rewritten under a new key on every content update, so a reader
* holding the previous key lands here routinely and correctly receives a 404. Each
* handler rethrows into the outer one, so logging those at `error` reports the same
* expected 404 twice and buries the failures that do warrant attention. A file too
* large to serve resident is the same kind of answer — a 413 the caller cannot retry
* its way out of, not something on call needs to look at.
*/
function logServeFailure(message: string, error: unknown): void {
if (error instanceof FileNotFoundError || isPayloadSizeLimitError(error)) {
logger.info(message, { reason: getErrorMessage(error) })
return
}
logger.error(message, error)
}
interface ServeOptions {
/** `raw=1` — bypass all resolution and serve the stored source as-is. */
raw: boolean
/** `preview=1` — the caller renders these bytes rather than saving them. */
preview: boolean
/** `v=<updatedAt>` — the caller asserts the URL addresses one fixed content revision. */
versioned: boolean
/** The request's `If-None-Match`, so a revalidation can be answered 304 instead of re-sending. */
ifNoneMatch: string | null
}
interface ServableBytes {
buffer: Buffer
contentType: string
/**
* These bytes were resolved against OTHER files' current content — a page inlining its images,
* or a document compiled against the files it references — so the same storage key can serve
* different bytes over time while this file's own key and `updatedAt` stay put.
*
* Required, so a branch added to the resolver cannot inherit the cacheable answer by saying
* nothing — the same reason the transfer ceiling is asserted where the branches converge rather
* than inside each one.
*/
dependsOnReferencedFiles: boolean
}
/**
* Resolves the bytes + content type to serve for a stored file.
*
* Document compilation is unconditional: a generated `.docx`/`.xlsx`/`.pptx` is
* stored as source, so the compiled artifact *is* the file, and every download
* routes through here. An image derivative is the opposite — the stored bytes are
* the file — so it is served only when the caller asked to preview, never when it
* asked to download.
*
* Every branch that replaces the source bytes is re-checked against the transfer
* ceiling on the way out. Bounding the read alone does not bound the response: a
* page inlines its images, a generated document resolves to a compiled artifact
* fetched separately, and a derivative is transcoded here — so each can turn a
* source under the ceiling into a response over it. One check where the branches
* converge is what makes that impossible to miss when a branch is added.
*/
async function resolveServableBytes(params: {
buffer: Buffer
filename: string
storageKey: string
workspaceId: string | undefined
options: ServeOptions
ownerKey: string | undefined
signal: AbortSignal | undefined
}): Promise<ServableBytes> {
// `raw` is the stored source, already bounded by the read that produced it, but it
// goes through the same check so the ceiling holds for everything this returns
// rather than for every branch someone remembered to cover.
const resolved: ServableBytes = params.options.raw
? {
buffer: params.buffer,
contentType: getContentType(params.filename),
dependsOnReferencedFiles: false,
}
: await resolveTransformedBytes(params)
assertKnownSizeWithinLimit(
resolved.buffer.length,
MAX_BUFFERED_TRANSFER_BYTES,
'served file response'
)
return resolved
}
async function resolveTransformedBytes(params: {
buffer: Buffer
filename: string
storageKey: string
workspaceId: string | undefined
options: ServeOptions
ownerKey: string | undefined
signal: AbortSignal | undefined
}): Promise<ServableBytes> {
const { buffer, filename, storageKey, workspaceId, options, ownerKey, signal } = params
// The pdf model for pages: a page file stores its SOURCE (frontmatter +
// markdown + sim: fences) and serving compiles it to the rendered document,
// the same way a .pdf key stores its script and serves the binary. Raw
// requests above still return the source; bespoke/legacy HTML falls through
// untouched.
if (filename.toLowerCase().endsWith('.html')) {
const text = buffer.toString('utf8')
if (isSimPageSource(text)) {
const rendered = Buffer.from(
await renderSimPageDocumentWithAssets(text, { workspaceId }),
'utf8'
)
// Inlines the workspace images the page references, read at their CURRENT content.
return {
buffer: rendered,
contentType: 'text/html',
dependsOnReferencedFiles: true,
}
}
}
if (options.preview) {
// Images resolve independently of the document path: a HEIF has no compiled-source
// concept, so it never reaches the doc branch.
const image = await resolveServableImageBytes(buffer, storageKey)
// Transcoded from THIS file's stored bytes, so it lives and dies with the storage key.
if (image) return { ...image, dependsOnReferencedFiles: false }
}
const doc = await resolveServableDocBytes({
rawBuffer: buffer,
fileName: filename,
workspaceId,
ownerKey,
signal,
})
return {
buffer: doc.buffer,
contentType: doc.contentType,
dependsOnReferencedFiles: doc.dependsOnReferencedFiles,
}
}
const STORAGE_KEY_PREFIX_RE = /^\d{13}-[a-z0-9]{7}-/
function stripStorageKeyPrefix(segment: string): string {
return STORAGE_KEY_PREFIX_RE.test(segment) ? segment.replace(STORAGE_KEY_PREFIX_RE, '') : segment
}
function getWorkspaceIdForCompile(key: string): string | undefined {
return parseWorkspaceFileKey(key) ?? undefined
}
const IMMUTABLE_CACHE_CONTROL = FILE_CACHE_CONTROL.immutable
const WORKSPACE_REVALIDATE_CACHE_CONTROL = FILE_CACHE_CONTROL.revalidate
/** For the genuinely-public, pre-auth asset routes (avatars, OG images, workspace logos) — these are
* intentionally shared-cacheable. Passed EXPLICITLY so the default response cache stays `private`. */
const PUBLIC_ASSET_CACHE_CONTROL = FILE_CACHE_CONTROL.publicAsset
/**
* Cache-Control for a served file.
*
* A versioned request (`?v=<updatedAt>`) normally addresses content-immutable bytes: a workspace
* file's content write stores the new bytes under a NEW storage key, so a given key's stored
* source never changes and the browser may cache it indefinitely — re-opens and focus refetches
* then resolve from cache with no round trip.
*
* That promise does NOT hold when the response was resolved against other files' current content
* (`derived-from-referenced-files`): a document compiled against the files it references, or a page
* inlining its images, recompiles per request, so the same key serves different bytes once a
* referenced file changes — while this file's key and `updatedAt`, and therefore the whole URL,
* stay put. Promising immutability there pins a stale render in the browser cache for a year, so
* those responses stay revalidated whether or not the request carried a version.
*/
function resolveServeCacheControl(
versioned: boolean,
context: string | undefined,
dependsOnReferencedFiles: boolean
): string | undefined {
if (context === 'workspace') return workspaceFileCacheControl(versioned, dependsOnReferencedFiles)
if (versioned && !dependsOnReferencedFiles) return IMMUTABLE_CACHE_CONTROL
return dependsOnReferencedFiles ? WORKSPACE_REVALIDATE_CACHE_CONTROL : undefined
}
/**
* The type a rendered workspace file is served under. A rendered Sim page is HTML; every other
* representation is named by the file's extension, as {@link resolveServableDocBytes} names it for
* local and cloud files, rather than by the stored record's type, so a `.csv` recorded as
* `application/vnd.ms-excel` still opens inline.
*/
function renderedWorkspaceContentType(file: WorkspaceFileRecord, renderedType: string): string {
return file.type === SIM_PAGE_CONTENT_TYPE && renderedType === 'text/html'
? renderedType
: resolveEffectiveMimeType(undefined, file.name)
}
/**
* Sends a resolved file, attaching a validator only where the client may actually revalidate.
*
* An immutable response is never revalidated, so digesting its buffer — a pass over up to the
* whole transfer ceiling — would cost the compute and never collect a single 304.
*/
function serveResolvedFile(file: FileResponse, ifNoneMatch: string | null): NextResponse {
return file.cacheControl === IMMUTABLE_CACHE_CONTROL
? createFileResponse(file)
: createConditionalFileResponse(file, ifNoneMatch)
}
export const GET = withRouteHandler(
async (request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) => {
try {
const paramsResult = fileServeParamsSchema.safeParse(await params)
if (!paramsResult.success) {
throw new FileNotFoundError('No file path provided')
}
const { path } = paramsResult.data
if (!path || path.length === 0) {
throw new FileNotFoundError('No file path provided')
}
if (path[0] === 'project') throw new FileNotFoundError('File not found')
logger.info('File serve request:', { path })
const fullPath = path.join('/')
const isS3Path = path[0] === 's3'
const isBlobPath = path[0] === 'blob'
const isGcsPath = path[0] === 'gcs'
const isCloudPath = isS3Path || isBlobPath || isGcsPath
const cloudKey = isCloudPath ? path.slice(1).join('/') : fullPath
/** Chat images are served only through the current private-chat owner boundary. */
if (cloudKey.startsWith('chat-images/')) throw new FileNotFoundError('File not found')
if (cloudKey.startsWith('assistant/')) {
const principal = await internalSessionAuth.authenticate()
const image = await readOrganizationChatAttachment({
principal,
key: cloudKey,
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
signal: request.signal,
})
return createFileResponse({
buffer: image.buffer,
filename: image.name,
contentType: image.contentType,
cacheControl: 'private, no-store',
})
}
const isPublicByKeyPrefix =
cloudKey.startsWith('profile-pictures/') ||
cloudKey.startsWith('og-images/') ||
cloudKey.startsWith('workspace-logos/') ||
cloudKey.startsWith('organization-logos/')
if (isPublicByKeyPrefix) {
const context = inferContextFromKey(cloudKey)
logger.info(`Serving public ${context}:`, { cloudKey })
if (isUsingCloudStorage() || isCloudPath) {
return await handleCloudProxyPublic(cloudKey, context)
}
return await handleLocalFilePublic(fullPath)
}
// Which module owns the object decides which branch below may serve it, and that
// is the row's answer, not the prefix's — a `workspace/` key carries both Files
// module files and mothership chat attachments. Reading the prefix alone here is
// what sent every attachment into the workspace-file use case, which matches on
// `context = 'workspace'` and answered 404 for a file that was present.
const storageContext = await resolveStoredFileContext(cloudKey)
const workspacePrincipal =
storageContext === 'workspace'
? await internalWorkspaceFileServeAuth.authenticate(request, { path })
: undefined
const legacyAuthResult = workspacePrincipal
? undefined
: await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
if (legacyAuthResult && (!legacyAuthResult.success || !legacyAuthResult.userId)) {
logger.warn('Unauthorized file access attempt', {
path,
error: legacyAuthResult.error || 'Missing userId',
})
return NextResponse.json(
{ error: 'Unauthorized' },
{
status: 401,
headers: {
'Cache-Control': FILE_CACHE_CONTROL.noStore,
'X-Content-Type-Options': 'nosniff',
},
}
)
}
const query = fileServeQuerySchema.parse({
raw: request.nextUrl.searchParams.get('raw'),
preview: request.nextUrl.searchParams.get('preview'),
v: request.nextUrl.searchParams.get('v'),
})
const options: ServeOptions = {
raw: query.raw === '1',
preview: query.preview === '1',
versioned: query.v != null,
ifNoneMatch: request.headers.get('if-none-match'),
}
if (workspacePrincipal) {
return await handleWorkspaceFile(cloudKey, workspacePrincipal, options, request)
}
const userId = legacyAuthResult?.userId
if (!userId) throw new Error('Authenticated file serve request is missing a user ID')
/** Only a session identifies a person; an internal token's user id reads as the workspace. */
const knowledgeAccess =
legacyAuthResult?.authType === AuthType.SESSION ? ('user' as const) : undefined
if (isUsingCloudStorage()) {
return await handleCloudProxy(
cloudKey,
userId,
options,
request.signal,
storageContext,
knowledgeAccess,
request.method === 'HEAD'
)
}
return await handleLocalFile(
cloudKey,
userId,
options,
request.signal,
storageContext,
knowledgeAccess,
request.method === 'HEAD'
)
} catch (error) {
if (request.signal.aborted) throw error
if (error instanceof InternalUnauthenticatedError) {
logger.warn('Unauthorized file access attempt', { error: error.message })
return NextResponse.json(
{ error: 'Unauthorized' },
{
status: 401,
headers: {
'Cache-Control': FILE_CACHE_CONTROL.noStore,
'X-Content-Type-Options': 'nosniff',
},
}
)
}
// An in-progress/incomplete doc source fails to compile — this is expected
// mid-generation, not a server fault. Return 409 (not 500) so it isn't an
// alarming error; the client re-fetches once the doc finishes (the serve
// URL is busted on the file's updatedAt).
if (error instanceof DocCompileUserError) {
logger.info('Serve: document still compiling, returning 409', {
message: error.message,
})
return NextResponse.json(
{ error: 'Document is still being generated' },
{
status: 409,
headers: {
'Cache-Control': FILE_CACHE_CONTROL.noStore,
'X-Content-Type-Options': 'nosniff',
},
}
)
}
const orchestrationError = asOrchestrationError(
concealCrossTenantResourceError(error, 'File not found')
)
if (orchestrationError?.code === 'not_found') {
const notFound = new FileNotFoundError('File not found')
logServeFailure('Error serving file:', notFound)
return createFileErrorResponse(notFound)
}
if (orchestrationError) {
if (orchestrationError.code === 'internal')
logServeFailure('Error serving file:', orchestrationError)
return createFileErrorResponse(
orchestrationError,
statusForOrchestrationError(orchestrationError.code)
)
}
logServeFailure('Error serving file:', error)
if (error instanceof FileNotFoundError) {
return createFileErrorResponse(error)
}
return createFileErrorResponse(
error instanceof Error ? error : new Error('Failed to serve file')
)
}
}
)
async function handleWorkspaceFile(
key: string,
principal: Principal,
options: ServeOptions,
request: NextRequest
): Promise<NextResponse> {
const workspaceId = getWorkspaceIdForCompile(key)
if (!workspaceId) throw new FileNotFoundError(`File not found: ${key}`)
const input = { key, assertedWorkspaceId: workspaceId }
if (request.method === 'HEAD') {
await readWorkspaceFileRecordByKey.execute({ principal, input, request })
return new NextResponse(null, {
headers: { 'Cache-Control': FILE_CACHE_CONTROL.noStore, 'X-Content-Type-Options': 'nosniff' },
})
}
let file: WorkspaceFileRecord
let resolved: ServableBytes
if (options.raw) {
const read = await readWorkspaceFileContentByKey.execute({ principal, input, request })
file = read.file
resolved = {
buffer: read.content,
contentType: getContentType(file.name),
dependsOnReferencedFiles: false,
}
} else {
file = (await readWorkspaceFileRecordByKey.execute({ principal, input, request })).file
const rendered = await fetchAuthorizedServableWorkspaceFileBuffer(file, principal, {
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
signal: request.signal,
})
const preview = options.preview ? await resolveServableImageBytes(rendered.buffer, key) : null
resolved = {
buffer: preview?.buffer ?? rendered.buffer,
contentType: preview?.contentType ?? renderedWorkspaceContentType(file, rendered.contentType),
dependsOnReferencedFiles: rendered.dependsOnReferencedFiles,
}
assertKnownSizeWithinLimit(
resolved.buffer.length,
MAX_BUFFERED_TRANSFER_BYTES,
'served file response'
)
await finishFileDelivery({
principal,
authorize: () => readWorkspaceFileRecordByKey.authorize({ principal, input, request }),
receipt: rendered.receipt,
})
}
logger.info('Workspace file served', {
fileId: file.id,
workspaceId,
size: resolved.buffer.length,
})
return serveResolvedFile(
{
buffer: resolved.buffer,
contentType: resolved.contentType,
filename: file.name,
cacheControl: resolveServeCacheControl(
options.versioned,
'workspace',
resolved.dependsOnReferencedFiles
),
},
options.ifNoneMatch
)
}
async function handleLocalFile(
filename: string,
userId: string,
options: ServeOptions,
signal: AbortSignal | undefined,
context: StorageContext,
knowledgeAccess: KnowledgeFileAccess | undefined,
head: boolean
): Promise<NextResponse> {
const ownerKey = `user:${userId}`
try {
const hasAccess = await verifyFileAccess(
filename,
userId,
undefined, // customConfig
context,
{ knowledgeAccess }
)
if (!hasAccess) {
logger.warn('Unauthorized local file access attempt', { userId, filename })
throw new FileNotFoundError(`File not found: ${filename}`)
}
if (head)
return new NextResponse(null, {
headers: {
'Cache-Control': FILE_CACHE_CONTROL.noStore,
'X-Content-Type-Options': 'nosniff',
},
})
const filePath = await findLocalFile(filename)
if (!filePath) {
throw new FileNotFoundError(`File not found: ${filename}`)
}
const rawBuffer = await readLocalFileWithinLimit(
filePath,
MAX_BUFFERED_TRANSFER_BYTES,
'served file'
)
const segment = filename.split('/').pop() || filename
const displayName = stripStorageKeyPrefix(segment)
const workspaceId = getWorkspaceIdForCompile(filename)
const {
buffer: fileBuffer,
contentType,
dependsOnReferencedFiles,
} = await resolveServableBytes({
buffer: rawBuffer,
filename: displayName,
storageKey: filename,
workspaceId,
options,
ownerKey,
signal,
})
logger.info('Local file served', { userId, filename, size: fileBuffer.length })
return serveResolvedFile(
{
buffer: fileBuffer,
contentType,
filename: displayName,
cacheControl: resolveServeCacheControl(
options.versioned,
context,
dependsOnReferencedFiles
),
},
options.ifNoneMatch
)
} catch (error) {
if (signal?.aborted) throw error
logServeFailure('Error reading local file:', error)
throw error
}
}
async function handleCloudProxy(
cloudKey: string,
userId: string,
options: ServeOptions,
signal: AbortSignal | undefined,
context: StorageContext,
knowledgeAccess: KnowledgeFileAccess | undefined,
head: boolean
): Promise<NextResponse> {
const ownerKey = `user:${userId}`
try {
logger.info(`Resolved context: ${context} for key: ${cloudKey}`)
const hasAccess = await verifyFileAccess(
cloudKey,
userId,
undefined, // customConfig
context,
{ knowledgeAccess }
)
if (!hasAccess) {
logger.warn('Unauthorized cloud file access attempt', { userId, key: cloudKey, context })
throw new FileNotFoundError(`File not found: ${cloudKey}`)
}
if (head)
return new NextResponse(null, {
headers: {
'Cache-Control': FILE_CACHE_CONTROL.noStore,
'X-Content-Type-Options': 'nosniff',
},
})
let rawBuffer: Buffer
if (context === 'copilot') {
rawBuffer = await CopilotFiles.downloadCopilotFile(cloudKey, {
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
})
} else {
rawBuffer = await downloadFile({
key: cloudKey,
context,
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
})
}
const segment = cloudKey.split('/').pop() || 'download'
const displayName = stripStorageKeyPrefix(segment)
const workspaceId = getWorkspaceIdForCompile(cloudKey)
const {
buffer: fileBuffer,
contentType,
dependsOnReferencedFiles,
} = await resolveServableBytes({
buffer: rawBuffer,
filename: displayName,
storageKey: cloudKey,
workspaceId,
options,
ownerKey,
signal,
})
logger.info('Cloud file served', {
userId,
key: cloudKey,
size: fileBuffer.length,
context,
})
return serveResolvedFile(
{
buffer: fileBuffer,
contentType,
filename: displayName,
cacheControl: resolveServeCacheControl(
options.versioned,
context,
dependsOnReferencedFiles
),
},
options.ifNoneMatch
)
} catch (error) {
if (signal?.aborted) throw error
logServeFailure('Error downloading from cloud storage:', error)
throw error
}
}
async function handleCloudProxyPublic(
cloudKey: string,
context: StorageContext
): Promise<NextResponse> {
try {
let fileBuffer: Buffer
if (context === 'copilot') {
fileBuffer = await CopilotFiles.downloadCopilotFile(cloudKey, {
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
})
} else {
fileBuffer = await downloadFile({
key: cloudKey,
context,
maxBytes: MAX_BUFFERED_TRANSFER_BYTES,
})
}
const filename = cloudKey.split('/').pop() || 'download'
const contentType = getContentType(filename)
logger.info('Public cloud file served', {
key: cloudKey,
size: fileBuffer.length,
context,
})
return createFileResponse({
buffer: fileBuffer,
contentType,
filename,
cacheControl: PUBLIC_ASSET_CACHE_CONTROL,
})
} catch (error) {
logServeFailure('Error serving public cloud file:', error)
throw error
}
}
async function handleLocalFilePublic(filename: string): Promise<NextResponse> {
try {
const filePath = await findLocalFile(filename)
if (!filePath) {
throw new FileNotFoundError(`File not found: ${filename}`)
}
const fileBuffer = await readLocalFileWithinLimit(
filePath,
MAX_BUFFERED_TRANSFER_BYTES,
'served file'
)
const contentType = getContentType(filename)
logger.info('Public local file served', { filename, size: fileBuffer.length })
return createFileResponse({
buffer: fileBuffer,
contentType,
filename,
cacheControl: PUBLIC_ASSET_CACHE_CONTROL,
})
} catch (error) {
logServeFailure('Error reading public local file:', error)
throw error
}
}