Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🌥️ feat: Add Optional Region-aware S3/CloudFront Storage Keys (#12987)

Danny Avila1bc2692a1564
diff --git a/api/server/routes/files/files.js b/api/server/routes/files/files.js
index e640a0ee16..4176642a71 100644
--- a/api/server/routes/files/files.js
+++ b/api/server/routes/files/files.js
@@ -432,6 +432,8 @@ const DOWNLOAD_METADATA_FIELDS = [
'embedded',
'filename',
'filepath',
+ 'storageKey',
+ 'storageRegion',
'object',
'type',
'usage',
@@ -573,7 +575,7 @@ router.get('/download/:userId/:file_id', fileAccess, async (req, res) => {
return res.status(501).send('Not Implemented');
}
- const fileStream = await getDownloadStream(req, file.filepath);
+ const fileStream = await getDownloadStream(req, file.storageKey || file.filepath);
fileStream.on('error', (streamError) => {
logger.error('[DOWNLOAD ROUTE] Stream error:', streamError);
diff --git a/api/server/routes/files/files.test.js b/api/server/routes/files/files.test.js
index 1998a0375c..5758b77387 100644
--- a/api/server/routes/files/files.test.js
+++ b/api/server/routes/files/files.test.js
@@ -562,6 +562,8 @@ describe('File Routes - Delete with Agent Access', () => {
file_id: userFileId,
filename: 'file.pdf',
filepath: 'uploads/user/file.pdf',
+ storageKey: 'r/us-east-2/uploads/user/file.pdf',
+ storageRegion: 'us-east-2',
bytes: 200,
type: 'application/pdf',
source: FileSources.s3,
@@ -581,6 +583,8 @@ describe('File Routes - Delete with Agent Access', () => {
file_id: userFileId,
filename: 'file.pdf',
filepath: 'uploads/user/file.pdf',
+ storageKey: 'r/us-east-2/uploads/user/file.pdf',
+ storageRegion: 'us-east-2',
source: FileSources.s3,
});
expect(response.body.metadata).not.toHaveProperty('_id');
@@ -650,6 +654,8 @@ describe('File Routes - Delete with Agent Access', () => {
file_id: userFileId,
filename: 'file.pdf',
filepath: 'uploads/user/file.pdf',
+ storageKey: 'r/us-east-2/uploads/user/file.pdf',
+ storageRegion: 'us-east-2',
bytes: 200,
type: 'application/pdf',
source: FileSources.s3,
@@ -674,6 +680,8 @@ describe('File Routes - Delete with Agent Access', () => {
file_id: userFileId,
filename: 'file.pdf',
filepath: 'uploads/user/file.pdf',
+ storageKey: 'r/us-east-2/uploads/user/file.pdf',
+ storageRegion: 'us-east-2',
bytes: 200,
type: 'application/pdf',
source: FileSources.cloudfront,
@@ -690,6 +698,8 @@ describe('File Routes - Delete with Agent Access', () => {
file_id: userFileId,
filename: 'file.pdf',
filepath: 'uploads/user/file.pdf',
+ storageKey: 'r/us-east-2/uploads/user/file.pdf',
+ storageRegion: 'us-east-2',
source: FileSources.cloudfront,
});
expect(metadata).not.toHaveProperty('_id');
@@ -698,7 +708,10 @@ describe('File Routes - Delete with Agent Access', () => {
expect(metadata).not.toHaveProperty('tenantId');
expect(metadata).not.toHaveProperty('text');
expect(getDownloadURL).not.toHaveBeenCalled();
- expect(getDownloadStream).toHaveBeenCalledWith(expect.any(Object), 'uploads/user/file.pdf');
+ expect(getDownloadStream).toHaveBeenCalledWith(
+ expect.any(Object),
+ 'r/us-east-2/uploads/user/file.pdf',
+ );
});
it('redirects to a direct signed download URL when explicitly requested', async () => {
diff --git a/api/server/routes/skills.js b/api/server/routes/skills.js
index 84a303d145..05b8f778e6 100644
--- a/api/server/routes/skills.js
+++ b/api/server/routes/skills.js
@@ -6,6 +6,7 @@ const {
createSkillsHandlers,
createImportHandler,
generateCheckAccess,
+ getStorageMetadata,
} = require('@librechat/api');
const { isValidObjectIdString, logger } = require('@librechat/data-schemas');
const {
@@ -143,6 +144,7 @@ const importHandler = createImportHandler({
.then((filepath) => ({
filepath,
source: storage.source,
+ ...getStorageMetadata({ filepath, source: storage.source }),
}));
},
deleteFile: (req, file) => {
@@ -199,6 +201,7 @@ async function uploadFileHandler(req, res) {
basePath: 'uploads',
tenantId: req.user.tenantId,
});
+ const storageMetadata = getStorageMetadata({ filepath, source: storage.source });
let result;
try {
@@ -208,6 +211,7 @@ async function uploadFileHandler(req, res) {
file_id: fileId,
filename,
filepath,
+ ...storageMetadata,
source: storage.source,
mimeType: file.mimetype || 'application/octet-stream',
bytes: file.size,
diff --git a/api/server/routes/skills.test.js b/api/server/routes/skills.test.js
index 1a0a23c896..2b7166a22d 100644
--- a/api/server/routes/skills.test.js
+++ b/api/server/routes/skills.test.js
@@ -1,5 +1,6 @@
const express = require('express');
const request = require('supertest');
+const JSZip = require('jszip');
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const {
@@ -298,6 +299,57 @@ describe('Skill routes', () => {
});
});
+ describe('POST /api/skills/import', () => {
+ it('persists storage metadata for imported skill files', async () => {
+ const savedFilepath =
+ 'https://cdn.example.com/r/us-east-2/uploads/user123/imported-script.sh';
+ const saveBuffer = jest.fn().mockResolvedValue(savedFilepath);
+ const { getFileStrategy } = require('~/server/utils/getFileStrategy');
+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');
+ getFileStrategy.mockReturnValueOnce('cloudfront');
+ getStrategyFunctions.mockReturnValueOnce({ saveBuffer });
+
+ const zip = new JSZip();
+ zip.file(
+ 'SKILL.md',
+ [
+ '---',
+ 'name: imported-skill',
+ 'description: Imported skill description for route tests.',
+ '---',
+ '# Imported Skill',
+ ].join('\n'),
+ );
+ zip.file('scripts/imported-script.sh', 'echo imported');
+ const buffer = await zip.generateAsync({ type: 'nodebuffer' });
+
+ const res = await request(app).post('/api/skills/import').attach('file', buffer, {
+ filename: 'imported-skill.skill',
+ contentType: 'application/zip',
+ });
+
+ expect(res.status).toBe(201);
+ expect(saveBuffer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: testUsers.owner._id.toString(),
+ basePath: 'uploads',
+ }),
+ );
+
+ const savedFile = await SkillFile.findOne({
+ relativePath: 'scripts/imported-script.sh',
+ }).lean();
+ expect(savedFile).toEqual(
+ expect.objectContaining({
+ filepath: savedFilepath,
+ source: 'cloudfront',
+ storageKey: 'r/us-east-2/uploads/user123/imported-script.sh',
+ storageRegion: 'us-east-2',
+ }),
+ );
+ });
+ });
+
describe('GET /api/skills', () => {
it('returns only skills the caller can access', async () => {
const mine = await createSkillAsOwner({ name: 'mine-skill' });
diff --git a/api/server/services/Files/Code/__tests__/process-traversal.spec.js b/api/server/services/Files/Code/__tests__/process-traversal.spec.js
index 6392e5b8bd..7412c4a28a 100644
--- a/api/server/services/Files/Code/__tests__/process-traversal.spec.js
+++ b/api/server/services/Files/Code/__tests__/process-traversal.spec.js
@@ -32,6 +32,7 @@ jest.mock('@librechat/api', () => {
* mock returns null in lockstep with the null `text` above so
* downstream consumers don't see a phantom format. */
getExtractedTextFormat: jest.fn(() => null),
+ getStorageMetadata: jest.fn(() => ({})),
/* Pass-through `withTimeout`: this suite asserts traversal sanitization,
* not deferred preview timing. */
withTimeout: async (promise) => promise,
diff --git a/api/server/services/Files/Code/process.js b/api/server/services/Files/Code/process.js
index c8d63cc919..016d8815c1 100644
--- a/api/server/services/Files/Code/process.js
+++ b/api/server/services/Files/Code/process.js
@@ -15,6 +15,7 @@ const {
codeServerHttpsAgent,
extractCodeArtifactText,
getExtractedTextFormat,
+ getStorageMetadata,
} = require('@librechat/api');
const {
Tools,
@@ -421,9 +422,16 @@ const processCodeOutput = async ({
const usage = isUpdate ? (claimed.usage ?? 0) + 1 : 1;
const _file = await convertImage(req, buffer, 'high', `${file_id}${fileExt}`);
const filepath = usage > 1 ? `${_file.filepath}?v=${Date.now()}` : _file.filepath;
+ const storageMetadata = getStorageMetadata({
+ filepath: _file.filepath,
+ source: appConfig.fileStrategy,
+ storageKey: _file.storageKey,
+ storageRegion: _file.storageRegion,
+ });
const file = {
..._file,
filepath,
+ ...storageMetadata,
file_id,
messageId: persistedMessageId,
usage,
@@ -494,6 +502,10 @@ const processCodeOutput = async ({
basePath: 'uploads',
tenantId: req.user.tenantId,
});
+ const storageMetadata = getStorageMetadata({
+ filepath,
+ source: appConfig.fileStrategy,
+ });
/* `classifyCodeArtifact` and `extractCodeArtifactText` make
* extension/bare-name decisions on the input string. With the
@@ -520,6 +532,7 @@ const processCodeOutput = async ({
const baseFile = {
file_id,
filepath,
+ ...storageMetadata,
messageId: persistedMessageId,
object: 'file',
filename: safeName,
diff --git a/api/server/services/Files/Code/process.spec.js b/api/server/services/Files/Code/process.spec.js
index 7ca7799bfb..93b76abffd 100644
--- a/api/server/services/Files/Code/process.spec.js
+++ b/api/server/services/Files/Code/process.spec.js
@@ -84,6 +84,7 @@ jest.mock('@librechat/api', () => {
* test overrides via `mockGetExtractedTextFormat.mockReturnValue`
* if a case needs to assert the 'html' value. */
getExtractedTextFormat: (...args) => mockGetExtractedTextFormat(...args),
+ getStorageMetadata: jest.fn(() => ({})),
codeServerHttpAgent: new http.Agent({ keepAlive: false }),
codeServerHttpsAgent: new https.Agent({ keepAlive: false }),
};
diff --git a/api/server/services/Files/images/convert.js b/api/server/services/Files/images/convert.js
index dd0d795448..09d8c0ecc3 100644
--- a/api/server/services/Files/images/convert.js
+++ b/api/server/services/Files/images/convert.js
@@ -2,6 +2,7 @@ const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
const { logger } = require('@librechat/data-schemas');
+const { getStorageMetadata } = require('@librechat/api');
const { getStrategyFunctions } = require('../strategies');
const { resizeImageBuffer } = require('./resize');
@@ -12,7 +13,7 @@ const { resizeImageBuffer } = require('./resize');
* @param {Buffer | Express.Multer.File} file - The file object, containing either a path or a buffer.
* @param {'low' | 'high'} [resolution='high'] - The desired resolution for the output image.
* @param {string} [basename=''] - The basename of the input file, if it is a buffer.
- * @returns {Promise<{filepath: string, bytes: number, width: number, height: number}>} An object containing the path, size, and dimensions of the converted image.
+ * @returns {Promise<{filepath: string, bytes: number, width: number, height: number, storageKey?: string, storageRegion?: string}>} An object containing the path, size, dimensions, and optional storage metadata of the converted image.
* @throws Throws an error if there is an issue during the conversion process.
*/
async function convertImage(req, file, resolution = 'high', basename = '') {
@@ -60,9 +61,13 @@ async function convertImage(req, file, resolution = 'high', basename = '') {
fileName: newFileName,
tenantId: req.user.tenantId,
});
+ const storageMetadata = getStorageMetadata({
+ filepath: savedFilePath,
+ source: appConfig.fileStrategy,
+ });
const bytes = Buffer.byteLength(outputBuffer);
- return { filepath: savedFilePath, bytes, width, height };
+ return { filepath: savedFilePath, ...storageMetadata, bytes, width, height };
} catch (err) {
logger.error(err);
throw err;
diff --git a/api/server/services/Files/process.js b/api/server/services/Files/process.js
index 057d3e531d..69b4a0b382 100644
--- a/api/server/services/Files/process.js
+++ b/api/server/services/Files/process.js
@@ -19,7 +19,12 @@ const {
documentParserMimeTypes,
} = require('librechat-data-provider');
const { logger } = require('@librechat/data-schemas');
-const { sanitizeFilename, parseText, processAudioFile } = require('@librechat/api');
+const {
+ sanitizeFilename,
+ parseText,
+ processAudioFile,
+ getStorageMetadata,
+} = require('@librechat/api');
const {
convertImage,
resizeAndConvert,
@@ -282,6 +287,12 @@ const processFileURL = async ({
if (!filepath) {
throw new Error(`Strategy "${fileStrategy}" did not return a file URL for "${fileName}"`);
}
+ const storageMetadata = getStorageMetadata({
+ filepath,
+ source: fileStrategy,
+ storageKey: typeof savedFile === 'string' ? undefined : savedFile.storageKey,
+ storageRegion: typeof savedFile === 'string' ? undefined : savedFile.storageRegion,
+ });
return await db.createFile(
{
@@ -289,6 +300,7 @@ const processFileURL = async ({
file_id: v4(),
bytes,
filepath,
+ ...storageMetadata,
filename: fileName,
source: fileStrategy,
type,
@@ -323,12 +335,13 @@ const processImageFile = async ({ req, res, metadata, returnFile = false }) => {
const { handleImageUpload } = getStrategyFunctions(source);
const { file_id, temp_file_id, endpoint } = metadata;
- const { filepath, bytes, width, height } = await handleImageUpload({
+ const { filepath, bytes, width, height, storageKey, storageRegion } = await handleImageUpload({
req,
file,
file_id,
endpoint,
});
+ const storageMetadata = getStorageMetadata({ filepath, source, storageKey, storageRegion });
const result = await db.createFile(
{
@@ -337,6 +350,7 @@ const processImageFile = async ({ req, res, metadata, returnFile = false }) => {
temp_file_id,
bytes,
filepath,
+ ...storageMetadata,
filename: file.originalname,
context: FileContext.message_attachment,
source,
@@ -388,12 +402,14 @@ const uploadImageBuffer = async ({ req, context, metadata = {}, resize = true })
buffer,
tenantId: req.user.tenantId,
});
+ const storageMetadata = getStorageMetadata({ filepath, source });
return await db.createFile(
{
user: req.user.id,
file_id,
bytes,
filepath,
+ ...storageMetadata,
filename,
context,
source,
@@ -440,6 +456,8 @@ const processFileUpload = async ({ req, res, metadata }) => {
bytes,
filename,
filepath: _filepath,
+ storageKey: _storageKey,
+ storageRegion: _storageRegion,
embedded,
height,
width,
@@ -465,6 +483,12 @@ const processFileUpload = async ({ req, res, metadata }) => {
}
let filepath = isAssistantUpload ? `${openai.baseURL}/files/${id}` : _filepath;
+ let storageMetadata = getStorageMetadata({
+ filepath,
+ source,
+ storageKey: _storageKey,
+ storageRegion: _storageRegion,
+ });
if (isAssistantUpload && file.mimetype.startsWith('image')) {
const result = await processImageFile({
req,
@@ -473,6 +497,12 @@ const processFileUpload = async ({ req, res, metadata }) => {
returnFile: true,
});
filepath = result.filepath;
+ storageMetadata = getStorageMetadata({
+ filepath,
+ source: result.source,
+ storageKey: result.storageKey,
+ storageRegion: result.storageRegion,
+ });
}
const result = await db.createFile(
@@ -482,6 +512,7 @@ const processFileUpload = async ({ req, res, metadata }) => {
temp_file_id,
bytes,
filepath,
+ ...storageMetadata,
filename: filename ?? sanitizeFilename(file.originalname),
context: isAssistantUpload ? FileContext.assistants : FileContext.message_attachment,
model: isAssistantUpload ? req.body.model : undefined,
@@ -714,7 +745,15 @@ const processAgentFileUpload = async ({ req, res, metadata }) => {
});
}
- let { bytes, filename, filepath: _filepath, height, width } = storageResult;
+ let {
+ bytes,
+ filename,
+ filepath: _filepath,
+ storageKey: _storageKey,
+ storageRegion: _storageRegion,
+ height,
+ width,
+ } = storageResult;
// For RAG files, use embedding result; for others, use storage result
let embedded = storageResult.embedded;
if (tool_resource === EToolResources.file_search) {
@@ -723,6 +762,12 @@ const processAgentFileUpload = async ({ req, res, metadata }) => {
}
let filepath = _filepath;
+ let storageMetadata = getStorageMetadata({
+ filepath,
+ source,
+ storageKey: _storageKey,
+ storageRegion: _storageRegion,
+ });
if (!messageAttachment && tool_resource) {
await db.addAgentResourceFile({
@@ -741,6 +786,12 @@ const processAgentFileUpload = async ({ req, res, metadata }) => {
returnFile: true,
});
filepath = result.filepath;
+ storageMetadata = getStorageMetadata({
+ filepath,
+ source: result.source,
+ storageKey: result.storageKey,
+ storageRegion: result.storageRegion,
+ });
}
const fileInfo = removeNullishValues({
@@ -749,6 +800,7 @@ const processAgentFileUpload = async ({ req, res, metadata }) => {
temp_file_id,
bytes,
filepath,
+ ...storageMetadata,
filename: filename ?? sanitizeFilename(file.originalname),
context: messageAttachment ? FileContext.message_attachment : FileContext.agents,
model: messageAttachment ? undefined : req.body.model,
@@ -995,6 +1047,7 @@ async function saveBase64Image(
buffer: image.buffer,
tenantId: req.user.tenantId,
});
+ const storageMetadata = getStorageMetadata({ filepath, source });
return await db.createFile(
{
type,
@@ -1002,6 +1055,7 @@ async function saveBase64Image(
context,
file_id,
filepath,
+ ...storageMetadata,
filename,
user: req.user.id,
bytes: image.bytes,
diff --git a/api/server/services/Files/process.spec.js b/api/server/services/Files/process.spec.js
index 02d12673e0..2bcea53058 100644
--- a/api/server/services/Files/process.spec.js
+++ b/api/server/services/Files/process.spec.js
@@ -10,6 +10,7 @@ jest.mock('@librechat/api', () => ({
sanitizeFilename: jest.fn((n) => n),
parseText: jest.fn().mockResolvedValue({ text: '', bytes: 0 }),
processAudioFile: jest.fn(),
+ getStorageMetadata: jest.fn(() => ({})),
}));
jest.mock('librechat-data-provider', () => ({
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 963189584c..16c0dbc0a4 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -36,13 +36,25 @@ cache: true
# invalidateOnDelete: false # Create cache invalidation on file delete
# imageSigning: "none" # "none" (public) | "cookies" (signed cookies)
# # When imageSigning: "cookies", API + CloudFront must share a parent domain.
-# # Cookies are path-scoped to private image prefixes and avatar prefixes.
-# # If adding tenantId to a private pre-release CloudFront deployment, re-key
-# # legacy /images and /avatars objects under /t/{tenantId}/ before enabling.
+# # Cookies are path-scoped to inline assets only:
+# # /i/... private uploaded/generated images, user-scoped
+# # /a/... tenant-visible avatars, tenant-scoped when tenantId is present
+# # Downloads, documents, uploads, and code outputs stay outside /i and /a and
+# # use backend-authorized signed URLs instead of signed cookies.
# # API: api.example.com, CloudFront CNAME: cdn.example.com, cookieDomain: ".example.com"
# cookieDomain: ".example.com" # Required for "cookies" - shared parent domain
# cookieExpiry: 1800 # Cookie lifetime in seconds (max: 604800 / 7 days, default: 1800 / 30 min)
# urlExpiry: 3600 # Signed CloudFront download URL lifetime in seconds
+# # Optional multi-region S3/CloudFront layout. Default: false.
+# # When enabled, new object keys include:
+# # /i/r/{storageRegion}/t/{tenantId}/images/{userId}/{file} (private inline images)
+# # /a/r/{storageRegion}/t/{tenantId}/avatars/{userId}/{file} (tenant-visible avatars)
+# # /r/{storageRegion}/t/{tenantId}/{basePath}/{userId}/{file} (non-inline files)
+# # storageRegion defaults to AWS_REGION when omitted, but only affects new keys
+# # when includeRegionInPath is true. Existing files are not moved automatically.
+# # LibreChat does not configure CloudFront origins, Route53, or regional routing.
+# storageRegion: "us-east-2"
+# includeRegionInPath: false
# # Direct-download filename/content-type overrides require the CloudFront cache/origin
# # request policy to forward and cache on response-content-disposition and
# # response-content-type query strings to S3.
diff --git a/packages/api/src/cdn/__tests__/cloudfront-cookies.test.ts b/packages/api/src/cdn/__tests__/cloudfront-cookies.test.ts
index fcfd63d1f8..44f3e0b7b0 100644
--- a/packages/api/src/cdn/__tests__/cloudfront-cookies.test.ts
+++ b/packages/api/src/cdn/__tests__/cloudfront-cookies.test.ts
@@ -148,7 +148,7 @@ describe('setCloudFrontCookies', () => {
expect(result).toBe(true);
expect(mockRes.cookie).toHaveBeenCalledTimes(7);
- expect(mockRes.clearCookie).toHaveBeenCalledTimes(6);
+ expect(mockRes.clearCookie).toHaveBeenCalledTimes(18);
const cookieNames = cookieArgs.map(([name]) => name);
expect(cookieNames).toContain('CloudFront-Policy');
@@ -180,9 +180,9 @@ describe('setCloudFrontCookies', () => {
secure: true,
sameSite: 'none',
domain: '.example.com',
- path: '/images/user123',
+ path: '/i',
});
- expect(cookieArgs[3][2]).toMatchObject({ path: '/avatars' });
+ expect(cookieArgs[3][2]).toMatchObject({ path: '/a' });
});
it('clears legacy image-wide and avatar cookie paths before setting scoped cookies', () => {
@@ -203,15 +203,31 @@ describe('setCloudFrontCookies', () => {
setCloudFrontCookies(mockRes as Response, defaultScope);
- expect(clearedCookies).toHaveLength(6);
+ expect(clearedCookies).toHaveLength(18);
expect(clearedCookies).toContainEqual([
'CloudFront-Policy',
expect.objectContaining({ path: '/images' }),
]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Signature',
+ expect.objectContaining({ path: '/images/user123' }),
+ ]);
expect(clearedCookies).toContainEqual([
'CloudFront-Key-Pair-Id',
expect.objectContaining({ path: '/avatars' }),
]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Signature',
+ expect.objectContaining({ path: '/r' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/i' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Key-Pair-Id',
+ expect.objectContaining({ path: '/a' }),
+ ]);
});
it('clears the previously issued scoped cookie paths before setting new cookies', () => {
@@ -244,6 +260,22 @@ describe('setCloudFrontCookies', () => {
'CloudFront-Signature',
expect.objectContaining({ path: '/t/oldTenant/avatars' }),
]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Key-Pair-Id',
+ expect.objectContaining({ path: '/t/newTenant/images/newUser' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/t/newTenant/avatars' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/i' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Signature',
+ expect.objectContaining({ path: '/a' }),
+ ]);
});
it('stores the issued CloudFront cookie scope for later cleanup', () => {
@@ -268,7 +300,7 @@ describe('setCloudFrontCookies', () => {
expect(name).toBe('LibreChat-CloudFront-Scope');
expect(options).toMatchObject({ domain: '.example.com', path: '/' });
expect(Buffer.from(value, 'base64url').toString('utf8')).toBe(
- JSON.stringify({ userId: 'user123', tenantId: 'tenantA' }),
+ JSON.stringify({ userId: 'user123', tenantId: 'tenantA', storageRegion: null }),
);
});
@@ -300,10 +332,10 @@ describe('setCloudFrontCookies', () => {
}),
);
expect(privatePolicy.Statement).toEqual([
- expect.objectContaining({ Resource: 'https://cdn.example.com/images/user123/*' }),
+ expect.objectContaining({ Resource: 'https://cdn.example.com/i/images/user123/*' }),
]);
expect(avatarPolicy.Statement).toEqual([
- expect.objectContaining({ Resource: 'https://cdn.example.com/avatars/*' }),
+ expect.objectContaining({ Resource: 'https://cdn.example.com/a/avatars/*' }),
]);
});
@@ -333,14 +365,146 @@ describe('setCloudFrontCookies', () => {
expect(result).toBe(true);
expect(privatePolicy.Statement).toEqual([
expect.objectContaining({
- Resource: 'https://cdn.example.com/t/tenantA/images/user123/*',
+ Resource: 'https://cdn.example.com/i/t/tenantA/images/user123/*',
+ }),
+ ]);
+ expect(avatarPolicy.Statement).toEqual([
+ expect.objectContaining({ Resource: 'https://cdn.example.com/a/t/tenantA/avatars/*' }),
+ ]);
+ expect(cookieArgs[0][2]).toMatchObject({ path: '/i' });
+ expect(cookieArgs[3][2]).toMatchObject({ path: '/a' });
+ });
+
+ it('builds disjoint region-wildcard image and avatar policies', () => {
+ mockGetCloudFrontConfig.mockReturnValue({
+ domain: 'https://cdn.example.com',
+ imageSigning: 'cookies',
+ cookieExpiry: 1800,
+ cookieDomain: '.example.com',
+ privateKey: '-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----',
+ keyPairId: 'K123ABC',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+
+ mockGetSignedCookies.mockReturnValue({
+ 'CloudFront-Policy': 'policy-value',
+ 'CloudFront-Signature': 'signature-value',
+ 'CloudFront-Key-Pair-Id': 'K123ABC',
+ });
+
+ const result = setCloudFrontCookies(mockRes as Response, {
+ userId: 'user123',
+ tenantId: 'tenantA',
+ });
+
+ const privatePolicy = JSON.parse(mockGetSignedCookies.mock.calls[0][0].policy);
+ const avatarPolicy = JSON.parse(mockGetSignedCookies.mock.calls[1][0].policy);
+ expect(result).toBe(true);
+ expect(mockGetSignedCookies).toHaveBeenCalledTimes(2);
+ expect(mockRes.cookie).toHaveBeenCalledTimes(7);
+ expect(privatePolicy.Statement).toEqual([
+ expect.objectContaining({
+ Resource: 'https://cdn.example.com/i/r/*/t/tenantA/images/user123/*',
}),
]);
expect(avatarPolicy.Statement).toEqual([
- expect.objectContaining({ Resource: 'https://cdn.example.com/t/tenantA/avatars/*' }),
+ expect.objectContaining({
+ Resource: 'https://cdn.example.com/a/r/*/t/tenantA/avatars/*',
+ }),
+ ]);
+ expect(cookieArgs[0][2]).toMatchObject({ path: '/i' });
+ expect(cookieArgs[3][2]).toMatchObject({ path: '/a' });
+
+ const [, scopeValue] = cookieArgs[cookieArgs.length - 1];
+ expect(Buffer.from(scopeValue, 'base64url').toString('utf8')).toBe(
+ JSON.stringify({ userId: 'user123', tenantId: 'tenantA', storageRegion: 'us-east-2' }),
+ );
+ });
+
+ it('does not require a concrete storageRegion for wildcard region policies', () => {
+ const originalRegion = process.env.AWS_REGION;
+ delete process.env.AWS_REGION;
+ mockGetCloudFrontConfig.mockReturnValue({
+ domain: 'https://cdn.example.com',
+ imageSigning: 'cookies',
+ cookieExpiry: 1800,
+ cookieDomain: '.example.com',
+ privateKey: '-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----',
+ keyPairId: 'K123ABC',
+ includeRegionInPath: true,
+ });
+
+ mockGetSignedCookies.mockReturnValue({
+ 'CloudFront-Policy': 'policy-value',
+ 'CloudFront-Signature': 'signature-value',
+ 'CloudFront-Key-Pair-Id': 'K123ABC',
+ });
+
+ try {
+ const result = setCloudFrontCookies(mockRes as Response, {
+ userId: 'user123',
+ tenantId: 'tenantA',
+ });
+
+ const privatePolicy = JSON.parse(mockGetSignedCookies.mock.calls[0][0].policy);
+ const avatarPolicy = JSON.parse(mockGetSignedCookies.mock.calls[1][0].policy);
+ const [, scopeValue] = cookieArgs[cookieArgs.length - 1];
+ expect(result).toBe(true);
+ expect(privatePolicy.Statement).toEqual([
+ expect.objectContaining({
+ Resource: 'https://cdn.example.com/i/r/*/t/tenantA/images/user123/*',
+ }),
+ ]);
+ expect(avatarPolicy.Statement).toEqual([
+ expect.objectContaining({
+ Resource: 'https://cdn.example.com/a/r/*/t/tenantA/avatars/*',
+ }),
+ ]);
+ expect(Buffer.from(scopeValue, 'base64url').toString('utf8')).toBe(
+ JSON.stringify({ userId: 'user123', tenantId: 'tenantA', storageRegion: null }),
+ );
+ } finally {
+ if (originalRegion == null) {
+ delete process.env.AWS_REGION;
+ } else {
+ process.env.AWS_REGION = originalRegion;
+ }
+ }
+ });
+
+ it('builds a user-bounded region-wildcard policy for non-tenant installs', () => {
+ mockGetCloudFrontConfig.mockReturnValue({
+ domain: 'https://cdn.example.com',
+ imageSigning: 'cookies',
+ cookieExpiry: 1800,
+ cookieDomain: '.example.com',
+ privateKey: '-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----',
+ keyPairId: 'K123ABC',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+
+ mockGetSignedCookies.mockReturnValue({
+ 'CloudFront-Policy': 'policy-value',
+ 'CloudFront-Signature': 'signature-value',
+ 'CloudFront-Key-Pair-Id': 'K123ABC',
+ });
+
+ const result = setCloudFrontCookies(mockRes as Response, { userId: 'user123' });
+
+ const privatePolicy = JSON.parse(mockGetSignedCookies.mock.calls[0][0].policy);
+ const avatarPolicy = JSON.parse(mockGetSignedCookies.mock.calls[1][0].policy);
+ expect(result).toBe(true);
+ expect(mockGetSignedCookies).toHaveBeenCalledTimes(2);
+ expect(privatePolicy.Statement).toEqual([
+ expect.objectContaining({ Resource: 'https://cdn.example.com/i/r/*/images/user123/*' }),
+ ]);
+ expect(avatarPolicy.Statement).toEqual([
+ expect.objectContaining({ Resource: 'https://cdn.example.com/a/r/*/avatars/*' }),
]);
- expect(cookieArgs[0][2]).toMatchObject({ path: '/t/tenantA/images/user123' });
- expect(cookieArgs[3][2]).toMatchObject({ path: '/t/tenantA/avatars' });
+ expect(cookieArgs[0][2]).toMatchObject({ path: '/i' });
+ expect(cookieArgs[3][2]).toMatchObject({ path: '/a' });
});
it('handles multiple trailing slashes in domain', () => {
@@ -363,7 +527,7 @@ describe('setCloudFrontCookies', () => {
expect(mockGetSignedCookies).toHaveBeenCalledWith(
expect.objectContaining({
- policy: expect.stringContaining('https://cdn.example.com/images/user123/*'),
+ policy: expect.stringContaining('https://cdn.example.com/i/images/user123/*'),
}),
);
});
@@ -537,7 +701,7 @@ describe('clearCloudFrontCookies', () => {
clearCloudFrontCookies(mockRes as Response);
- expect(mockRes.clearCookie).toHaveBeenCalledTimes(10);
+ expect(mockRes.clearCookie).toHaveBeenCalledTimes(19);
});
it('does nothing when cookieDomain is missing', () => {
@@ -562,7 +726,7 @@ describe('clearCloudFrontCookies', () => {
clearCloudFrontCookies(mockRes as Response);
- expect(mockRes.clearCookie).toHaveBeenCalledTimes(10);
+ expect(mockRes.clearCookie).toHaveBeenCalledTimes(19);
const legacyPathOptions = {
domain: '.example.com',
@@ -584,6 +748,10 @@ describe('clearCloudFrontCookies', () => {
expect(clearedCookies).toContainEqual(['CloudFront-Policy', rootPathOptions]);
expect(clearedCookies).toContainEqual(['CloudFront-Signature', rootPathOptions]);
expect(clearedCookies).toContainEqual(['CloudFront-Key-Pair-Id', rootPathOptions]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/r' }),
+ ]);
});
it('clears tenant-scoped cookies', () => {
@@ -597,17 +765,35 @@ describe('clearCloudFrontCookies', () => {
clearCloudFrontCookies(mockRes as Response, { userId: 'user123', tenantId: 'tenantA' });
- expect(mockRes.clearCookie).toHaveBeenCalledTimes(19);
+ expect(mockRes.clearCookie).toHaveBeenCalledTimes(28);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ {
+ domain: '.example.com',
+ path: '/i',
+ httpOnly: true,
+ secure: true,
+ sameSite: 'none',
+ },
+ ]);
expect(clearedCookies).toContainEqual([
'CloudFront-Policy',
{
domain: '.example.com',
- path: '/t/tenantA/images/user123',
+ path: '/a',
httpOnly: true,
secure: true,
sameSite: 'none',
},
]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/t/tenantA/images/user123' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Signature',
+ expect.objectContaining({ path: '/t/tenantA/avatars' }),
+ ]);
expect(clearedCookies).toContainEqual([
'LibreChat-CloudFront-Scope',
{
@@ -620,6 +806,41 @@ describe('clearCloudFrontCookies', () => {
]);
});
+ it('clears region-mode scoped cookies without requiring scope.storageRegion', () => {
+ mockGetCloudFrontConfig.mockReturnValue({
+ domain: 'https://cdn.example.com',
+ imageSigning: 'cookies',
+ cookieDomain: '.example.com',
+ privateKey: 'test-key',
+ keyPairId: 'K123',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+
+ clearCloudFrontCookies(mockRes as Response, { userId: 'user123', tenantId: 'tenantA' });
+
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/t/tenantA/images/user123' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Signature',
+ expect.objectContaining({ path: '/t/tenantA/avatars' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/i' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'CloudFront-Policy',
+ expect.objectContaining({ path: '/a' }),
+ ]);
+ expect(clearedCookies).toContainEqual([
+ 'LibreChat-CloudFront-Scope',
+ expect.objectContaining({ path: '/' }),
+ ]);
+ });
+
it('logs warning and does not throw when clearing fails', () => {
mockGetCloudFrontConfig.mockReturnValue({
domain: 'https://cdn.example.com',
diff --git a/packages/api/src/cdn/__tests__/cloudfront.test.ts b/packages/api/src/cdn/__tests__/cloudfront.test.ts
index bcdf202fe6..3e02d8738a 100644
--- a/packages/api/src/cdn/__tests__/cloudfront.test.ts
+++ b/packages/api/src/cdn/__tests__/cloudfront.test.ts
@@ -21,6 +21,7 @@ function makeConfig(overrides: Partial<RequiredCloudFrontConfig> = {}): Required
imageSigning: 'none',
urlExpiry: 3600,
cookieExpiry: 1800,
+ includeRegionInPath: false,
...overrides,
};
}
diff --git a/packages/api/src/cdn/cloudfront-cookies.ts b/packages/api/src/cdn/cloudfront-cookies.ts
index b62b5533fd..0c905df537 100644
--- a/packages/api/src/cdn/cloudfront-cookies.ts
+++ b/packages/api/src/cdn/cloudfront-cookies.ts
@@ -3,7 +3,9 @@ import { logger } from '@librechat/data-schemas';
import type { Response } from 'express';
+import { INLINE_AVATAR_PATH_PREFIX, INLINE_IMAGE_PATH_PREFIX } from '~/storage/constants';
import { assertPathSegment } from '~/storage/validation';
+import { s3Config } from '~/storage/s3/s3Config';
import { getCloudFrontConfig } from './cloudfront';
const DEFAULT_COOKIE_EXPIRY = 1800;
@@ -20,6 +22,7 @@ const unsafePolicySegmentPattern = /[?*[\]\s]/;
export interface CloudFrontCookieScope {
userId?: string | null;
tenantId?: string | null;
+ storageRegion?: string | null;
}
type CookieOptions = {
@@ -39,27 +42,67 @@ function assertPolicyPathSegment(label: string, value: string | null | undefined
function getPolicyScopes(
domain: string,
- { userId, tenantId }: CloudFrontCookieScope,
+ { userId, tenantId, storageRegion }: CloudFrontCookieScope,
+ includeRegionInPath = false,
): Array<{ resource: string; path: string }> {
if (!userId) {
throw new Error('[CloudFront cookies] userId is required for private image access.');
}
const safeUserId = assertPolicyPathSegment('userId', userId);
+ if (includeRegionInPath) {
+ if (storageRegion) {
+ assertPolicyPathSegment('storageRegion', storageRegion);
+ }
+ if (tenantId) {
+ const safeTenantId = assertPolicyPathSegment('tenantId', tenantId);
+ return [
+ {
+ resource: `${domain}/${INLINE_IMAGE_PATH_PREFIX}/r/*/t/${safeTenantId}/images/${safeUserId}/*`,
+ path: `/${INLINE_IMAGE_PATH_PREFIX}`,
+ },
+ {
+ resource: `${domain}/${INLINE_AVATAR_PATH_PREFIX}/r/*/t/${safeTenantId}/avatars/*`,
+ path: `/${INLINE_AVATAR_PATH_PREFIX}`,
+ },
+ ];
+ }
+
+ return [
+ {
+ resource: `${domain}/${INLINE_IMAGE_PATH_PREFIX}/r/*/images/${safeUserId}/*`,
+ path: `/${INLINE_IMAGE_PATH_PREFIX}`,
+ },
+ {
+ resource: `${domain}/${INLINE_AVATAR_PATH_PREFIX}/r/*/avatars/*`,
+ path: `/${INLINE_AVATAR_PATH_PREFIX}`,
+ },
+ ];
+ }
+
if (tenantId) {
const safeTenantId = assertPolicyPathSegment('tenantId', tenantId);
return [
{
- resource: `${domain}/t/${safeTenantId}/images/${safeUserId}/*`,
- path: `/t/${safeTenantId}/images/${safeUserId}`,
+ resource: `${domain}/${INLINE_IMAGE_PATH_PREFIX}/t/${safeTenantId}/images/${safeUserId}/*`,
+ path: `/${INLINE_IMAGE_PATH_PREFIX}`,
+ },
+ {
+ resource: `${domain}/${INLINE_AVATAR_PATH_PREFIX}/t/${safeTenantId}/avatars/*`,
+ path: `/${INLINE_AVATAR_PATH_PREFIX}`,
},
- { resource: `${domain}/t/${safeTenantId}/avatars/*`, path: `/t/${safeTenantId}/avatars` },
];
}
return [
- { resource: `${domain}/images/${safeUserId}/*`, path: `/images/${safeUserId}` },
- { resource: `${domain}/avatars/*`, path: '/avatars' },
+ {
+ resource: `${domain}/${INLINE_IMAGE_PATH_PREFIX}/images/${safeUserId}/*`,
+ path: `/${INLINE_IMAGE_PATH_PREFIX}`,
+ },
+ {
+ resource: `${domain}/${INLINE_AVATAR_PATH_PREFIX}/avatars/*`,
+ path: `/${INLINE_AVATAR_PATH_PREFIX}`,
+ },
];
}
@@ -71,23 +114,28 @@ function getScopeCookiePaths(
return [];
}
+ if (scope.storageRegion) {
+ assertPolicyPathSegment('storageRegion', scope.storageRegion);
+ }
const safeUserId = assertPolicyPathSegment('userId', scope.userId);
- if (scope.tenantId) {
- const safeTenantId = assertPolicyPathSegment('tenantId', scope.tenantId);
- const paths = [`/t/${safeTenantId}/images/${safeUserId}`, `/t/${safeTenantId}/avatars`];
- if (includeTenantRoot) {
- paths.push(`/t/${safeTenantId}`);
- }
- return paths;
+ const safeTenantId = scope.tenantId ? assertPolicyPathSegment('tenantId', scope.tenantId) : null;
+ const paths = [`/${INLINE_IMAGE_PATH_PREFIX}`, `/${INLINE_AVATAR_PATH_PREFIX}`];
+ if (safeTenantId) {
+ paths.push(`/t/${safeTenantId}/images/${safeUserId}`, `/t/${safeTenantId}/avatars`);
+ } else {
+ paths.push(`/images/${safeUserId}`, '/avatars');
}
-
- return [`/images/${safeUserId}`, '/avatars'];
+ if (safeTenantId && includeTenantRoot) {
+ paths.push(`/t/${safeTenantId}`);
+ }
+ return paths;
}
function encodeCloudFrontCookieScope(scope: CloudFrontCookieScope): string {
const payload = {
userId: scope.userId ?? null,
tenantId: scope.tenantId ?? null,
+ storageRegion: scope.storageRegion ?? null,
};
return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
}
@@ -103,6 +151,7 @@ export function parseCloudFrontCookieScope(
const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as {
userId?: unknown;
tenantId?: unknown;
+ storageRegion?: unknown;
};
const scope: CloudFrontCookieScope = {};
if (typeof parsed.userId === 'string') {
@@ -111,6 +160,9 @@ export function parseCloudFrontCookieScope(
if (typeof parsed.tenantId === 'string') {
scope.tenantId = assertPolicyPathSegment('tenantId', parsed.tenantId);
}
+ if (typeof parsed.storageRegion === 'string') {
+ scope.storageRegion = assertPolicyPathSegment('storageRegion', parsed.storageRegion);
+ }
return scope.userId ? scope : null;
} catch {
return null;
@@ -146,9 +198,18 @@ export function clearCloudFrontCookies(res: Response, scope: CloudFrontCookieSco
secure: true,
sameSite: 'none' as const,
};
- const paths = new Set(['/images', '/avatars', '/']);
- if (scope.userId) {
- for (const path of getScopeCookiePaths(scope, { includeTenantRoot: true })) {
+ const paths = new Set(['/images', '/avatars', '/r', '/i', '/a', '/']);
+ const clearScope =
+ config.includeRegionInPath && scope.userId && !scope.storageRegion
+ ? {
+ ...scope,
+ storageRegion: config.storageRegion ?? s3Config.AWS_REGION ?? process.env.AWS_REGION,
+ }
+ : scope;
+ if (clearScope.userId) {
+ for (const path of getScopeCookiePaths(clearScope, {
+ includeTenantRoot: true,
+ })) {
paths.add(path);
}
}
@@ -199,14 +260,29 @@ export function setCloudFrontCookies(
const expiresAtEpoch = Math.floor(expiresAtMs / 1000);
const cleanDomain = config.domain.replace(/\/+$/, '');
- const policyScopes = getPolicyScopes(cleanDomain, scope);
- // CloudFront custom-policy cookies are scoped to one resource, so issue
- // separate path-specific cookie sets for private files and shared avatars.
- const signedCookieSets = policyScopes.map(({ resource, path }) => {
+ const includeRegionInPath = config.includeRegionInPath ?? false;
+ const configuredStorageRegion =
+ scope.storageRegion ?? config.storageRegion ?? s3Config.AWS_REGION ?? process.env.AWS_REGION;
+ const scopedStorageRegion = includeRegionInPath ? configuredStorageRegion : scope.storageRegion;
+ const effectiveScope = {
+ ...scope,
+ ...(scopedStorageRegion ? { storageRegion: scopedStorageRegion } : {}),
+ };
+ const policyScopes = getPolicyScopes(cleanDomain, effectiveScope, includeRegionInPath);
+ const resourcesByPath = new Map<string, string[]>();
+ for (const { resource, path } of policyScopes) {
+ resourcesByPath.set(path, [...(resourcesByPath.get(path) ?? []), resource]);
+ }
+
+ const signedCookieSets = Array.from(resourcesByPath, ([path, resources]) => {
+ if (resources.length > 1) {
+ throw new Error('[CloudFront cookies] Multiple resources cannot share a cookie path.');
+ }
+
const policy = JSON.stringify({
Statement: [
{
- Resource: resource,
+ Resource: resources[0],
Condition: {
DateLessThan: {
'AWS:EpochTime': expiresAtEpoch,
@@ -232,12 +308,15 @@ export function setCloudFrontCookies(
sameSite: 'none' as const,
domain: config.cookieDomain,
};
- const stalePaths = new Set(['/images', '/avatars']);
+ const stalePaths = new Set(['/images', '/avatars', '/r', '/i', '/a']);
if (previousScope?.userId) {
for (const path of getScopeCookiePaths(previousScope)) {
stalePaths.add(path);
}
}
+ for (const path of getScopeCookiePaths(effectiveScope)) {
+ stalePaths.add(path);
+ }
for (const { cookies } of signedCookieSets) {
for (const key of REQUIRED_CF_COOKIES) {
@@ -257,7 +336,7 @@ export function setCloudFrontCookies(
res.cookie(key, cookies[key], cookieOptions);
}
}
- res.cookie(CLOUDFRONT_SCOPE_COOKIE, encodeCloudFrontCookieScope(scope), {
+ res.cookie(CLOUDFRONT_SCOPE_COOKIE, encodeCloudFrontCookieScope(effectiveScope), {
...baseCookieOptions,
path: '/',
});
diff --git a/packages/api/src/skills/handlers.ts b/packages/api/src/skills/handlers.ts
index 81982186aa..41836b66cd 100644
--- a/packages/api/src/skills/handlers.ts
+++ b/packages/api/src/skills/handlers.ts
@@ -203,6 +203,8 @@ function serializeSkillFile(file: ISkillFile & { _id: Types.ObjectId }): TSkillF
file_id: file.file_id,
filename: file.filename,
filepath: file.filepath,
+ storageKey: file.storageKey,
+ storageRegion: file.storageRegion,
source: file.source as TSkillFile['source'],
mimeType: file.mimeType,
bytes: file.bytes,
@@ -544,6 +546,8 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
if (deleteBlob) {
deleteBlob(req, {
filepath: file.filepath,
+ storageKey: file.storageKey,
+ storageRegion: file.storageRegion,
user: file.author?.toString?.(),
tenantId: file.tenantId?.toString?.(),
}).catch((e) =>
@@ -633,7 +637,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
'Content-Disposition',
`${isImageMime ? 'inline' : 'attachment'}; filename="${safeName}"`,
);
- const stream = await strategy.getDownloadStream(req, file.filepath);
+ const stream = await strategy.getDownloadStream(req, file.storageKey || file.filepath);
stream.on('error', (err: Error) => {
logger.error('[downloadFile] Stream error:', err);
if (!res.headersSent) {
@@ -667,7 +671,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
// destroy (binary) or continue reading (text) in the same iteration.
// N.B. breaking out of `for await...of` destroys the stream via
// iterator.return(), so we must NOT use break + a second loop.
- const stream = await strategy.getDownloadStream(req, file.filepath);
+ const stream = await strategy.getDownloadStream(req, file.storageKey || file.filepath);
const chunks: Buffer[] = [];
let totalBytes = 0;
let binaryChecked = false;
@@ -749,6 +753,8 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
if (deleteBlob) {
deleteBlob(req, {
filepath: file.filepath,
+ storageKey: file.storageKey,
+ storageRegion: file.storageRegion,
user: file.author?.toString?.(),
tenantId: file.tenantId?.toString?.(),
}).catch((e) => logger.error('[deleteFile] Storage cleanup failed:', e));
diff --git a/packages/api/src/skills/import.ts b/packages/api/src/skills/import.ts
index af6e0e3466..6a2b135ebc 100644
--- a/packages/api/src/skills/import.ts
+++ b/packages/api/src/skills/import.ts
@@ -170,7 +170,7 @@ export interface ImportSkillDeps {
isImage?: boolean;
tenantId?: string;
},
- ) => Promise<{ filepath: string; source: string }>;
+ ) => Promise<{ filepath: string; source: string; storageKey?: string; storageRegion?: string }>;
deleteFile?: (
req: Request,
file: { filepath: string; source: string; [key: string]: unknown },
@@ -519,7 +519,7 @@ async function handleZip(
const mimeType = guessMimeType(filename);
// Save to file storage (strategy-aware)
- const { filepath, source } = await deps.saveBuffer(req, {
+ const { filepath, source, storageKey, storageRegion } = await deps.saveBuffer(req, {
userId,
buffer: fileBuffer,
fileName: storageFileName,
@@ -537,6 +537,8 @@ async function handleZip(
file_id: fileId,
filename,
filepath,
+ storageKey,
+ storageRegion,
source,
mimeType,
bytes: fileBuffer.length,
@@ -547,7 +549,14 @@ async function handleZip(
} catch (dbError) {
if (deps.deleteFile) {
await deps
- .deleteFile(req, { filepath, source, user: authorId, tenantId })
+ .deleteFile(req, {
+ filepath,
+ storageKey,
+ storageRegion,
+ source,
+ user: authorId,
+ tenantId,
+ })
.catch((e) =>
logger.error(`[importSkill] Orphan cleanup failed for ${relativePath}:`, e),
);
diff --git a/packages/api/src/storage/__tests__/metadata.test.ts b/packages/api/src/storage/__tests__/metadata.test.ts
new file mode 100644
index 0000000000..4fae4dd3f4
--- /dev/null
+++ b/packages/api/src/storage/__tests__/metadata.test.ts
@@ -0,0 +1,83 @@
+import { logger } from '@librechat/data-schemas';
+import { FileSources } from 'librechat-data-provider';
+import { getStorageMetadata } from '../metadata';
+
+// getStorageMetadata uses real S3 key extraction/parsing from crud.ts; no S3 calls are made here.
+jest.mock('@librechat/data-schemas', () => ({
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ },
+}));
+
+describe('getStorageMetadata', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns empty metadata for non-cloud storage sources', () => {
+ expect(
+ getStorageMetadata({
+ source: FileSources.local,
+ filepath: '/images/user123/file.png',
+ }),
+ ).toEqual({});
+ });
+
+ it('returns empty metadata when cloud files have no filepath or storageKey', () => {
+ expect(getStorageMetadata({ source: FileSources.s3 })).toEqual({});
+ expect(getStorageMetadata({ source: FileSources.cloudfront, filepath: '' })).toEqual({});
+ });
+
+ it('uses an explicit storageKey and parses its embedded region', () => {
+ expect(
+ getStorageMetadata({
+ source: FileSources.s3,
+ storageKey: 'i/r/us-east-2/t/tenantA/images/user123/photo.png',
+ }),
+ ).toEqual({
+ storageKey: 'i/r/us-east-2/t/tenantA/images/user123/photo.png',
+ storageRegion: 'us-east-2',
+ });
+ });
+
+ it('extracts storage metadata from CloudFront filepaths', () => {
+ expect(
+ getStorageMetadata({
+ source: FileSources.cloudfront,
+ filepath:
+ 'https://cdn.example.com/a/r/eu-central-1/t/tenantA/avatars/user123/avatar.png?Policy=abc',
+ }),
+ ).toEqual({
+ storageKey: 'a/r/eu-central-1/t/tenantA/avatars/user123/avatar.png',
+ storageRegion: 'eu-central-1',
+ });
+ });
+
+ it('returns empty metadata for malformed cloud filepaths', () => {
+ expect(
+ getStorageMetadata({
+ source: FileSources.s3,
+ filepath: 'https://cdn.example.com/not-enough',
+ }),
+ ).toEqual({});
+ });
+
+ it('keeps explicit storageRegion on mismatch and logs the mismatch', () => {
+ expect(
+ getStorageMetadata({
+ source: FileSources.s3,
+ storageKey: 'r/us-east-2/uploads/user123/report.pdf',
+ storageRegion: 'eu-central-1',
+ }),
+ ).toEqual({
+ storageKey: 'r/us-east-2/uploads/user123/report.pdf',
+ storageRegion: 'eu-central-1',
+ });
+ expect(logger.warn).toHaveBeenCalledWith(
+ '[getStorageMetadata] storageRegion "eu-central-1" does not match key region "us-east-2".',
+ );
+ });
+});
diff --git a/packages/api/src/storage/cloudfront/__tests__/crud.test.ts b/packages/api/src/storage/cloudfront/__tests__/crud.test.ts
index 163b191751..d3bf5bf975 100644
--- a/packages/api/src/storage/cloudfront/__tests__/crud.test.ts
+++ b/packages/api/src/storage/cloudfront/__tests__/crud.test.ts
@@ -4,13 +4,14 @@ import type { CloudFrontFullConfig } from '~/cdn/cloudfront';
import type { ServerRequest } from '~/types';
const mockGetCloudFrontConfig = jest.fn<CloudFrontFullConfig | null, []>();
-const mockGetS3Key = jest.fn<string, [string, string, string, string?]>();
+const mockGetS3Key = jest.fn();
const mockSaveBufferToS3 = jest.fn();
const mockSaveURLToS3WithMetadata = jest.fn();
const mockUploadFileToS3 = jest.fn();
const mockDeleteFileFromS3 = jest.fn();
const mockGetS3FileStream = jest.fn();
const mockExtractKeyFromS3Url = jest.fn<string, [string]>();
+const mockResolveStoredS3Key = jest.fn<string, [TFile]>();
const mockCloudFrontSend = jest.fn();
const mockGetSignedUrl = jest.fn<string, [object]>();
const mockLogger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() };
@@ -27,6 +28,7 @@ jest.mock('~/storage/s3/crud', () => ({
deleteFileFromS3: mockDeleteFileFromS3,
getS3FileStream: mockGetS3FileStream,
extractKeyFromS3Url: mockExtractKeyFromS3Url,
+ resolveStoredS3Key: mockResolveStoredS3Key,
}));
jest.mock('@aws-sdk/cloudfront-signer', () => ({
@@ -51,6 +53,7 @@ function makeConfig(overrides: Partial<CloudFrontFullConfig> = {}): CloudFrontFu
imageSigning: 'none',
urlExpiry: 3600,
cookieExpiry: 1800,
+ includeRegionInPath: false,
privateKey: null,
keyPairId: null,
...overrides,
@@ -60,10 +63,22 @@ function makeConfig(overrides: Partial<CloudFrontFullConfig> = {}): CloudFrontFu
describe('CloudFront CRUD', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockGetS3Key.mockImplementation((basePath, userId, fileName, tenantId) =>
- tenantId
- ? `t/${tenantId}/${basePath}/${userId}/${fileName}`
- : `${basePath}/${userId}/${fileName}`,
+ mockGetS3Key.mockImplementation(
+ ({ basePath, userId, fileName, tenantId, storageRegion, useInlinePath }) => {
+ let inlinePrefix = null;
+ if (useInlinePath) {
+ inlinePrefix = basePath === 'avatars' ? 'a' : 'i';
+ }
+ const prefix = inlinePrefix ? `${inlinePrefix}/` : '';
+ if (storageRegion) {
+ return tenantId
+ ? `${prefix}r/${storageRegion}/t/${tenantId}/${basePath}/${userId}/${fileName}`
+ : `${prefix}r/${storageRegion}/${basePath}/${userId}/${fileName}`;
+ }
+ return tenantId
+ ? `${prefix}t/${tenantId}/${basePath}/${userId}/${fileName}`
+ : `${prefix}${basePath}/${userId}/${fileName}`;
+ },
);
mockGetCloudFrontConfig.mockReturnValue(makeConfig());
});
@@ -72,7 +87,7 @@ describe('CloudFront CRUD', () => {
it('returns plain CloudFront URL when sign is false (default)', async () => {
const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
const url = await getCloudFrontURL({ userId: 'user1', fileName: 'photo.webp' });
- expect(url).toBe('https://d123.cloudfront.net/images/user1/photo.webp');
+ expect(url).toBe('https://d123.cloudfront.net/i/images/user1/photo.webp');
expect(mockGetSignedUrl).not.toHaveBeenCalled();
});
@@ -95,7 +110,72 @@ describe('CloudFront CRUD', () => {
tenantId: 'tenantA',
});
expect(url).toBe('https://d123.cloudfront.net/t/tenantA/documents/user1/doc.pdf');
- expect(mockGetS3Key).toHaveBeenCalledWith('documents', 'user1', 'doc.pdf', 'tenantA');
+ expect(mockGetS3Key).toHaveBeenCalledWith(
+ expect.objectContaining({
+ basePath: 'documents',
+ userId: 'user1',
+ fileName: 'doc.pdf',
+ tenantId: 'tenantA',
+ }),
+ );
+ });
+
+ it('uses region-prefixed keys when configured', async () => {
+ mockGetCloudFrontConfig.mockReturnValue(
+ makeConfig({ storageRegion: 'us-east-2', includeRegionInPath: true }),
+ );
+ const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
+ const url = await getCloudFrontURL({
+ userId: 'user1',
+ fileName: 'doc.pdf',
+ basePath: 'documents',
+ tenantId: 'tenantA',
+ });
+ expect(url).toBe('https://d123.cloudfront.net/r/us-east-2/t/tenantA/documents/user1/doc.pdf');
+ expect(mockGetS3Key).toHaveBeenCalledWith(
+ expect.objectContaining({
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ }),
+ );
+ });
+
+ it('uses region-aware private inline image keys when configured', async () => {
+ mockGetCloudFrontConfig.mockReturnValue(
+ makeConfig({ storageRegion: 'eu-central-1', includeRegionInPath: true }),
+ );
+ const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
+ const url = await getCloudFrontURL({
+ userId: 'user1',
+ fileName: 'photo.webp',
+ tenantId: 'tenantA',
+ });
+ expect(url).toBe(
+ 'https://d123.cloudfront.net/i/r/eu-central-1/t/tenantA/images/user1/photo.webp',
+ );
+ expect(mockGetS3Key).toHaveBeenCalledWith(
+ expect.objectContaining({
+ basePath: 'images',
+ useInlinePath: true,
+ }),
+ );
+ });
+
+ it('uses avatar cookie namespace for avatar URLs', async () => {
+ const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
+ const url = await getCloudFrontURL({
+ userId: 'user1',
+ fileName: 'avatar.png',
+ basePath: 'avatars',
+ tenantId: 'tenantA',
+ });
+ expect(url).toBe('https://d123.cloudfront.net/a/t/tenantA/avatars/user1/avatar.png');
+ expect(mockGetS3Key).toHaveBeenCalledWith(
+ expect.objectContaining({
+ basePath: 'avatars',
+ useInlinePath: true,
+ }),
+ );
});
it('strips trailing slash from domain', async () => {
@@ -104,7 +184,7 @@ describe('CloudFront CRUD', () => {
);
const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
const url = await getCloudFrontURL({ userId: 'user1', fileName: 'photo.webp' });
- expect(url).toBe('https://d123.cloudfront.net/images/user1/photo.webp');
+ expect(url).toBe('https://d123.cloudfront.net/i/images/user1/photo.webp');
});
it('strips multiple trailing slashes from domain', async () => {
@@ -113,7 +193,7 @@ describe('CloudFront CRUD', () => {
);
const { getCloudFrontURL } = await import('~/storage/cloudfront/crud');
const url = await getCloudFrontURL({ userId: 'user1', fileName: 'photo.webp' });
- expect(url).toBe('https://d123.cloudfront.net/images/user1/photo.webp');
+ expect(url).toBe('https://d123.cloudfront.net/i/images/user1/photo.webp');
});
it('strips leading slash from S3 key', async () => {
@@ -223,6 +303,7 @@ describe('CloudFront CRUD', () => {
buffer: Buffer.from('data'),
fileName: 'f.webp',
basePath: 'images',
+ useInlinePath: true,
urlBuilder: expect.any(Function),
}),
);
@@ -318,18 +399,22 @@ describe('CloudFront CRUD', () => {
});
describe('uploadFileToCloudFront', () => {
- it('delegates to uploadFileToS3 with a urlBuilder', async () => {
- const uploadResult = { filepath: 'https://d123.cloudfront.net/images/u/f.pdf', bytes: 1024 };
+ it('keeps document uploads outside the inline cookie namespaces', async () => {
+ const uploadResult = { filepath: 'https://d123.cloudfront.net/uploads/u/f.pdf', bytes: 1024 };
mockUploadFileToS3.mockResolvedValue(uploadResult);
const mockReq = { user: { id: 'u' } } as ServerRequest;
- const mockFile = { path: '/tmp/f.pdf' } as Express.Multer.File;
+ const mockFile = {
+ path: '/tmp/f.pdf',
+ mimetype: 'application/pdf',
+ } as Express.Multer.File;
const { uploadFileToCloudFront } = await import('~/storage/cloudfront/crud');
const result = await uploadFileToCloudFront({
req: mockReq,
file: mockFile,
file_id: 'fid-1',
+ basePath: 'uploads',
});
expect(mockUploadFileToS3).toHaveBeenCalledWith(
@@ -337,11 +422,35 @@ describe('CloudFront CRUD', () => {
req: mockReq,
file: mockFile,
file_id: 'fid-1',
+ basePath: 'uploads',
+ useInlinePath: false,
urlBuilder: expect.any(Function),
}),
);
expect(result).toEqual(uploadResult);
});
+
+ it('keeps image uploads in the private inline namespace', async () => {
+ const uploadResult = { filepath: 'https://d123.cloudfront.net/i/images/u/f.png', bytes: 512 };
+ mockUploadFileToS3.mockResolvedValue(uploadResult);
+
+ const mockReq = { user: { id: 'u' } } as ServerRequest;
+ const mockFile = { path: '/tmp/f.png', mimetype: 'image/png' } as Express.Multer.File;
+
+ const { uploadFileToCloudFront } = await import('~/storage/cloudfront/crud');
+ const result = await uploadFileToCloudFront({
+ req: mockReq,
+ file: mockFile,
+ file_id: 'fid-1',
+ });
+
+ expect(mockUploadFileToS3).toHaveBeenCalledWith(
+ expect.objectContaining({
+ useInlinePath: true,
+ }),
+ );
+ expect(result).toEqual(uploadResult);
+ });
});
describe('deleteFileFromCloudFront', () => {
@@ -355,6 +464,7 @@ describe('CloudFront CRUD', () => {
beforeEach(() => {
mockDeleteFileFromS3.mockResolvedValue(undefined);
mockExtractKeyFromS3Url.mockReturnValue('images/u/file.webp');
+ mockResolveStoredS3Key.mockReturnValue('images/u/file.webp');
});
it('calls deleteFileFromS3 to remove the file', async () => {
@@ -402,7 +512,7 @@ describe('CloudFront CRUD', () => {
});
it('prefixes key with / for invalidation path', async () => {
- mockExtractKeyFromS3Url.mockReturnValue('images/u/file.webp'); // no leading slash
+ mockResolveStoredS3Key.mockReturnValue('images/u/file.webp'); // no leading slash
mockGetCloudFrontConfig.mockReturnValue(
makeConfig({ invalidateOnDelete: true, distributionId: 'E123' }),
);
@@ -422,7 +532,7 @@ describe('CloudFront CRUD', () => {
});
it('does not re-prefix path that already has leading slash', async () => {
- mockExtractKeyFromS3Url.mockReturnValue('/images/u/file.webp'); // already has slash
+ mockResolveStoredS3Key.mockReturnValue('/images/u/file.webp'); // already has slash
mockGetCloudFrontConfig.mockReturnValue(
makeConfig({ invalidateOnDelete: true, distributionId: 'E123' }),
);
@@ -481,7 +591,7 @@ describe('CloudFront CRUD', () => {
mockGetCloudFrontConfig.mockReturnValue(
makeConfig({ privateKey: 'pk-secret', keyPairId: 'K123' }),
);
- mockExtractKeyFromS3Url.mockReturnValue('t/tenantA/uploads/user1/doc.pdf');
+ mockResolveStoredS3Key.mockReturnValue('t/tenantA/uploads/user1/doc.pdf');
mockGetSignedUrl.mockReturnValue(
'https://d123.cloudfront.net/t/tenantA/uploads/user1/doc.pdf?Policy=abc',
);
@@ -495,8 +605,10 @@ describe('CloudFront CRUD', () => {
});
expect(result).toContain('Policy=abc');
- expect(mockExtractKeyFromS3Url).toHaveBeenCalledWith(
- 'https://d123.cloudfront.net/t/tenantA/uploads/user1/doc.pdf',
+ expect(mockResolveStoredS3Key).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filepath: 'https://d123.cloudfront.net/t/tenantA/uploads/user1/doc.pdf',
+ }),
);
expect(mockGetSignedUrl).toHaveBeenCalledWith(
expect.objectContaining({
@@ -511,7 +623,7 @@ describe('CloudFront CRUD', () => {
mockGetCloudFrontConfig.mockReturnValue(
makeConfig({ privateKey: 'pk-secret', keyPairId: 'K123' }),
);
- mockExtractKeyFromS3Url.mockReturnValue('uploads/user1/report.pdf');
+ mockResolveStoredS3Key.mockReturnValue('uploads/user1/report.pdf');
mockGetSignedUrl.mockReturnValue('signed-url');
const { getCloudFrontDownloadURL } = await import('~/storage/cloudfront/crud');
@@ -553,7 +665,7 @@ describe('CloudFront CRUD', () => {
it('throws when signing keys are missing', async () => {
mockGetCloudFrontConfig.mockReturnValue(makeConfig({ privateKey: null, keyPairId: null }));
- mockExtractKeyFromS3Url.mockReturnValue('uploads/user1/doc.pdf');
+ mockResolveStoredS3Key.mockReturnValue('uploads/user1/doc.pdf');
const { getCloudFrontDownloadURL } = await import('~/storage/cloudfront/crud');
await expect(
diff --git a/packages/api/src/storage/cloudfront/crud.ts b/packages/api/src/storage/cloudfront/crud.ts
index 074ed3e5df..b532bbd909 100644
--- a/packages/api/src/storage/cloudfront/crud.ts
+++ b/packages/api/src/storage/cloudfront/crud.ts
@@ -16,7 +16,7 @@ import type {
} from '~/storage/types';
import { getCloudFrontConfig } from '~/cdn/cloudfront';
import { s3Config } from '~/storage/s3/s3Config';
-import { DEFAULT_BASE_PATH as defaultBasePath } from '~/storage/constants';
+import { AVATAR_BASE_PATH, DEFAULT_BASE_PATH as defaultBasePath } from '~/storage/constants';
import { sanitizeContentDispositionFilename } from '~/storage/validation';
import {
getS3Key,
@@ -25,7 +25,7 @@ import {
uploadFileToS3,
deleteFileFromS3,
getS3FileStream,
- extractKeyFromS3Url,
+ resolveStoredS3Key,
} from '~/storage/s3/crud';
let _cloudFrontClient: CloudFrontClient | null = null;
@@ -45,6 +45,38 @@ export interface CloudFrontURLParams extends GetURLParams {
sign?: boolean;
}
+function getRegionPathOptions({
+ basePath = defaultBasePath,
+ storageRegion = null,
+ includeRegionInPath,
+ useInlinePath,
+}: {
+ basePath?: string;
+ storageRegion?: string | null;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
+}): Pick<GetURLParams, 'storageRegion' | 'includeRegionInPath' | 'useInlinePath'> {
+ const config = getCloudFrontConfig();
+ const shouldIncludeRegion = includeRegionInPath ?? config?.includeRegionInPath ?? false;
+ return {
+ includeRegionInPath: shouldIncludeRegion,
+ storageRegion: shouldIncludeRegion
+ ? (storageRegion ?? config?.storageRegion ?? s3Config.AWS_REGION ?? process.env.AWS_REGION)
+ : (storageRegion ?? config?.storageRegion),
+ useInlinePath: useInlinePath ?? (basePath === defaultBasePath || basePath === AVATAR_BASE_PATH),
+ };
+}
+
+function isInlineFileUpload({ basePath, file, useInlinePath }: UploadFileParams): boolean {
+ if (useInlinePath != null) {
+ return useInlinePath;
+ }
+ if (basePath === AVATAR_BASE_PATH) {
+ return true;
+ }
+ return (basePath ?? defaultBasePath) === defaultBasePath && file.mimetype?.startsWith('image/');
+}
+
function buildCloudFrontUrl(s3Key: string): string {
const config = getCloudFrontConfig();
if (!config?.domain) {
@@ -127,9 +159,18 @@ export async function getCloudFrontURL({
fileName,
basePath = defaultBasePath,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath,
+ useInlinePath,
sign = false,
}: CloudFrontURLParams): Promise<string> {
- const key = getS3Key(basePath, userId, fileName, tenantId);
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId,
+ ...getRegionPathOptions({ basePath, storageRegion, includeRegionInPath, useInlinePath }),
+ });
const url = buildCloudFrontUrl(key);
return sign ? signUrl(url) : url;
}
@@ -139,7 +180,12 @@ export async function saveBufferToCloudFront(
params: SaveBufferParams & { sign?: boolean },
): Promise<string> {
const { sign = false, ...rest } = params;
- return saveBufferToS3({ ...rest, urlBuilder: (p) => getCloudFrontURL({ ...p, sign }) });
+ const regionOptions = getRegionPathOptions(rest);
+ return saveBufferToS3({
+ ...rest,
+ ...regionOptions,
+ urlBuilder: (p) => getCloudFrontURL({ ...p, ...regionOptions, sign }),
+ });
}
/** Save file from URL to S3 and return CloudFront URL. */
@@ -155,9 +201,11 @@ export async function saveURLToCloudFrontWithMetadata(
params: SaveURLParams & { sign?: boolean },
): Promise<SaveURLResult> {
const { sign = false, ...rest } = params;
+ const regionOptions = getRegionPathOptions(rest);
return saveURLToS3WithMetadata({
...rest,
- urlBuilder: (p) => getCloudFrontURL({ ...p, sign }),
+ ...regionOptions,
+ urlBuilder: (p) => getCloudFrontURL({ ...p, ...regionOptions, sign }),
});
}
@@ -166,7 +214,15 @@ export async function uploadFileToCloudFront(
params: UploadFileParams & { sign?: boolean },
): Promise<UploadResult> {
const { sign = false, ...rest } = params;
- return uploadFileToS3({ ...rest, urlBuilder: (p) => getCloudFrontURL({ ...p, sign }) });
+ const regionOptions = getRegionPathOptions({
+ ...rest,
+ useInlinePath: isInlineFileUpload(rest),
+ });
+ return uploadFileToS3({
+ ...rest,
+ ...regionOptions,
+ urlBuilder: (p) => getCloudFrontURL({ ...p, ...regionOptions, sign }),
+ });
}
/** Delete file from S3 and optionally invalidate CloudFront cache. */
@@ -179,7 +235,7 @@ export async function deleteFileFromCloudFront(req: ServerRequest, file: TFile):
try {
const client = getOrCreateCloudFrontClient();
// CloudFront URL pathname matches S3 key when no origin path prefix is configured
- const key = extractKeyFromS3Url(file.filepath);
+ const key = resolveStoredS3Key(file);
const path = key.startsWith('/') ? key : `/${key}`;
await client.send(
@@ -215,7 +271,7 @@ export async function getCloudFrontDownloadURL({
customFilename = null,
contentType = null,
}: DownloadURLParams): Promise<string> {
- const key = extractKeyFromS3Url(file.filepath);
+ const key = resolveStoredS3Key(file);
if (!key) {
throw new Error('[getCloudFrontDownloadURL] Unable to extract S3 key from file path');
}
diff --git a/packages/api/src/storage/constants.ts b/packages/api/src/storage/constants.ts
index c2f6ac5939..3a173c4bb8 100644
--- a/packages/api/src/storage/constants.ts
+++ b/packages/api/src/storage/constants.ts
@@ -3,3 +3,9 @@ export const DEFAULT_BASE_PATH = 'images';
/** Shared avatar base path for cloud-stored public/avatar assets. */
export const AVATAR_BASE_PATH = 'avatars';
+
+/** CloudFront cookie path prefix for private inline images. */
+export const INLINE_IMAGE_PATH_PREFIX = 'i';
+
+/** CloudFront cookie path prefix for app-visible avatars. */
+export const INLINE_AVATAR_PATH_PREFIX = 'a';
diff --git a/packages/api/src/storage/index.ts b/packages/api/src/storage/index.ts
index fe545dcc01..2c8df83f0a 100644
--- a/packages/api/src/storage/index.ts
+++ b/packages/api/src/storage/index.ts
@@ -3,3 +3,4 @@ export * from './s3';
export * from './types';
export * from './images';
export * from './avatar';
+export * from './metadata';
diff --git a/packages/api/src/storage/metadata.ts b/packages/api/src/storage/metadata.ts
new file mode 100644
index 0000000000..8dfdb2333b
--- /dev/null
+++ b/packages/api/src/storage/metadata.ts
@@ -0,0 +1,51 @@
+import { logger } from '@librechat/data-schemas';
+import { FileSources } from 'librechat-data-provider';
+import type { SaveURLResult } from './types';
+import { extractKeyFromS3Url, getStorageMetadataForKey } from './s3/crud';
+
+type StorageMetadataInput = {
+ filepath?: string | null;
+ source?: string | null;
+ storageKey?: string | null;
+ storageRegion?: string | null;
+};
+
+export function getStorageMetadata({
+ filepath,
+ source,
+ storageKey,
+ storageRegion,
+}: StorageMetadataInput): Pick<SaveURLResult, 'storageKey' | 'storageRegion'> {
+ if (source !== FileSources.s3 && source !== FileSources.cloudfront) {
+ return {};
+ }
+
+ let key = storageKey ?? '';
+ if (!key && filepath) {
+ try {
+ key = extractKeyFromS3Url(filepath);
+ } catch (error) {
+ logger.warn('[getStorageMetadata] Unable to extract storage key from filepath', error);
+ return {};
+ }
+ }
+ if (!key) {
+ return {};
+ }
+
+ const metadata = getStorageMetadataForKey(key);
+ if (!metadata.storageKey) {
+ return {};
+ }
+
+ if (storageRegion && metadata.storageRegion && storageRegion !== metadata.storageRegion) {
+ logger.warn(
+ `[getStorageMetadata] storageRegion "${storageRegion}" does not match key region "${metadata.storageRegion}".`,
+ );
+ }
+
+ return {
+ ...metadata,
+ ...(storageRegion ? { storageRegion } : {}),
+ };
+}
diff --git a/packages/api/src/storage/s3/__tests__/crud.test.ts b/packages/api/src/storage/s3/__tests__/crud.test.ts
index 55b5200e61..5004446625 100644
--- a/packages/api/src/storage/s3/__tests__/crud.test.ts
+++ b/packages/api/src/storage/s3/__tests__/crud.test.ts
@@ -87,6 +87,52 @@ describe('S3 CRUD', () => {
expect(key).toBe('images/user123/file.png');
});
+ it('keeps the legacy positional overload outside inline cookie namespaces', async () => {
+ const { getS3Key } = await import('../crud');
+ expect(getS3Key('images', 'user123', 'file.png', 'tenantA')).toBe(
+ 't/tenantA/images/user123/file.png',
+ );
+ expect(getS3Key('avatars', 'user123', 'avatar.png')).toBe('avatars/user123/avatar.png');
+ });
+
+ it('keeps object-form image and avatar keys outside inline cookie namespaces by default', async () => {
+ const { getS3Key } = await import('../crud');
+ expect(
+ getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ }),
+ ).toBe('images/user123/file.png');
+ expect(
+ getS3Key({
+ basePath: 'avatars',
+ userId: 'user123',
+ fileName: 'avatar.png',
+ }),
+ ).toBe('avatars/user123/avatar.png');
+ });
+
+ it('uses inline cookie namespaces only when explicitly requested', async () => {
+ const { getS3Key } = await import('../crud');
+ expect(
+ getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ useInlinePath: true,
+ }),
+ ).toBe('i/images/user123/file.png');
+ expect(
+ getS3Key({
+ basePath: 'avatars',
+ userId: 'user123',
+ fileName: 'avatar.png',
+ useInlinePath: true,
+ }),
+ ).toBe('a/avatars/user123/avatar.png');
+ });
+
it('handles nested file names', async () => {
const { getS3Key } = await import('../crud');
const key = getS3Key('files', 'user456', 'folder/subfolder/doc.pdf');
@@ -99,6 +145,85 @@ describe('S3 CRUD', () => {
expect(key).toBe('t/tenantA/images/user123/file.png');
});
+ it('keeps region-prefixed image keys outside inline namespaces by default', async () => {
+ const { getS3Key } = await import('../crud');
+ const key = getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+ expect(key).toBe('r/us-east-2/images/user123/file.png');
+ });
+
+ it('constructs region-prefixed inline image keys when requested', async () => {
+ const { getS3Key } = await import('../crud');
+ const key = getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ useInlinePath: true,
+ });
+ expect(key).toBe('i/r/us-east-2/images/user123/file.png');
+ });
+
+ it('constructs region and tenant-prefixed keys together', async () => {
+ const { getS3Key } = await import('../crud');
+ const key = getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ tenantId: 'tenantA',
+ storageRegion: 'eu-central-1',
+ includeRegionInPath: true,
+ useInlinePath: true,
+ });
+ expect(key).toBe('i/r/eu-central-1/t/tenantA/images/user123/file.png');
+ });
+
+ it('constructs avatar-prefixed region keys under the avatar cookie namespace', async () => {
+ const { getS3Key } = await import('../crud');
+ const key = getS3Key({
+ basePath: 'avatars',
+ userId: 'user123',
+ fileName: 'avatar.png',
+ tenantId: 'tenantA',
+ storageRegion: 'ap-southeast-1',
+ includeRegionInPath: true,
+ useInlinePath: true,
+ });
+ expect(key).toBe('a/r/ap-southeast-1/t/tenantA/avatars/user123/avatar.png');
+ });
+
+ it('keeps uploads outside the inline cookie namespaces when region pathing is enabled', async () => {
+ const { getS3Key } = await import('../crud');
+ const key = getS3Key({
+ basePath: 'uploads',
+ userId: 'user123',
+ fileName: 'report.pdf',
+ tenantId: 'tenantA',
+ storageRegion: 'eu-central-1',
+ includeRegionInPath: true,
+ });
+ expect(key).toBe('r/eu-central-1/t/tenantA/uploads/user123/report.pdf');
+ });
+
+ it('throws if storageRegion contains unsafe path characters', async () => {
+ const { getS3Key } = await import('../crud');
+ expect(() =>
+ getS3Key({
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ storageRegion: 'us/east/2',
+ includeRegionInPath: true,
+ }),
+ ).toThrow('[getS3Key] storageRegion must not contain slashes: "us/east/2"');
+ });
+
it('throws if basePath contains a slash', async () => {
const { getS3Key } = await import('../crud');
expect(() => getS3Key('a/b', 'user123', 'file.png')).toThrow(
@@ -138,6 +263,7 @@ describe('S3 CRUD', () => {
it('parses legacy keys', async () => {
const { parseS3Key } = await import('../crud');
expect(parseS3Key('images/user123/folder/file.png')).toEqual({
+ useInlinePath: false,
basePath: 'images',
userId: 'user123',
fileName: 'folder/file.png',
@@ -147,11 +273,89 @@ describe('S3 CRUD', () => {
it('parses tenant-prefixed keys', async () => {
const { parseS3Key } = await import('../crud');
expect(parseS3Key('t/tenantA/images/user123/file.png')).toEqual({
+ useInlinePath: false,
+ tenantId: 'tenantA',
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ });
+ });
+
+ it('round-trips legacy image and avatar keys without adding inline prefixes', async () => {
+ const { getS3Key, parseS3Key } = await import('../crud');
+ const imageKey = parseS3Key('images/user123/file.png');
+ const avatarKey = parseS3Key('avatars/user123/avatar.png');
+
+ expect(imageKey).not.toBeNull();
+ expect(avatarKey).not.toBeNull();
+ expect(getS3Key(imageKey!)).toBe('images/user123/file.png');
+ expect(getS3Key(avatarKey!)).toBe('avatars/user123/avatar.png');
+ });
+
+ it('parses region-prefixed keys', async () => {
+ const { parseS3Key } = await import('../crud');
+ expect(parseS3Key('i/r/us-east-2/images/user123/file.png')).toEqual({
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ useInlinePath: true,
+ inlinePathPrefix: 'i',
+ basePath: 'images',
+ userId: 'user123',
+ fileName: 'file.png',
+ });
+ });
+
+ it('parses non-region inline-prefixed keys', async () => {
+ const { parseS3Key } = await import('../crud');
+ expect(parseS3Key('i/t/tenantA/images/user123/file.png')).toEqual({
+ useInlinePath: true,
+ inlinePathPrefix: 'i',
tenantId: 'tenantA',
basePath: 'images',
userId: 'user123',
fileName: 'file.png',
});
+ expect(parseS3Key('a/avatars/user123/avatar.png')).toEqual({
+ useInlinePath: true,
+ inlinePathPrefix: 'a',
+ basePath: 'avatars',
+ userId: 'user123',
+ fileName: 'avatar.png',
+ });
+ });
+
+ it('parses region-prefixed avatar keys', async () => {
+ const { parseS3Key } = await import('../crud');
+ expect(parseS3Key('a/r/us-east-2/t/tenantA/avatars/user123/avatar.png')).toEqual({
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ useInlinePath: true,
+ inlinePathPrefix: 'a',
+ tenantId: 'tenantA',
+ basePath: 'avatars',
+ userId: 'user123',
+ fileName: 'avatar.png',
+ });
+ });
+
+ it('parses region and tenant-prefixed keys', async () => {
+ const { parseS3Key } = await import('../crud');
+ expect(parseS3Key('r/ap-southeast-1/t/tenantA/uploads/user123/report.pdf')).toEqual({
+ storageRegion: 'ap-southeast-1',
+ includeRegionInPath: true,
+ useInlinePath: false,
+ tenantId: 'tenantA',
+ basePath: 'uploads',
+ userId: 'user123',
+ fileName: 'report.pdf',
+ });
+ });
+
+ it('rejects malformed inline-prefixed keys', async () => {
+ const { parseS3Key } = await import('../crud');
+ expect(parseS3Key('i/r/us-east-2/uploads/user123/file.pdf')).toBeNull();
+ expect(parseS3Key('a/r/us-east-2/images/user123/file.png')).toBeNull();
+ expect(parseS3Key('i/r/us-east-2/images/user123')).toBeNull();
});
it('returns null for incomplete keys', async () => {
@@ -164,6 +368,8 @@ describe('S3 CRUD', () => {
const { parseS3Key } = await import('../crud');
expect(parseS3Key('t/../images/user123/file.png')).toBeNull();
expect(parseS3Key('images/../file.png')).toBeNull();
+ expect(parseS3Key('r/us\u0000east/images/user123/file.png')).toBeNull();
+ expect(parseS3Key('r/us-east-2/images/user123/../file.png')).toBeNull();
});
});
@@ -216,6 +422,40 @@ describe('S3 CRUD', () => {
fileName: 'document.pdf',
basePath: 'documents',
tenantId: 'tenantA',
+ storageRegion: null,
+ includeRegionInPath: false,
+ useInlinePath: undefined,
+ });
+ });
+
+ it('uses region-prefixed key and URL params when region pathing is enabled', async () => {
+ const urlBuilder = jest
+ .fn()
+ .mockResolvedValue('https://cdn.example.com/r/us-east-2/file.txt');
+ const { saveBufferToS3 } = await import('../crud');
+ await saveBufferToS3({
+ userId: 'user123',
+ buffer: Buffer.from('test content'),
+ fileName: 'document.pdf',
+ basePath: 'documents',
+ tenantId: 'tenantA',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ urlBuilder,
+ });
+
+ const calls = s3Mock.commandCalls(PutObjectCommand);
+ expect(calls[0].args[0].input.Key).toBe(
+ 'r/us-east-2/t/tenantA/documents/user123/document.pdf',
+ );
+ expect(urlBuilder).toHaveBeenCalledWith({
+ userId: 'user123',
+ fileName: 'document.pdf',
+ basePath: 'documents',
+ tenantId: 'tenantA',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ useInlinePath: undefined,
});
});
@@ -357,12 +597,33 @@ describe('S3 CRUD', () => {
expect(s3Mock.commandCalls(PutObjectCommand)).toHaveLength(1);
expect(result).toEqual({
filepath: 'https://bucket.s3.amazonaws.com/test-key?signed=true',
+ storageKey: 'images/user123/downloaded.jpg',
bytes: 8,
type: 'image/jpeg',
dimensions: {},
});
});
+ it('returns storage metadata for region-prefixed URL saves', async () => {
+ const { saveURLToS3WithMetadata } = await import('../crud');
+ const result = await saveURLToS3WithMetadata({
+ userId: 'user123',
+ URL: 'https://example.com/image.jpg',
+ fileName: 'downloaded.jpg',
+ tenantId: 'tenantA',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+
+ expect(result).toMatchObject({
+ storageKey: 'r/us-east-2/t/tenantA/images/user123/downloaded.jpg',
+ storageRegion: 'us-east-2',
+ });
+ expect(s3Mock.commandCalls(PutObjectCommand)[0].args[0].input.Key).toBe(
+ 'r/us-east-2/t/tenantA/images/user123/downloaded.jpg',
+ );
+ });
+
it('uses the downloaded buffer size instead of a stale content-length header', async () => {
(global.fetch as unknown as jest.Mock).mockResolvedValueOnce({
ok: true,
@@ -571,6 +832,44 @@ describe('S3 CRUD', () => {
expect(s3Mock.commandCalls(DeleteObjectCommand)).toHaveLength(1);
});
+ it('deletes a region-prefixed tenant file when owner and tenant match', async () => {
+ const mockFile = {
+ filepath: 'https://bucket.s3.amazonaws.com/r/us-east-2/t/tenantA/images/user123/file.jpg',
+ file_id: 'file123',
+ user: 'user123',
+ tenantId: 'tenantA',
+ } as TFile;
+
+ s3Mock.on(HeadObjectCommand).resolvesOnce({});
+
+ const { deleteFileFromS3 } = await import('../crud');
+ await deleteFileFromS3(mockReq, mockFile);
+
+ expect(s3Mock.commandCalls(DeleteObjectCommand)[0].args[0].input.Key).toBe(
+ 'r/us-east-2/t/tenantA/images/user123/file.jpg',
+ );
+ expect(deleteRagFile).toHaveBeenCalledWith({ userId: 'user123', file: mockFile });
+ });
+
+ it('prefers storageKey when deleting legacy filepath records', async () => {
+ const mockFile = {
+ filepath: 'https://bucket.s3.amazonaws.com/images/user123/legacy.jpg',
+ storageKey: 'r/us-east-2/t/tenantA/images/user123/file.jpg',
+ file_id: 'file123',
+ user: 'user123',
+ tenantId: 'tenantA',
+ } as TFile;
+
+ s3Mock.on(HeadObjectCommand).resolvesOnce({});
+
+ const { deleteFileFromS3 } = await import('../crud');
+ await deleteFileFromS3(mockReq, mockFile);
+
+ expect(s3Mock.commandCalls(DeleteObjectCommand)[0].args[0].input.Key).toBe(
+ 'r/us-east-2/t/tenantA/images/user123/file.jpg',
+ );
+ });
+
it('handles file not found gracefully and cleans up RAG', async () => {
const mockFile = {
filepath: 'https://bucket.s3.amazonaws.com/images/user123/nonexistent.jpg',
@@ -673,6 +972,7 @@ describe('S3 CRUD', () => {
expect(result).toEqual({
filepath: expect.stringContaining('signed=true'),
+ storageKey: 'images/user123/file123__photo.jpg',
bytes: 1024,
});
expect(fs.createReadStream).toHaveBeenCalledWith('/tmp/upload.jpg');
@@ -704,6 +1004,33 @@ describe('S3 CRUD', () => {
expect(calls[0].args[0].input.Key).toBe('t/tenantA/images/user123/file123__photo.jpg');
});
+ it('uses region-prefixed keys when uploading a file from disk', async () => {
+ const mockFile = {
+ path: '/tmp/upload.jpg',
+ originalname: 'photo.jpg',
+ } as Express.Multer.File;
+
+ (fs.promises.stat as jest.Mock).mockResolvedValue({ size: 1024 });
+ (fs.createReadStream as jest.Mock).mockReturnValue(new Readable());
+
+ const { uploadFileToS3 } = await import('../crud');
+ const result = await uploadFileToS3({
+ req: mockReq,
+ file: mockFile,
+ file_id: 'file123',
+ basePath: 'images',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+
+ const calls = s3Mock.commandCalls(PutObjectCommand);
+ expect(calls[0].args[0].input.Key).toBe('r/us-east-2/images/user123/file123__photo.jpg');
+ expect(result).toMatchObject({
+ storageKey: 'r/us-east-2/images/user123/file123__photo.jpg',
+ storageRegion: 'us-east-2',
+ });
+ });
+
it('handles upload errors and cleans up temp file', async () => {
const mockFile = {
path: '/tmp/upload.jpg',
@@ -783,6 +1110,30 @@ describe('S3 CRUD', () => {
expect.anything(),
);
});
+
+ it('prefers storageKey when present', async () => {
+ const mockFile = {
+ filepath: 'https://bucket.s3.amazonaws.com/images/user123/legacy.pdf',
+ storageKey: 'r/eu-central-1/t/tenantA/uploads/user123/file.pdf',
+ filename: 'file.pdf',
+ } as TFile;
+
+ const { getS3DownloadURL } = await import('../crud');
+ await getS3DownloadURL({
+ req: {} as ServerRequest,
+ file: mockFile,
+ });
+
+ expect(getSignedUrl).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ input: expect.objectContaining({
+ Key: 'r/eu-central-1/t/tenantA/uploads/user123/file.pdf',
+ }),
+ }),
+ expect.anything(),
+ );
+ });
});
describe('needsRefresh', () => {
@@ -832,6 +1183,15 @@ describe('S3 CRUD', () => {
);
expect(result).toContain('signed=true');
+ expect(getSignedUrl).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ input: expect.objectContaining({
+ Key: 'images/user123/file.jpg',
+ }),
+ }),
+ expect.anything(),
+ );
});
it('generates a new URL from a tenant-prefixed S3 URL', async () => {
@@ -891,9 +1251,37 @@ describe('S3 CRUD', () => {
expect(result[0].filepath).toContain('signed=true');
expect(result[1].filepath).toContain('signed=true');
+ expect(getSignedUrl).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
+ expect.objectContaining({
+ input: expect.objectContaining({
+ Key: 'images/user123/file1.jpg',
+ }),
+ }),
+ expect.anything(),
+ );
+ expect(getSignedUrl).toHaveBeenNthCalledWith(
+ 2,
+ expect.anything(),
+ expect.objectContaining({
+ input: expect.objectContaining({
+ Key: 'images/user456/file2.jpg',
+ }),
+ }),
+ expect.anything(),
+ );
expect(mockBatchUpdate).toHaveBeenCalledWith([
- { file_id: 'file1', filepath: expect.stringContaining('signed=true') },
- { file_id: 'file2', filepath: expect.stringContaining('signed=true') },
+ {
+ file_id: 'file1',
+ filepath: expect.stringContaining('signed=true'),
+ storageKey: 'images/user123/file1.jpg',
+ },
+ {
+ file_id: 'file2',
+ filepath: expect.stringContaining('signed=true'),
+ storageKey: 'images/user456/file2.jpg',
+ },
]);
});
diff --git a/packages/api/src/storage/s3/crud.ts b/packages/api/src/storage/s3/crud.ts
index b6a1695ddc..22833f3b20 100644
--- a/packages/api/src/storage/s3/crud.ts
+++ b/packages/api/src/storage/s3/crud.ts
@@ -39,6 +39,12 @@ import {
} from '~/storage/validation';
import { initializeS3 } from '~/cdn/s3';
import { deleteRagFile } from '~/files';
+import {
+ AVATAR_BASE_PATH,
+ DEFAULT_BASE_PATH as defaultBasePath,
+ INLINE_AVATAR_PATH_PREFIX,
+ INLINE_IMAGE_PATH_PREFIX,
+} from '~/storage/constants';
import { s3Config } from './s3Config';
const {
@@ -47,16 +53,31 @@ const {
AWS_FORCE_PATH_STYLE: forcePathStyle,
S3_URL_EXPIRY_SECONDS: s3UrlExpirySeconds,
S3_REFRESH_EXPIRY_MS: s3RefreshExpiryMs,
- DEFAULT_BASE_PATH: defaultBasePath,
} = s3Config;
const MULTIPART_UPLOAD_PART_SIZE = 5 * 1024 * 1024;
+const INLINE_STORAGE_PREFIXES = new Map([
+ [defaultBasePath, INLINE_IMAGE_PATH_PREFIX],
+ [AVATAR_BASE_PATH, INLINE_AVATAR_PATH_PREFIX],
+]);
-export interface S3KeyParts {
+interface S3KeyBase {
basePath: string;
userId: string;
fileName: string;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
+}
+
+export interface S3KeyParts extends S3KeyBase {
+ storageRegion?: string;
tenantId?: string;
+ inlinePathPrefix?: string;
+}
+
+export interface S3KeyOptions extends S3KeyBase {
+ tenantId?: string | null;
+ storageRegion?: string | null;
}
const parseS3PathSegment = (value: string | undefined): string | null => {
@@ -67,27 +88,103 @@ const parseS3PathSegment = (value: string | undefined): string | null => {
}
};
-export const getS3Key = (
- basePath: string,
- userId: string,
- fileName: string,
- tenantId?: string | null,
-): string => {
- const safeBasePath = assertPathSegment('basePath', basePath, 'getS3Key');
- const safeUserId = assertPathSegment('userId', userId, 'getS3Key');
- const safeFileName = assertS3FileName('fileName', fileName, 'getS3Key');
+const parseS3FileName = (value: string | undefined): string | null => {
+ try {
+ return assertS3FileName('fileName', value, 'parseS3Key');
+ } catch {
+ return null;
+ }
+};
- if (tenantId) {
- const safeTenantId = assertPathSegment('tenantId', tenantId, 'getS3Key');
- return `t/${safeTenantId}/${safeBasePath}/${safeUserId}/${safeFileName}`;
+const getParsedPathFlags = (
+ storageRegion?: string,
+ inlinePathPrefix?: string,
+): Pick<S3KeyParts, 'useInlinePath' | 'inlinePathPrefix'> => {
+ if (inlinePathPrefix) {
+ return { useInlinePath: true, inlinePathPrefix };
}
- return `${safeBasePath}/${safeUserId}/${safeFileName}`;
+ return { useInlinePath: false };
};
-export const parseS3Key = (key: string): S3KeyParts | null => {
- const normalizedKey = key.replace(/^\/+/, '');
- const keyParts = normalizedKey.split('/');
+const getDefaultStorageRegion = (): string | null =>
+ s3Config.AWS_REGION || process.env.AWS_REGION || null;
+
+const getInlinePathPrefix = ({
+ basePath,
+ useInlinePath,
+}: Pick<S3KeyOptions, 'basePath' | 'useInlinePath'>): string | null => {
+ const prefix = INLINE_STORAGE_PREFIXES.get(basePath);
+ const shouldUseInlinePath = useInlinePath ?? false;
+ if (!shouldUseInlinePath) {
+ return null;
+ }
+ if (!prefix) {
+ throw new Error(`[getS3Key] inline path is not supported for basePath: "${basePath}"`);
+ }
+ return prefix;
+};
+
+function normalizeS3KeyOptions(
+ basePathOrOptions: string | S3KeyOptions,
+ userId?: string,
+ fileName?: string,
+ tenantId?: string | null,
+): S3KeyOptions {
+ if (typeof basePathOrOptions === 'object') {
+ return basePathOrOptions;
+ }
+ return {
+ basePath: basePathOrOptions,
+ userId: userId ?? '',
+ fileName: fileName ?? '',
+ tenantId,
+ useInlinePath: false,
+ };
+}
+
+export function getS3Key(options: S3KeyOptions): string;
+export function getS3Key(
+ basePath: string,
+ userId: string,
+ fileName: string,
+ tenantId?: string | null,
+): string;
+export function getS3Key(
+ basePathOrOptions: string | S3KeyOptions,
+ userId?: string,
+ fileName?: string,
+ tenantId?: string | null,
+): string {
+ const options = normalizeS3KeyOptions(basePathOrOptions, userId, fileName, tenantId);
+ const { includeRegionInPath = false } = options;
+ const safeBasePath = assertPathSegment('basePath', options.basePath, 'getS3Key');
+ const safeUserId = assertPathSegment('userId', options.userId, 'getS3Key');
+ const safeFileName = assertS3FileName('fileName', options.fileName, 'getS3Key');
+ const inlinePathPrefix = getInlinePathPrefix({
+ ...options,
+ basePath: safeBasePath,
+ });
+
+ const pathParts: string[] = [];
+ if (inlinePathPrefix) {
+ pathParts.push(inlinePathPrefix);
+ }
+ if (includeRegionInPath) {
+ const storageRegion = options.storageRegion ?? getDefaultStorageRegion();
+ pathParts.push('r', assertPathSegment('storageRegion', storageRegion, 'getS3Key'));
+ }
+ if (options.tenantId) {
+ pathParts.push('t', assertPathSegment('tenantId', options.tenantId, 'getS3Key'));
+ }
+ pathParts.push(safeBasePath, safeUserId, safeFileName);
+ return pathParts.join('/');
+}
+const parseS3KeyParts = (
+ keyParts: string[],
+ storageRegion?: string,
+ inlinePathPrefix?: string,
+): S3KeyParts | null => {
if (keyParts[0] === 't') {
if (keyParts.length < 5) {
return null;
@@ -96,14 +193,22 @@ export const parseS3Key = (key: string): S3KeyParts | null => {
const safeTenantId = parseS3PathSegment(tenantId);
const safeBasePath = parseS3PathSegment(basePath);
const safeUserId = parseS3PathSegment(userId);
- if (!safeTenantId || !safeBasePath || !safeUserId) {
+ const safeFileName = parseS3FileName(fileNameParts.join('/'));
+ if (!safeTenantId || !safeBasePath || !safeUserId || !safeFileName) {
+ return null;
+ }
+ const expectedInlinePrefix = INLINE_STORAGE_PREFIXES.get(safeBasePath);
+ if (inlinePathPrefix && expectedInlinePrefix !== inlinePathPrefix) {
return null;
}
return {
+ ...(storageRegion ? { storageRegion } : {}),
+ ...(storageRegion ? { includeRegionInPath: true } : {}),
+ ...getParsedPathFlags(storageRegion, inlinePathPrefix),
tenantId: safeTenantId,
basePath: safeBasePath,
userId: safeUserId,
- fileName: fileNameParts.join('/'),
+ fileName: safeFileName,
};
}
@@ -113,12 +218,67 @@ export const parseS3Key = (key: string): S3KeyParts | null => {
const [basePath, userId, ...fileNameParts] = keyParts;
const safeBasePath = parseS3PathSegment(basePath);
const safeUserId = parseS3PathSegment(userId);
- if (!safeBasePath || !safeUserId) {
+ const safeFileName = parseS3FileName(fileNameParts.join('/'));
+ if (!safeBasePath || !safeUserId || !safeFileName) {
+ return null;
+ }
+ const expectedInlinePrefix = INLINE_STORAGE_PREFIXES.get(safeBasePath);
+ if (inlinePathPrefix && expectedInlinePrefix !== inlinePathPrefix) {
return null;
}
- return { basePath: safeBasePath, userId: safeUserId, fileName: fileNameParts.join('/') };
+ return {
+ ...(storageRegion ? { storageRegion } : {}),
+ ...(storageRegion ? { includeRegionInPath: true } : {}),
+ ...getParsedPathFlags(storageRegion, inlinePathPrefix),
+ basePath: safeBasePath,
+ userId: safeUserId,
+ fileName: safeFileName,
+ };
+};
+
+export const parseS3Key = (key: string): S3KeyParts | null => {
+ const normalizedKey = key.replace(/^\/+/, '');
+ const keyParts = normalizedKey.split('/');
+ const inlinePathPrefix =
+ keyParts[0] === INLINE_IMAGE_PATH_PREFIX || keyParts[0] === INLINE_AVATAR_PATH_PREFIX
+ ? keyParts.shift()
+ : undefined;
+
+ if (keyParts[0] === 'r') {
+ if (keyParts.length < 5) {
+ return null;
+ }
+ const [, storageRegion, ...remainingParts] = keyParts;
+ const safeStorageRegion = parseS3PathSegment(storageRegion);
+ if (!safeStorageRegion) {
+ return null;
+ }
+ return parseS3KeyParts(remainingParts, safeStorageRegion, inlinePathPrefix);
+ }
+
+ return parseS3KeyParts(keyParts, undefined, inlinePathPrefix);
};
+export function getStorageMetadataForKey(
+ key: string,
+): Pick<SaveURLResult, 'storageKey' | 'storageRegion'> {
+ const normalizedKey = key.replace(/^\/+/, '');
+ const parsedKey = parseS3Key(normalizedKey);
+ if (!parsedKey) {
+ return {};
+ }
+ return {
+ storageKey: normalizedKey,
+ ...(parsedKey?.storageRegion ? { storageRegion: parsedKey.storageRegion } : {}),
+ };
+}
+
+export function resolveStoredS3Key(
+ file: Pick<TFile, 'filepath'> & { storageKey?: string | null },
+): string {
+ return file.storageKey || extractKeyFromS3Url(file.filepath);
+}
+
async function getS3URLForKey({
key,
customFilename = null,
@@ -158,8 +318,19 @@ export async function getS3URL({
customFilename = null,
contentType = null,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath = false,
+ useInlinePath,
}: GetURLParams): Promise<string> {
- const key = getS3Key(basePath, userId, fileName, tenantId);
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
return getS3URLForKey({ key, customFilename, contentType });
}
@@ -169,9 +340,20 @@ export async function saveBufferToS3({
fileName,
basePath = defaultBasePath,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath = false,
+ useInlinePath,
urlBuilder,
}: SaveBufferParams & { urlBuilder?: UrlBuilder }): Promise<string> {
- const key = getS3Key(basePath, userId, fileName, tenantId);
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
const params = { Bucket: bucketName, Key: key, Body: buffer };
try {
@@ -182,7 +364,15 @@ export async function saveBufferToS3({
await s3.send(new PutObjectCommand(params));
const getUrl = urlBuilder ?? getS3URL;
- return await getUrl({ userId, fileName, basePath, tenantId });
+ return await getUrl({
+ userId,
+ fileName,
+ basePath,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
} catch (error) {
logger.error('[saveBufferToS3] Error uploading buffer to S3:', (error as Error).message);
throw error;
@@ -232,12 +422,23 @@ async function saveReadableToS3({
fileName,
basePath = defaultBasePath,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath = false,
+ useInlinePath,
urlBuilder,
}: Omit<SaveBufferParams, 'buffer'> & {
body: Readable;
urlBuilder?: UrlBuilder;
-}): Promise<{ filepath: string; bytes: number }> {
- const key = getS3Key(basePath, userId, fileName, tenantId);
+}): Promise<{ filepath: string; bytes: number; storageKey?: string; storageRegion?: string }> {
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
const pending: PendingUploadBuffers = { buffers: [], bytes: 0 };
const completedParts: CompletedPart[] = [];
let totalBytes = 0;
@@ -310,7 +511,19 @@ async function saveReadableToS3({
}
const getUrl = urlBuilder ?? getS3URL;
- return { filepath: await getUrl({ userId, fileName, basePath, tenantId }), bytes: totalBytes };
+ return {
+ filepath: await getUrl({
+ userId,
+ fileName,
+ basePath,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ }),
+ bytes: totalBytes,
+ ...getStorageMetadataForKey(key),
+ };
} catch (error) {
if (uploadId) {
try {
@@ -332,6 +545,9 @@ export async function saveURLToS3WithMetadata({
fileName,
basePath = defaultBasePath,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath = false,
+ useInlinePath,
urlBuilder,
}: SaveURLParams & { urlBuilder?: UrlBuilder }): Promise<SaveURLResult> {
try {
@@ -350,10 +566,15 @@ export async function saveURLToS3WithMetadata({
fileName,
basePath,
tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
urlBuilder,
});
return {
filepath: result.filepath,
+ storageKey: result.storageKey,
+ storageRegion: result.storageRegion,
bytes: result.bytes,
type: contentType,
dimensions: {},
@@ -367,10 +588,23 @@ export async function saveURLToS3WithMetadata({
fileName,
basePath,
tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
urlBuilder,
});
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
return {
filepath,
+ ...getStorageMetadataForKey(key),
bytes: buffer.byteLength,
type: contentType,
dimensions: {},
@@ -393,6 +627,10 @@ export function extractKeyFromS3Url(fileUrlOrKey: string): string {
throw new Error('Invalid input: URL or key is empty');
}
+ if (!fileUrlOrKey.startsWith('http://') && !fileUrlOrKey.startsWith('https://')) {
+ return fileUrlOrKey.startsWith('/') ? fileUrlOrKey.substring(1) : fileUrlOrKey;
+ }
+
try {
const url = new URL(fileUrlOrKey);
const hostname = url.hostname;
@@ -470,7 +708,7 @@ export async function deleteFileFromS3(req: ServerRequest, file: TFile): Promise
throw new Error('[deleteFileFromS3] User not authenticated');
}
- const key = extractKeyFromS3Url(file.filepath);
+ const key = resolveStoredS3Key(file);
const parsedKey = parseS3Key(key);
const ownerId = file.user?.toString?.();
const fileTenantId = file.tenantId?.toString?.() ?? null;
@@ -534,6 +772,9 @@ export async function uploadFileToS3({
file_id,
basePath = defaultBasePath,
tenantId = null,
+ storageRegion = null,
+ includeRegionInPath = false,
+ useInlinePath,
urlBuilder,
}: UploadFileParams & { urlBuilder?: UrlBuilder }): Promise<UploadResult> {
if (!req.user) {
@@ -545,7 +786,15 @@ export async function uploadFileToS3({
const userId = req.user.id;
const resolvedTenantId = tenantId ?? req.user.tenantId ?? null;
const fileName = `${file_id}__${file.originalname}`;
- const key = getS3Key(basePath, userId, fileName, resolvedTenantId);
+ const key = getS3Key({
+ basePath,
+ userId,
+ fileName,
+ tenantId: resolvedTenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
const stats = await fs.promises.stat(inputFilePath);
const bytes = stats.size;
@@ -564,12 +813,20 @@ export async function uploadFileToS3({
await s3.send(new PutObjectCommand(uploadParams));
const getUrl = urlBuilder ?? getS3URL;
- const fileURL = await getUrl({ userId, fileName, basePath, tenantId: resolvedTenantId });
+ const fileURL = await getUrl({
+ userId,
+ fileName,
+ basePath,
+ tenantId: resolvedTenantId,
+ storageRegion,
+ includeRegionInPath,
+ useInlinePath,
+ });
// NOTE: temp file is intentionally NOT deleted on the success path.
// The caller (processAgentFileUpload) reads file.path after this returns
// to stream the file to the RAG vector embedding service (POST /embed).
// Temp file lifecycle on success is the caller's responsibility.
- return { filepath: fileURL, bytes };
+ return { filepath: fileURL, bytes, ...getStorageMetadataForKey(key) };
} catch (error) {
logger.error('[uploadFileToS3] Error streaming file to S3:', error);
if (file?.path) {
@@ -609,7 +866,7 @@ export async function getS3DownloadURL({
customFilename = null,
contentType = null,
}: DownloadURLParams): Promise<string> {
- const key = extractKeyFromS3Url(file.filepath);
+ const key = resolveStoredS3Key(file);
if (!key) {
throw new Error('[getS3DownloadURL] Unable to extract S3 key from file path');
}
@@ -655,9 +912,12 @@ export function needsRefresh(signedUrl: string, bufferSeconds: number): boolean
}
}
-export async function getNewS3URL(currentURL: string): Promise<string | undefined> {
+export async function getNewS3URL(
+ currentURL: string,
+ storageKey?: string | null,
+): Promise<string | undefined> {
try {
- const s3Key = extractKeyFromS3Url(currentURL);
+ const s3Key = storageKey || extractKeyFromS3Url(currentURL);
if (!s3Key) {
return;
}
@@ -682,7 +942,12 @@ export async function refreshS3FileUrls(
return [];
}
- const filesToUpdate: Array<{ file_id: string; filepath: string }> = [];
+ const filesToUpdate: Array<{
+ file_id: string;
+ filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
+ }> = [];
const updatedFiles = [...files];
for (let i = 0; i < updatedFiles.length; i++) {
@@ -701,15 +966,19 @@ export async function refreshS3FileUrls(
}
try {
- const newURL = await getNewS3URL(file.filepath);
+ const newURL = await getNewS3URL(file.filepath, file.storageKey);
if (!newURL) {
continue;
}
+ const storageMetadata = file.storageKey
+ ? getStorageMetadataForKey(file.storageKey)
+ : getStorageMetadataForKey(extractKeyFromS3Url(file.filepath));
filesToUpdate.push({
file_id: file.file_id,
filepath: newURL,
+ ...storageMetadata,
});
- updatedFiles[i] = { ...file, filepath: newURL };
+ updatedFiles[i] = { ...file, filepath: newURL, ...storageMetadata };
} catch (error) {
logger.error(`Error refreshing S3 URL for file ${file.file_id}:`, error);
}
@@ -732,7 +1001,7 @@ export async function refreshS3Url(fileObj: S3FileRef, bufferSeconds = 3600): Pr
}
try {
- const s3Key = extractKeyFromS3Url(fileObj.filepath);
+ const s3Key = fileObj.storageKey || extractKeyFromS3Url(fileObj.filepath);
if (!s3Key) {
logger.warn(`Unable to extract S3 key from URL: ${fileObj.filepath}`);
return fileObj.filepath;
diff --git a/packages/api/src/storage/types.ts b/packages/api/src/storage/types.ts
index 6462b3f4bd..63afab569a 100644
--- a/packages/api/src/storage/types.ts
+++ b/packages/api/src/storage/types.ts
@@ -7,6 +7,9 @@ export interface SaveBufferParams {
fileName: string;
basePath?: string;
tenantId?: string | null;
+ storageRegion?: string | null;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
}
export interface GetURLParams {
@@ -16,6 +19,9 @@ export interface GetURLParams {
customFilename?: string | null;
contentType?: string | null;
tenantId?: string | null;
+ storageRegion?: string | null;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
}
export interface SaveURLParams {
@@ -24,10 +30,15 @@ export interface SaveURLParams {
fileName: string;
basePath?: string;
tenantId?: string | null;
+ storageRegion?: string | null;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
}
export interface SaveURLResult {
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
bytes?: number;
type?: string;
dimensions?: {
@@ -42,6 +53,9 @@ export interface UploadFileParams {
file_id: string;
basePath?: string;
tenantId?: string | null;
+ storageRegion?: string | null;
+ includeRegionInPath?: boolean;
+ useInlinePath?: boolean;
}
export interface DownloadURLParams {
@@ -58,6 +72,8 @@ export interface UploadImageParams extends UploadFileParams {
export interface UploadResult {
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
bytes: number;
}
@@ -77,11 +93,15 @@ export interface ProcessAvatarParams {
export interface S3FileRef {
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
source: string;
}
export type SaveBufferFn = (params: SaveBufferParams) => Promise<string>;
-export type BatchUpdateFn = (files: Array<{ file_id: string; filepath: string }>) => Promise<void>;
+export type BatchUpdateFn = (
+ files: Array<{ file_id: string; filepath: string; storageKey?: string; storageRegion?: string }>,
+) => Promise<void>;
export type UrlBuilder = (params: GetURLParams) => Promise<string>;
diff --git a/packages/api/src/types/files.ts b/packages/api/src/types/files.ts
index 62df64afb0..203c500eeb 100644
--- a/packages/api/src/types/files.ts
+++ b/packages/api/src/types/files.ts
@@ -177,6 +177,12 @@ export interface StrategyFunctions {
getDownloadURL?: (params: DownloadURLParams) => Promise<string>;
deleteFile?: (
req: ServerRequest,
- file: { filepath: string; user?: string; tenantId?: string | null },
+ file: {
+ filepath: string;
+ storageKey?: string | null;
+ storageRegion?: string | null;
+ user?: string;
+ tenantId?: string | null;
+ },
) => Promise<void>;
}
diff --git a/packages/data-provider/src/cloudfront-config.spec.ts b/packages/data-provider/src/cloudfront-config.spec.ts
index 4d7766c368..c3c0a00416 100644
--- a/packages/data-provider/src/cloudfront-config.spec.ts
+++ b/packages/data-provider/src/cloudfront-config.spec.ts
@@ -26,6 +26,27 @@ describe('cloudfrontConfigSchema cookieDomain validation', () => {
});
expect(result.success).toBe(true);
});
+
+ it('defaults region pathing to disabled', () => {
+ const result = cloudfrontConfigSchema.safeParse({
+ domain: 'https://cdn.example.com',
+ });
+ expect(result.success).toBe(true);
+ if (!result.success) {
+ throw result.error;
+ }
+ expect(result.data?.includeRegionInPath ?? false).toBe(false);
+ expect(result.data?.storageRegion).toBeUndefined();
+ });
+
+ it('accepts optional region pathing config', () => {
+ const result = cloudfrontConfigSchema.safeParse({
+ domain: 'https://cdn.example.com',
+ storageRegion: 'us-east-2',
+ includeRegionInPath: true,
+ });
+ expect(result.success).toBe(true);
+ });
});
describe('cloudfrontConfigSchema cross-field refinements', () => {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index d0ae378f0b..c5c62be3fc 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -203,6 +203,8 @@ export const cloudfrontConfigSchema = z
message: 'cookieDomain must start with a dot (e.g., ".example.com") to apply to subdomains',
})
.optional(),
+ storageRegion: z.string().min(1).optional(),
+ includeRegionInPath: z.boolean().default(false),
})
.refine((data) => !data.invalidateOnDelete || !!data.distributionId, {
message: 'distributionId is required when invalidateOnDelete is true',
diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.ts
index f4bd260e6e..6771033614 100644
--- a/packages/data-provider/src/types/files.ts
+++ b/packages/data-provider/src/types/files.ts
@@ -100,6 +100,8 @@ export type TFile = {
__v?: number;
user: string;
tenantId?: string;
+ storageRegion?: string;
+ storageKey?: string;
conversationId?: string;
message?: string;
file_id: string;
@@ -228,6 +230,8 @@ export type DeleteFilesResponse = {
export type BatchFile = {
file_id: string;
filepath: string;
+ storageRegion?: string;
+ storageKey?: string;
embedded: boolean;
source: FileSources;
temp_file_id?: string;
diff --git a/packages/data-provider/src/types/skills.ts b/packages/data-provider/src/types/skills.ts
index b8dd22a7f3..3552629a80 100644
--- a/packages/data-provider/src/types/skills.ts
+++ b/packages/data-provider/src/types/skills.ts
@@ -172,6 +172,8 @@ export type TSkillFile = {
file_id: string;
filename: string;
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
source: FileSources;
mimeType: string;
bytes: number;
diff --git a/packages/data-schemas/src/methods/file.spec.ts b/packages/data-schemas/src/methods/file.spec.ts
index 1d3efb56a2..e3882f4958 100644
--- a/packages/data-schemas/src/methods/file.spec.ts
+++ b/packages/data-schemas/src/methods/file.spec.ts
@@ -688,6 +688,62 @@ describe('File Methods', () => {
}
});
+ it('should persist storage metadata when provided', async () => {
+ const userId = new mongoose.Types.ObjectId();
+ const fileId = uuidv4();
+
+ await fileMethods.createFile({
+ file_id: fileId,
+ user: userId,
+ filename: 'region-file.txt',
+ filepath: '/old-path/file.txt',
+ type: 'text/plain',
+ bytes: 100,
+ });
+
+ await fileMethods.batchUpdateFiles([
+ {
+ file_id: fileId,
+ filepath: '/new-path/file.txt',
+ storageKey: 'i/r/us-east-2/images/user123/file.txt',
+ storageRegion: 'us-east-2',
+ },
+ ]);
+
+ const file = await fileMethods.findFileById(fileId);
+ expect(file?.filepath).toBe('/new-path/file.txt');
+ expect(file?.storageKey).toBe('i/r/us-east-2/images/user123/file.txt');
+ expect(file?.storageRegion).toBe('us-east-2');
+ });
+
+ it('should not overwrite existing storage metadata when omitted', async () => {
+ const userId = new mongoose.Types.ObjectId();
+ const fileId = uuidv4();
+
+ await fileMethods.createFile({
+ file_id: fileId,
+ user: userId,
+ filename: 'existing-metadata.txt',
+ filepath: '/old-path/file.txt',
+ storageKey: 'r/eu-central-1/uploads/user123/file.txt',
+ storageRegion: 'eu-central-1',
+ type: 'text/plain',
+ bytes: 100,
+ });
+
+ await fileMethods.batchUpdateFiles([
+ {
+ file_id: fileId,
+ filepath: '/new-path/file.txt',
+ },
+ ]);
+
+ const file = await fileMethods.findFileById(fileId);
+ expect(file?.filepath).toBe('/new-path/file.txt');
+ expect(file?.storageKey).toBe('r/eu-central-1/uploads/user123/file.txt');
+ expect(file?.storageRegion).toBe('eu-central-1');
+ });
+
it('should handle empty updates array gracefully', async () => {
await expect(fileMethods.batchUpdateFiles([])).resolves.toBeUndefined();
});
diff --git a/packages/data-schemas/src/methods/file.ts b/packages/data-schemas/src/methods/file.ts
index 5ed87e002c..a09770d675 100644
--- a/packages/data-schemas/src/methods/file.ts
+++ b/packages/data-schemas/src/methods/file.ts
@@ -326,10 +326,15 @@ export function createFileMethods(mongoose: typeof import('mongoose')) {
/**
* Batch updates files with new signed URLs in MongoDB
- * @param updates - Array of updates in the format { file_id, filepath }
+ * @param updates - Array of updates in the format { file_id, filepath, storageKey?, storageRegion? }
*/
async function batchUpdateFiles(
- updates: Array<{ file_id: string; filepath: string }>,
+ updates: Array<{
+ file_id: string;
+ filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
+ }>,
): Promise<void> {
if (!updates || updates.length === 0) {
return;
@@ -339,7 +344,13 @@ export function createFileMethods(mongoose: typeof import('mongoose')) {
const bulkOperations = updates.map((update) => ({
updateOne: {
filter: { file_id: update.file_id },
- update: { $set: { filepath: update.filepath } },
+ update: {
+ $set: {
+ filepath: update.filepath,
+ ...(update.storageKey ? { storageKey: update.storageKey } : {}),
+ ...(update.storageRegion ? { storageRegion: update.storageRegion } : {}),
+ },
+ },
},
}));
diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.ts
index e28269152c..86cf101678 100644
--- a/packages/data-schemas/src/methods/skill.spec.ts
+++ b/packages/data-schemas/src/methods/skill.spec.ts
@@ -1318,6 +1318,27 @@ describe('SkillFile methods', () => {
expect(files[0].file_id).toBe('file-2');
});
+ it('upsertSkillFile persists storage metadata', async () => {
+ const { skill } = await methods.createSkill(makeSkillInput());
+ await methods.upsertSkillFile({
+ skillId: skill._id,
+ relativePath: 'scripts/parse.sh',
+ file_id: 'file-1',
+ filename: 'parse.sh',
+ filepath: '/tmp/v1',
+ storageKey: 'r/us-east-2/uploads/user123/parse.sh',
+ storageRegion: 'us-east-2',
+ source: 's3',
+ mimeType: 'text/plain',
+ bytes: 10,
+ author: owner._id,
+ });
+
+ const files = await methods.listSkillFiles(skill._id);
+ expect(files[0].storageKey).toBe('r/us-east-2/uploads/user123/parse.sh');
+ expect(files[0].storageRegion).toBe('us-east-2');
+ });
+
it('deleteSkillFile recounts and bumps version', async () => {
const { skill } = await methods.createSkill(makeSkillInput());
await methods.upsertSkillFile({
diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.ts
index 2e2ca5f052..502ca34c47 100644
--- a/packages/data-schemas/src/methods/skill.ts
+++ b/packages/data-schemas/src/methods/skill.ts
@@ -587,6 +587,8 @@ export type UpsertSkillFileInput = {
file_id: string;
filename: string;
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
source: string;
mimeType: string;
bytes: number;
@@ -1424,6 +1426,8 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Sk
file_id: row.file_id,
filename: row.filename,
filepath: row.filepath,
+ storageKey: row.storageKey,
+ storageRegion: row.storageRegion,
source: row.source,
mimeType: row.mimeType,
bytes: row.bytes,
diff --git a/packages/data-schemas/src/schema/file.ts b/packages/data-schemas/src/schema/file.ts
index e9127dfd5f..4b9d462b2d 100644
--- a/packages/data-schemas/src/schema/file.ts
+++ b/packages/data-schemas/src/schema/file.ts
@@ -39,6 +39,12 @@ const file: Schema<IMongoFile> = new Schema(
type: String,
required: true,
},
+ storageKey: {
+ type: String,
+ },
+ storageRegion: {
+ type: String,
+ },
object: {
type: String,
required: true,
diff --git a/packages/data-schemas/src/schema/skillFile.ts b/packages/data-schemas/src/schema/skillFile.ts
index b0430fce91..fbaa35155c 100644
--- a/packages/data-schemas/src/schema/skillFile.ts
+++ b/packages/data-schemas/src/schema/skillFile.ts
@@ -59,6 +59,12 @@ const skillFileSchema: Schema<ISkillFileDocument> = new Schema(
type: String,
required: true,
},
+ storageKey: {
+ type: String,
+ },
+ storageRegion: {
+ type: String,
+ },
source: {
type: String,
required: true,
diff --git a/packages/data-schemas/src/types/file.ts b/packages/data-schemas/src/types/file.ts
index 163980ca84..28170ee57f 100644
--- a/packages/data-schemas/src/types/file.ts
+++ b/packages/data-schemas/src/types/file.ts
@@ -50,6 +50,8 @@ export interface IMongoFile extends Omit<Document, 'model'> {
previewRevision?: string;
filename: string;
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
object: 'file';
embedded?: boolean;
type: string;
diff --git a/packages/data-schemas/src/types/skill.ts b/packages/data-schemas/src/types/skill.ts
index 084d1c2af5..90555ffe65 100644
--- a/packages/data-schemas/src/types/skill.ts
+++ b/packages/data-schemas/src/types/skill.ts
@@ -116,6 +116,8 @@ export interface ISkillFile {
file_id: string;
filename: string;
filepath: string;
+ storageKey?: string;
+ storageRegion?: string;
source: string;
mimeType: string;
bytes: number;