2026-09-07 16:49:00 +08:00
import { ObjectInfo , S3SignRequest } from '@shumai/dtos'
import {
S3Client ,
PutObjectCommand ,
GetObjectCommand ,
HeadObjectCommand ,
DeleteObjectCommand ,
DeleteObjectsCommand ,
ListObjectsV2Command ,
ListObjectsV2CommandOutput ,
CopyObjectCommand ,
CreateMultipartUploadCommand ,
UploadPartCommand ,
ListPartsCommand ,
CompleteMultipartUploadCommand ,
AbortMultipartUploadCommand ,
2026-11-03 20:31:56 +08:00
StorageClass ,
2026-09-07 16:49:00 +08:00
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
2026-05-19 16:05:09 +08:00
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
2026-09-07 16:49:00 +08:00
import { Readable } from 'stream'
2026-09-07 19:33:13 +08:00
import { pipeline } from 'stream/promises'
2026-05-19 16:05:09 +08:00
import { ulid } from 'ulid'
2026-06-08 14:52:56 +08:00
import { LruTtlCache } from '../cache/lru-ttl-cache'
2026-07-28 14:28:41 +08:00
import { detectSupportedMimeType } from '../utils/mime'
2026-05-19 16:05:09 +08:00
export function signLocalUrl ( bucket : string , key : string ) : string {
const secret = process . env . BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto . createHmac ( 'sha256' , secret )
hmac . update ( ` ${ bucket } / ${ key } ` )
const signature = hmac . digest ( 'hex' )
return `/api/upload/local?bucket= ${ encodeURIComponent ( bucket ) } &key= ${ encodeURIComponent ( key ) } &Signature= ${ signature } `
}
export function verifyLocalUrlSignature ( bucket : string , key : string , signature : string ) : boolean {
const secret = process . env . BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto . createHmac ( 'sha256' , secret )
hmac . update ( ` ${ bucket } / ${ key } ` )
const expected = hmac . digest ( 'hex' )
try {
return crypto . timingSafeEqual ( Buffer . from ( signature , 'hex' ), Buffer . from ( expected , 'hex' ))
} catch {
return false
}
}
2026-11-05 20:49:38 +08:00
export const DEFAULT_LOCAL_GET_EXPIRY_SECONDS = 12 * 3600
export function signLocalGetUrl (
bucket : string ,
key : string ,
expiresInSeconds : number = DEFAULT_LOCAL_GET_EXPIRY_SECONDS ,
) : { signature : string ; expires : number } {
const expires = Math . floor ( Date . now () / 1000 ) + expiresInSeconds
const secret = process . env . BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto . createHmac ( 'sha256' , secret )
hmac . update ( `GET: ${ bucket } / ${ key } : ${ expires } ` )
const signature = hmac . digest ( 'hex' )
return { signature , expires }
}
export function verifyLocalGetUrlSignature (
bucket : string ,
key : string ,
signature : string | undefined | null ,
expiresStr : string | undefined | null ,
) : boolean {
if ( ! signature || ! expiresStr ) return false
const expires = parseInt ( expiresStr , 10 )
if ( isNaN ( expires )) return false
const now = Math . floor ( Date . now () / 1000 )
if ( now > expires ) return false
const secret = process . env . BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto . createHmac ( 'sha256' , secret )
hmac . update ( `GET: ${ bucket } / ${ key } : ${ expires } ` )
const expected = hmac . digest ( 'hex' )
try {
const sigBuf = Buffer . from ( signature , 'hex' )
const expBuf = Buffer . from ( expected , 'hex' )
if ( sigBuf . length !== expBuf . length ) return false
return crypto . timingSafeEqual ( sigBuf , expBuf )
} catch {
return false
}
}
2026-08-09 16:39:15 +08:00
/**
* Build a Content-Disposition header value for downloads.
* - Falls back to plain `attachment` when no filename is provided.
* - Strips control characters (CR/LF header injection), quotes, and backslashes.
* - Header values must be ASCII (RFC 7230): non-ASCII names are conveyed only
* via the percent-encoded RFC 5987 `filename*` parameter; the quoted
* `filename="..."` fallback is included only when the name is pure ASCII.
*/
export function buildContentDisposition ( filename? : string | null ) : string {
if ( ! filename ) return 'attachment'
// Strip C0 control characters (incl. CR/LF header injection) and DEL, then
// quotes/backslashes which would break the quoted-string form.
const sanitized = [... filename ]
. filter (( ch ) => {
const code = ch . charCodeAt ( 0 )
return code > 0x1f && code !== 0x7f && ch !== '"' && ch !== '\\'
})
. join ( '' )
. trim ()
if ( ! sanitized ) return 'attachment'
// RFC 5987 attr-char excludes ' ( ) * — percent-encode them explicitly
const encoded = encodeURIComponent ( sanitized ). replace (
/['()*]/g ,
( c ) => `% ${ c . charCodeAt ( 0 ). toString ( 16 ). toUpperCase () } ` ,
)
const isAscii = [... sanitized ]. every (( ch ) => ch . charCodeAt ( 0 ) <= 0x7f )
if ( ! isAscii ) {
return `attachment; filename*=UTF-8'' ${ encoded } `
}
return `attachment; filename=" ${ sanitized } "; filename*=UTF-8'' ${ encoded } `
}
2026-05-19 16:05:09 +08:00
export interface S3Object {
buffer : Buffer
contentType : string
}
2026-11-03 20:31:56 +08:00
export interface S3StreamObject {
stream : ReadableStream < Uint8Array >
contentLength? : number
contentType? : string
}
export interface UploadStreamParams {
bucket : string
key : string
stream : ReadableStream < Uint8Array >
contentLength? : number
contentType? : string
storageClass? : string
}
const SINGLE_PUT_MAX_BYTES = 64 * 1024 * 1024 // 64 MB
const MULTIPART_PART_SIZE_BYTES = 16 * 1024 * 1024 // 16 MB
export function bodyToWebReadableStream ( body : unknown ) : ReadableStream < Uint8Array > {
if ( ! body ) {
throw new Error ( 'NoSuchKey: The specified key returned an empty body.' )
}
if (
typeof body === 'object' &&
'transformToWebStream' in body &&
typeof ( body as { transformToWebStream : unknown }). transformToWebStream === 'function'
) {
return (
body as { transformToWebStream : () => ReadableStream < Uint8Array > }
). transformToWebStream ()
}
if ( typeof body === 'object' && 'getReader' in body ) {
return body as ReadableStream < Uint8Array >
}
// Convert Node.js Readable or AsyncIterable to Web ReadableStream
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeReadable = 'pipe' in ( body as any ) ? ( body as Readable ) : Readable . from ( body as any )
return Readable . toWeb ( nodeReadable ) as unknown as ReadableStream < Uint8Array >
}
export function isS3NotFoundError ( err : unknown ) : boolean {
if ( ! err || typeof err !== 'object' ) return false
const r = err as Record < string , unknown >
const name = typeof r . name === 'string' ? r . name : ''
const code = typeof r . code === 'string' ? r . code : ''
const msg = typeof r . message === 'string' ? r . message : ''
const metadata = r . $metadata as { httpStatusCode? : number } | undefined
return (
name === 'NotFound' ||
name === 'NoSuchKey' ||
code === 'NotFound' ||
code === 'NoSuchKey' ||
code === 'ENOENT' ||
metadata ? . httpStatusCode === 404 ||
msg . includes ( 'NoSuchKey' ) ||
msg . includes ( 'NotFound' )
)
}
export async function writeStreamToLocalFile (
targetPath : string ,
stream : ReadableStream < Uint8Array >,
) : Promise < void > {
const dir = path . dirname ( targetPath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
const tempPath = ` ${ targetPath } .tmp- ${ ulid () } `
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeStream = Readable . fromWeb ( stream as any )
await pipeline ( nodeStream , fs . createWriteStream ( tempPath ))
await fs . promises . rename ( tempPath , targetPath )
} catch ( err ) {
await fs . promises . unlink ( tempPath ). catch (() => {})
throw err
}
}
export async function uploadStreamToS3Client (
client : S3Client ,
params : UploadStreamParams ,
partSizeBytes : number = MULTIPART_PART_SIZE_BYTES ,
singlePutMaxBytes : number = SINGLE_PUT_MAX_BYTES ,
) : Promise < void > {
const { bucket , key , stream , contentLength , contentType , storageClass } = params
// AWS SDK v3 StorageClass is an open string union at runtime; cast safely for arbitrary S3-compatible classes
const s3StorageClass = storageClass ? ( storageClass as StorageClass ) : undefined
const MAX_S3_PARTS = 10000
const effectivePartSize =
contentLength !== undefined && contentLength > MAX_S3_PARTS * partSizeBytes
? Math . max ( partSizeBytes , Math . ceil ( contentLength / 9900 ))
: partSizeBytes
if ( contentLength !== undefined && contentLength <= singlePutMaxBytes ) {
if ( contentLength === 0 ) {
await stream . cancel (). catch (() => {})
await client . send (
new PutObjectCommand ({
Bucket : bucket ,
Key : key ,
Body : Buffer.alloc ( 0 ),
ContentLength : 0 ,
ContentType : contentType ,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass : s3StorageClass ,
}),
)
return
}
// Convert Web ReadableStream to Node stream without buffering into memory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nodeStream = Readable . fromWeb ( stream as any )
await client . send (
new PutObjectCommand ({
Bucket : bucket ,
Key : key ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Body : nodeStream as any ,
ContentLength : contentLength ,
ContentType : contentType ,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass : s3StorageClass ,
}),
)
return
}
// Multipart streaming upload for > 64 MB or unknown contentLength
const createRes = await client . send (
new CreateMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
ContentType : contentType ,
// eslint-disable-next-line @typescript-eslint/naming-convention
StorageClass : s3StorageClass ,
}),
)
const uploadId = createRes . UploadId
if ( ! uploadId ) {
throw new Error ( `Failed to initiate multipart upload for ${ bucket } / ${ key } ` )
}
const reader = stream . getReader ()
// eslint-disable-next-line @typescript-eslint/naming-convention
const completedParts : Array < { ETag? : string ; PartNumber : number } > = []
let partNumber = 1
const pendingChunks : Uint8Array [] = []
let pendingLength = 0
const flushPart = async ( sizeToFlush : number ) => {
const partBuffer = Buffer . allocUnsafe ( sizeToFlush )
let offset = 0
while ( offset < sizeToFlush && pendingChunks . length > 0 ) {
const chunk = pendingChunks [ 0 ]
const remaining = sizeToFlush - offset
if ( chunk . byteLength <= remaining ) {
partBuffer . set ( chunk , offset )
offset += chunk . byteLength
pendingLength -= chunk . byteLength
pendingChunks . shift ()
} else {
partBuffer . set ( chunk . subarray ( 0 , remaining ), offset )
pendingChunks [ 0 ] = chunk . subarray ( remaining )
offset += remaining
pendingLength -= remaining
}
}
const currentPartNumber = partNumber ++
const partRes = await client . send (
new UploadPartCommand ({
Bucket : bucket ,
Key : key ,
UploadId : uploadId ,
PartNumber : currentPartNumber ,
Body : partBuffer ,
ContentLength : partBuffer.byteLength ,
}),
)
completedParts . push ({
// eslint-disable-next-line @typescript-eslint/naming-convention
ETag : partRes.ETag ,
PartNumber : currentPartNumber ,
})
}
try {
while ( true ) {
const { done , value } = await reader . read ()
if ( done ) {
break
}
if ( value && value . byteLength > 0 ) {
pendingChunks . push ( value )
pendingLength += value . byteLength
while ( pendingLength >= effectivePartSize ) {
await flushPart ( effectivePartSize )
}
}
}
if ( pendingLength > 0 || completedParts . length === 0 ) {
await flushPart ( pendingLength )
}
await client . send (
new CompleteMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
UploadId : uploadId ,
/* eslint-disable @typescript-eslint/naming-convention */
MultipartUpload : {
Parts : completedParts ,
},
/* eslint-enable @typescript-eslint/naming-convention */
}),
)
} catch ( err ) {
await reader . cancel (). catch (() => {})
await client
. send (
new AbortMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
UploadId : uploadId ,
}),
)
. catch (() => {})
throw err
} finally {
reader . releaseLock ()
}
}
2026-05-19 16:05:09 +08:00
export interface S3Service {
2026-07-30 08:29:18 +08:00
getObjectSize : ( bucket : string , key : string ) => Promise < number >
putObject : (
2026-05-19 16:05:09 +08:00
bucket : string ,
key : string ,
2026-09-07 19:33:13 +08:00
body : Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS . ReadableStream ,
2026-05-19 16:05:09 +08:00
size : number ,
contentType? : string ,
2026-07-30 08:29:18 +08:00
) => Promise < void >
getObject : ( bucket : string , key : string ) => Promise < S3Object >
2026-11-03 20:31:56 +08:00
getObjectStream : ( bucket : string , key : string ) => Promise < S3StreamObject >
uploadStream : ( params : UploadStreamParams ) => Promise < void >
2026-07-30 08:29:18 +08:00
copyObject : (
2026-05-24 20:15:55 +08:00
sourceBucket : string ,
sourceKey : string ,
destBucket : string ,
destKey : string ,
2026-07-30 08:29:18 +08:00
) => Promise < void >
downloadToFile : ( bucket : string , key : string , filePath : string ) => Promise < void >
deleteObject : ( bucket : string , key : string ) => Promise < number >
deletePrefix : ( bucket : string , prefix : string ) => Promise < number >
headObject : ( bucket : string , key : string ) => Promise < ObjectInfo >
listObjects : ( bucket : string , prefix : string ) => Promise < string [] >
uploadFile : ( filePath : string , contentType : string ) => Promise < string >
uploadFileToKey : ( filePath : string , key : string , contentType : string ) => Promise < void >
2026-08-09 16:39:15 +08:00
presign : (
bucket : string ,
key : string ,
method : string ,
download? : boolean ,
filename? : string ,
2026-10-19 15:35:08 +08:00
internal? : boolean ,
2026-11-05 20:49:38 +08:00
/** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h) for PUT, or PRESIGNED_URL_EXPIRES_IN (5h) for GET, or DEFAULT_LOCAL_GET_EXPIRY_SECONDS (12h) for local. */
2026-10-27 08:09:10 +08:00
expiresInSeconds? : number ,
2026-08-09 16:39:15 +08:00
) => Promise < string >
2026-09-07 16:49:00 +08:00
presignMultipart : (
bucket : string ,
key : string ,
request : S3SignRequest ,
) => Promise < { url : string } >
abortMultipartUpload : ( bucket : string , key : string , uploadId : string ) => Promise < void >
2026-09-08 10:17:15 +08:00
resolveInput : ( bucket : string , key : string ) => Promise < string >
2026-11-05 09:57:34 +08:00
getStoragePath : ( bucket : string , key : string ) => string
2026-05-19 16:05:09 +08:00
}
export class S3StorageService implements S3Service {
private client : S3Client
2026-10-19 15:35:08 +08:00
private presignClient : S3Client
2026-05-19 16:05:09 +08:00
private bucket : string
2026-06-08 14:52:56 +08:00
private presignCache = new LruTtlCache < string , string >( 50000 )
2026-05-19 16:05:09 +08:00
constructor (
endpoint : string ,
accessKeyId : string ,
secretAccessKey : string ,
bucket : string ,
region : string = 'auto' ,
2026-10-19 15:35:08 +08:00
publicEndpoint? : string ,
2026-05-19 16:05:09 +08:00
) {
this . client = new S3Client ({
region ,
2026-07-06 10:05:42 +08:00
endpoint ,
2026-09-07 16:49:00 +08:00
credentials : {
accessKeyId ,
secretAccessKey ,
},
forcePathStyle : true ,
requestChecksumCalculation : 'WHEN_REQUIRED' ,
responseChecksumValidation : 'WHEN_REQUIRED' ,
2026-05-19 16:05:09 +08:00
})
2026-10-19 15:35:08 +08:00
this . presignClient =
publicEndpoint && publicEndpoint !== endpoint
? new S3Client ({
region ,
endpoint : publicEndpoint ,
credentials : {
accessKeyId ,
secretAccessKey ,
},
forcePathStyle : true ,
requestChecksumCalculation : 'WHEN_REQUIRED' ,
responseChecksumValidation : 'WHEN_REQUIRED' ,
})
: this . client
2026-05-19 16:05:09 +08:00
this . bucket = bucket
}
async getObjectSize ( bucket : string , key : string ) : Promise < number > {
2026-09-07 16:49:00 +08:00
const res = await this . client . send ( new HeadObjectCommand ({ Bucket : bucket , Key : key }))
return res . ContentLength ?? 0
2026-05-19 16:05:09 +08:00
}
async putObject (
bucket : string ,
key : string ,
2026-09-07 16:49:00 +08:00
body : Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS . ReadableStream ,
size : number ,
2026-05-19 16:05:09 +08:00
contentType? : string ,
) : Promise < void > {
2026-09-07 16:49:00 +08:00
let payload : string | Uint8Array | Buffer | NodeJS . ReadableStream = ''
if ( body && typeof body === 'object' && 'getReader' in body ) {
// Convert web ReadableStream to Node stream without buffering into memory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload = Readable . fromWeb ( body as any )
} else if ( body && typeof body === 'object' && 'pipe' in body ) {
payload = body as NodeJS . ReadableStream
} else if ( body instanceof ArrayBuffer ) {
payload = Buffer . from ( body )
} else if ( typeof body === 'string' || body instanceof Uint8Array || Buffer . isBuffer ( body )) {
payload = body
}
await this . client . send (
new PutObjectCommand ({
Bucket : bucket ,
Key : key ,
// AWS SDK v3 PutObjectCommandInput types differ slightly between Node and Web streams
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Body : payload as any ,
ContentLength : size > 0 ? size : undefined ,
ContentType : contentType ,
}),
)
2026-05-19 16:05:09 +08:00
}
async getObject ( bucket : string , key : string ) : Promise < S3Object > {
2026-09-07 16:49:00 +08:00
const res = await this . client . send ( new GetObjectCommand ({ Bucket : bucket , Key : key }))
const bytes = await res . Body ? . transformToByteArray ()
const buffer = bytes ? Buffer . from ( bytes ) : Buffer . alloc ( 0 )
let contentType = res . ContentType
2026-07-28 14:28:41 +08:00
if ( ! contentType || contentType === 'application/octet-stream' ) {
const detected = detectSupportedMimeType ( buffer )
if ( detected ) {
contentType = detected
} else {
const fileType = Bun . file ( key ). type
if ( fileType && fileType !== 'application/octet-stream' ) {
contentType = fileType
}
}
}
2026-05-19 16:05:09 +08:00
return {
2026-07-28 14:28:41 +08:00
buffer ,
contentType : contentType || 'application/octet-stream' ,
2026-05-19 16:05:09 +08:00
}
}
2026-11-03 20:31:56 +08:00
async getObjectStream ( bucket : string , key : string ) : Promise < S3StreamObject > {
const res = await this . client . send ( new GetObjectCommand ({ Bucket : bucket , Key : key }))
return {
stream : bodyToWebReadableStream ( res . Body ),
contentLength : res.ContentLength ,
contentType : res.ContentType || Bun . file ( key ). type || 'application/octet-stream' ,
}
}
async uploadStream ( params : UploadStreamParams ) : Promise < void > {
await uploadStreamToS3Client ( this . client , params )
}
2026-05-24 20:15:55 +08:00
async copyObject (
sourceBucket : string ,
sourceKey : string ,
destBucket : string ,
destKey : string ,
) : Promise < void > {
2026-09-07 16:49:00 +08:00
await this . client . send (
new CopyObjectCommand ({
CopySource : ` ${ sourceBucket } / ${ sourceKey } ` ,
Bucket : destBucket ,
Key : destKey ,
}),
)
2026-05-24 20:15:55 +08:00
}
2026-05-19 16:05:09 +08:00
async downloadToFile ( bucket : string , key : string , filePath : string ) : Promise < void > {
2026-09-07 19:33:13 +08:00
const dir = path . dirname ( filePath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
2026-09-07 16:49:00 +08:00
const res = await this . client . send ( new GetObjectCommand ({ Bucket : bucket , Key : key }))
2026-09-07 19:33:13 +08:00
if ( ! res . Body ) {
return
}
2026-09-08 14:52:37 +08:00
const writeStream = fs . createWriteStream ( filePath )
2026-09-07 19:33:13 +08:00
try {
2026-09-08 14:52:37 +08:00
await pipeline ( res . Body as unknown as NodeJS . ReadableStream , writeStream )
2026-09-07 19:33:13 +08:00
} catch ( err ) {
2026-09-08 14:52:37 +08:00
if ( ! writeStream . closed ) {
await new Promise (( resolve ) => writeStream . once ( 'close' , resolve ))
}
2026-09-07 19:33:13 +08:00
await fs . promises . unlink ( filePath ). catch (() => {})
throw err
2026-09-07 16:49:00 +08:00
}
2026-05-19 16:05:09 +08:00
}
2026-05-24 09:24:44 +08:00
async deleteObject ( bucket : string , key : string ) : Promise < number > {
try {
2026-09-07 16:49:00 +08:00
await this . client . send ( new DeleteObjectCommand ({ Bucket : bucket , Key : key }))
2026-05-24 09:24:44 +08:00
return 1
2026-11-03 20:31:56 +08:00
} catch ( err : unknown ) {
if ( isS3NotFoundError ( err )) {
return 0
}
throw err
2026-05-24 09:24:44 +08:00
}
2026-05-23 18:09:30 +08:00
}
2026-05-24 09:24:44 +08:00
async deletePrefix ( bucket : string , prefix : string ) : Promise < number > {
2026-05-24 09:18:58 +08:00
const keys = await this . listObjects ( bucket , prefix )
2026-09-07 16:49:00 +08:00
if ( keys . length === 0 ) return 0
const chunkSize = 1000
for ( let i = 0 ; i < keys . length ; i += chunkSize ) {
const batch = keys . slice ( i , i + chunkSize )
await this . client . send (
new DeleteObjectsCommand ({
Bucket : bucket ,
Delete : {
Objects : batch.map (( k ) => ({ Key : k })),
Quiet : true ,
},
}),
)
2026-05-24 09:18:58 +08:00
}
2026-05-24 09:24:44 +08:00
return keys . length
2026-05-24 09:18:58 +08:00
}
2026-05-19 16:05:09 +08:00
async headObject ( bucket : string , key : string ) : Promise < ObjectInfo > {
2026-09-07 16:49:00 +08:00
try {
const res = await this . client . send ( new HeadObjectCommand ({ Bucket : bucket , Key : key }))
return {
key ,
size : res.ContentLength ?? 0 ,
lastModified : res.LastModified ?? new Date (),
contentType : res.ContentType || 'application/octet-stream' ,
eTag : res.ETag || '' ,
}
} catch ( err : unknown ) {
2026-11-03 20:31:56 +08:00
if ( isS3NotFoundError ( err )) {
throw new Error ( `NoSuchKey: The specified key does not exist.` , { cause : err })
}
throw err
2026-05-19 16:05:09 +08:00
}
}
async listObjects ( bucket : string , prefix : string ) : Promise < string [] > {
const keys : string [] = []
let isTruncated = true
let continuationToken : string | undefined = undefined
while ( isTruncated ) {
2026-09-07 16:49:00 +08:00
const response : ListObjectsV2CommandOutput = await this . client . send (
new ListObjectsV2Command ({
Bucket : bucket ,
Prefix : prefix ,
ContinuationToken : continuationToken ,
}),
)
2026-05-19 16:05:09 +08:00
2026-09-07 16:49:00 +08:00
if ( response . Contents ) {
for ( const item of response . Contents ) {
if ( item . Key ) {
keys . push ( item . Key )
2026-05-19 16:05:09 +08:00
}
}
}
2026-09-07 16:49:00 +08:00
isTruncated = response . IsTruncated || false
continuationToken = response . NextContinuationToken
2026-05-19 16:05:09 +08:00
}
return keys
}
async uploadFile ( filePath : string , contentType : string ) : Promise < string > {
const key = ulid () + path . extname ( filePath )
await this . uploadFileToKey ( filePath , key , contentType )
return key
}
async uploadFileToKey ( filePath : string , key : string , contentType : string ) : Promise < void > {
2026-09-07 16:49:00 +08:00
const file = Bun . file ( filePath )
const stream = fs . createReadStream ( filePath )
await this . client . send (
new PutObjectCommand ({
Bucket : this.bucket ,
Key : key ,
Body : stream ,
ContentLength : file.size ,
ContentType : contentType ,
}),
)
2026-05-19 16:05:09 +08:00
}
2026-08-09 16:39:15 +08:00
async presign (
bucket : string ,
key : string ,
method : string ,
download? : boolean ,
filename? : string ,
2026-10-19 15:35:08 +08:00
internal? : boolean ,
2026-10-27 08:09:10 +08:00
expiresInSeconds? : number ,
2026-08-09 16:39:15 +08:00
) : Promise < string > {
2026-10-30 16:06:34 +08:00
const defaultExpireHours =
method === 'PUT'
? parseInt (
process . env . PRESIGNED_UPLOAD_URL_EXPIRES_IN ||
process . env . PRESIGNED_URL_EXPIRES_IN ||
'12' ,
10 ,
)
: parseInt ( process . env . PRESIGNED_URL_EXPIRES_IN || '5' , 10 )
const lifetimeSeconds = expiresInSeconds ?? defaultExpireHours * 3600
2026-10-27 08:09:10 +08:00
// With an explicit (usually short) lifetime, only reuse a cached URL while it has at
// least half of its lifetime left, so callers never receive a nearly expired link.
const cacheTtlMs = expiresInSeconds ? ( lifetimeSeconds * 1000 ) / 2 : lifetimeSeconds * 1000
2026-06-08 14:52:56 +08:00
2026-10-27 08:09:10 +08:00
const cacheKey = ` ${ bucket } / ${ key } ?download= ${ download || false } &filename= ${ filename || '' } &internal= ${ internal || false } &expires= ${ expiresInSeconds ?? 'default' } `
2026-07-02 15:26:10 +08:00
if ( method === 'GET' && ! download ) {
2026-06-08 14:52:56 +08:00
const cached = this . presignCache . get ( cacheKey )
2026-09-07 16:49:00 +08:00
if ( cached ) {
return cached
}
2026-06-08 14:52:56 +08:00
}
2026-10-19 15:35:08 +08:00
const signingClient = internal ? this . client : this.presignClient
2026-09-07 16:49:00 +08:00
let url : string
2026-05-19 16:05:09 +08:00
2026-09-07 16:49:00 +08:00
if ( method === 'GET' ) {
const command = new GetObjectCommand ({
Bucket : bucket ,
Key : key ,
ResponseContentDisposition : download ? buildContentDisposition ( filename ) : undefined ,
})
2026-10-27 08:09:10 +08:00
url = await getSignedUrl ( signingClient , command , { expiresIn : lifetimeSeconds })
2026-09-07 16:49:00 +08:00
} else if ( method === 'PUT' ) {
const command = new PutObjectCommand ({
Bucket : bucket ,
Key : key ,
})
2026-10-27 08:09:10 +08:00
url = await getSignedUrl ( signingClient , command , { expiresIn : lifetimeSeconds })
2026-09-07 16:49:00 +08:00
} else if ( method === 'DELETE' ) {
const command = new DeleteObjectCommand ({
Bucket : bucket ,
Key : key ,
})
2026-10-27 08:09:10 +08:00
url = await getSignedUrl ( signingClient , command , { expiresIn : lifetimeSeconds })
2026-09-07 16:49:00 +08:00
} else {
throw new Error ( `Unsupported method for presign: ${ method } ` )
2026-06-08 19:35:46 +08:00
}
2026-07-02 15:26:10 +08:00
if ( method === 'GET' && ! download ) {
2026-06-08 14:52:56 +08:00
this . presignCache . set ( cacheKey , url , cacheTtlMs )
}
return url
2026-05-19 16:05:09 +08:00
}
2026-09-07 16:49:00 +08:00
async presignMultipart (
bucket : string ,
key : string ,
request : S3SignRequest ,
) : Promise < { url : string } > {
2026-10-30 16:06:34 +08:00
const expireHours = parseInt (
process . env . PRESIGNED_UPLOAD_URL_EXPIRES_IN || process . env . PRESIGNED_URL_EXPIRES_IN || '12' ,
10 ,
)
2026-09-07 16:49:00 +08:00
const expiresInSeconds = expireHours * 3600
let url : string
if ( request . method === 'PUT' ) {
if ( request . uploadId && request . partNumber != null ) {
const command = new UploadPartCommand ({
Bucket : bucket ,
Key : key ,
UploadId : request.uploadId ,
PartNumber : request.partNumber ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
} else {
const command = new PutObjectCommand ({
Bucket : bucket ,
Key : key ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
}
} else if ( request . method === 'POST' ) {
if ( request . uploadId ) {
const command = new CompleteMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
UploadId : request.uploadId ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
} else {
const command = new CreateMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
}
} else if ( request . method === 'GET' ) {
if ( ! request . uploadId ) {
throw new Error ( 'List parts requires uploadId' )
}
const command = new ListPartsCommand ({
Bucket : bucket ,
Key : key ,
UploadId : request.uploadId ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
} else if ( request . method === 'DELETE' ) {
if ( ! request . uploadId ) {
throw new Error ( 'Abort multipart upload requires uploadId' )
}
const command = new AbortMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
UploadId : request.uploadId ,
})
2026-10-19 15:35:08 +08:00
url = await getSignedUrl ( this . presignClient , command , { expiresIn : expiresInSeconds })
2026-09-07 16:49:00 +08:00
} else {
throw new Error ( `Unsupported method for presignMultipart: ${ request . method } ` )
}
return { url }
}
async abortMultipartUpload ( bucket : string , key : string , uploadId : string ) : Promise < void > {
await this . client . send (
new AbortMultipartUploadCommand ({
Bucket : bucket ,
Key : key ,
UploadId : uploadId ,
}),
)
}
2026-09-08 10:17:15 +08:00
async resolveInput ( bucket : string , key : string ) : Promise < string > {
2026-10-19 15:35:08 +08:00
return this . presign ( bucket , key , 'GET' , false , undefined , true )
2026-09-08 10:17:15 +08:00
}
2026-11-05 09:57:34 +08:00
getStoragePath ( bucket : string , key : string ) : string {
return `s3:// ${ bucket } / ${ key } `
}
2026-05-19 16:05:09 +08:00
}
export class LocalStorageService implements S3Service {
private basePath : string
private endpoint : string
2026-11-05 20:49:38 +08:00
private presignCache = new LruTtlCache < string , string >( 50000 )
2026-05-19 16:05:09 +08:00
2026-05-24 09:36:23 +08:00
constructor ( endpoint : string , basePath : string = 'data' ) {
2026-05-19 16:05:09 +08:00
this . endpoint = endpoint . replace ( /\/$/ , '' )
this . basePath = path . resolve ( basePath )
if ( ! fs . existsSync ( this . basePath )) {
fs . mkdirSync ( this . basePath , { recursive : true })
}
}
private getFilePath ( bucket : string , key : string ) : string {
const filePath = path . join ( this . basePath , bucket , key )
if ( ! filePath . startsWith ( this . basePath )) {
throw new Error ( `Invalid path: potential path traversal detected` )
}
return filePath
}
async getObjectSize ( bucket : string , key : string ) : Promise < number > {
const filePath = this . getFilePath ( bucket , key )
try {
const stats = await fs . promises . stat ( filePath )
return stats . size
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
2026-06-07 11:10:27 +08:00
throw new Error ( `NoSuchKey: The specified key does not exist.` , { cause : e })
2026-05-19 16:05:09 +08:00
}
throw e
}
}
async putObject (
bucket : string ,
key : string ,
2026-09-07 19:33:13 +08:00
body : Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS . ReadableStream ,
2026-05-19 16:05:09 +08:00
_size : number , // eslint-disable-line @typescript-eslint/no-unused-vars
_contentType? : string , // eslint-disable-line @typescript-eslint/no-unused-vars
) : Promise < void > {
const filePath = this . getFilePath ( bucket , key )
const dir = path . dirname ( filePath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
2026-07-29 21:22:49 +08:00
2026-09-07 19:33:13 +08:00
if (
body &&
typeof body === 'object' &&
( 'pipe' in body || 'getReader' in body || Symbol . asyncIterator in body )
) {
try {
await pipeline ( body as unknown as NodeJS . ReadableStream , fs . createWriteStream ( filePath ))
} catch ( err ) {
await fs . promises . unlink ( filePath ). catch (() => {})
throw err
2026-07-29 21:22:49 +08:00
}
} else {
2026-07-29 21:32:53 +08:00
await Bun . write ( filePath , body )
2026-07-29 21:22:49 +08:00
}
2026-05-19 16:05:09 +08:00
}
async getObject ( bucket : string , key : string ) : Promise < S3Object > {
const filePath = this . getFilePath ( bucket , key )
try {
const buffer = await fs . promises . readFile ( filePath )
return {
buffer ,
contentType : Bun.file ( filePath ). type || 'application/octet-stream' ,
}
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
2026-06-07 11:10:27 +08:00
throw new Error ( `NoSuchKey: The specified key does not exist.` , { cause : e })
2026-05-19 16:05:09 +08:00
}
throw e
}
}
2026-11-03 20:31:56 +08:00
async getObjectStream ( bucket : string , key : string ) : Promise < S3StreamObject > {
const filePath = this . getFilePath ( bucket , key )
try {
const stats = await fs . promises . stat ( filePath )
const nodeStream = fs . createReadStream ( filePath )
return {
stream : Readable.toWeb ( nodeStream ) as unknown as ReadableStream < Uint8Array >,
contentLength : stats.size ,
contentType : Bun.file ( filePath ). type || 'application/octet-stream' ,
}
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
throw new Error ( `NoSuchKey: The specified key does not exist.` , { cause : e })
}
throw e
}
}
async uploadStream ( params : UploadStreamParams ) : Promise < void > {
const filePath = this . getFilePath ( params . bucket , params . key )
await writeStreamToLocalFile ( filePath , params . stream )
}
2026-05-24 20:15:55 +08:00
async copyObject (
sourceBucket : string ,
sourceKey : string ,
destBucket : string ,
destKey : string ,
) : Promise < void > {
const srcPath = this . getFilePath ( sourceBucket , sourceKey )
const destPath = this . getFilePath ( destBucket , destKey )
const dir = path . dirname ( destPath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
await fs . promises . copyFile ( srcPath , destPath )
}
2026-05-19 16:05:09 +08:00
async downloadToFile ( bucket : string , key : string , filePath : string ) : Promise < void > {
2026-09-07 19:33:13 +08:00
const dir = path . dirname ( filePath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
2026-05-19 16:05:09 +08:00
const srcPath = this . getFilePath ( bucket , key )
await fs . promises . copyFile ( srcPath , filePath )
}
2026-05-24 09:24:44 +08:00
async deleteObject ( bucket : string , key : string ) : Promise < number > {
2026-05-23 18:09:30 +08:00
const filePath = this . getFilePath ( bucket , key )
try {
await fs . promises . unlink ( filePath )
2026-05-24 09:24:44 +08:00
return 1
2026-05-23 18:09:30 +08:00
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
// Ignore if file doesn't exist
2026-05-24 09:24:44 +08:00
return 0
2026-05-23 18:09:30 +08:00
}
throw e
}
}
2026-05-24 09:24:44 +08:00
async deletePrefix ( bucket : string , prefix : string ) : Promise < number > {
// Get count of files before deleting
const keys = await this . listObjects ( bucket , prefix )
if ( keys . length === 0 ) return 0
2026-05-24 09:18:58 +08:00
const dirPath = this . getFilePath ( bucket , prefix )
try {
await fs . promises . rm ( dirPath , { recursive : true , force : true })
2026-05-24 09:24:44 +08:00
return keys . length
2026-05-24 09:18:58 +08:00
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
2026-05-24 09:24:44 +08:00
return 0
2026-05-24 09:18:58 +08:00
}
throw e
}
}
2026-05-19 16:05:09 +08:00
async headObject ( bucket : string , key : string ) : Promise < ObjectInfo > {
const filePath = this . getFilePath ( bucket , key )
try {
const stats = await fs . promises . stat ( filePath )
// Simple hash to simulate ETag
const hash = crypto
. createHash ( 'md5' )
. update ( filePath + stats . mtimeMs )
. digest ( 'hex' )
return {
key ,
size : stats.size ,
lastModified : stats.mtime ,
contentType : Bun.file ( key ). type || 'application/octet-stream' ,
eTag : `" ${ hash } "` ,
}
} catch ( e : unknown ) {
if ( e instanceof Error && ( e as NodeJS . ErrnoException ). code === 'ENOENT' ) {
2026-06-07 11:10:27 +08:00
throw new Error ( `NoSuchKey: The specified key does not exist.` , { cause : e })
2026-05-19 16:05:09 +08:00
}
throw e
}
}
async listObjects ( bucket : string , prefix : string ) : Promise < string [] > {
const bucketDir = path . join ( this . basePath , bucket )
const keys : string [] = []
if ( ! fs . existsSync ( bucketDir )) {
return keys
}
const walkDir = async ( currentDir : string ) => {
const files = await fs . promises . readdir ( currentDir )
for ( const file of files ) {
const fullPath = path . join ( currentDir , file )
const stat = await fs . promises . stat ( fullPath )
if ( stat . isDirectory ()) {
await walkDir ( fullPath )
} else {
// Get relative path from bucket dir
const relPath = path . relative ( bucketDir , fullPath )
// Normalise separators
const key = relPath . split ( path . sep ). join ( '/' )
if ( key . startsWith ( prefix )) {
keys . push ( key )
}
}
}
}
await walkDir ( bucketDir )
return keys
}
async uploadFile ( filePath : string , contentType : string ) : Promise < string > {
const key = ulid () + path . extname ( filePath )
await this . uploadFileToKey ( filePath , key , contentType )
return key
}
async uploadFileToKey (
filePath : string ,
key : string ,
_contentType : string , // eslint-disable-line @typescript-eslint/no-unused-vars
) : Promise < void > {
// using a default bucket for direct upload, or the user has to supply it
// S3StorageService uses this.bucket
const bucket = process . env . S3_BUCKET || 'shumai'
const destPath = this . getFilePath ( bucket , key )
const dir = path . dirname ( destPath )
if ( ! fs . existsSync ( dir )) {
fs . mkdirSync ( dir , { recursive : true })
}
await fs . promises . copyFile ( filePath , destPath )
}
2026-08-09 16:39:15 +08:00
async presign (
bucket : string ,
key : string ,
method : string ,
download? : boolean ,
filename? : string ,
2026-11-05 20:49:38 +08:00
_internal? : boolean ,
expiresInSeconds? : number ,
2026-08-09 16:39:15 +08:00
) : Promise < string > {
2026-05-19 16:05:09 +08:00
if ( method !== 'GET' && method !== 'PUT' ) {
throw new Error ( `Invalid method: ${ method } ` )
}
if ( method === 'PUT' ) {
return ` ${ this . endpoint }${ signLocalUrl ( bucket , key ) } `
}
2026-11-05 20:49:38 +08:00
const lifetimeSeconds = expiresInSeconds ?? DEFAULT_LOCAL_GET_EXPIRY_SECONDS
const cacheTtlMs = ( lifetimeSeconds * 1000 ) / 2
const cacheKey = ` ${ bucket } / ${ key } ?download= ${ download || false } &filename= ${ filename || '' } &expires= ${ expiresInSeconds ?? 'default' } `
if ( method === 'GET' && ! download ) {
const cached = this . presignCache . get ( cacheKey )
if ( cached ) {
return cached
}
}
const { signature , expires } = signLocalGetUrl ( bucket , key , lifetimeSeconds )
let url = ` ${ this . endpoint } /files/ ${ bucket } / ${ key } ?Signature= ${ signature } &Expires= ${ expires } `
2026-07-02 15:26:10 +08:00
if ( download ) {
2026-11-05 20:49:38 +08:00
url += '&download=1'
2026-08-09 16:39:15 +08:00
if ( filename ) {
url += `&filename= ${ encodeURIComponent ( filename ) } `
}
2026-06-08 19:35:46 +08:00
}
2026-11-05 20:49:38 +08:00
if ( method === 'GET' && ! download ) {
this . presignCache . set ( cacheKey , url , cacheTtlMs )
}
2026-06-08 19:35:46 +08:00
return url
2026-05-19 16:05:09 +08:00
}
2026-09-07 16:49:00 +08:00
async presignMultipart (
bucket : string ,
key : string ,
request : S3SignRequest ,
) : Promise < { url : string } > {
if ( request . method === 'PUT' ) {
return { url : ` ${ this . endpoint }${ signLocalUrl ( bucket , key ) } ` }
}
const url = await this . presign ( bucket , key , request . method )
return { url }
}
async abortMultipartUpload (
bucket : string ,
key : string ,
_uploadId : string , // eslint-disable-line @typescript-eslint/no-unused-vars
) : Promise < void > {
await this . deleteObject ( bucket , key )
}
2026-09-08 10:17:15 +08:00
async resolveInput ( bucket : string , key : string ) : Promise < string > {
const filePath = this . getFilePath ( bucket , key )
if ( fs . existsSync ( filePath )) {
return filePath
}
return this . presign ( bucket , key , 'GET' )
}
2026-11-05 09:57:34 +08:00
getStoragePath ( bucket : string , key : string ) : string {
return this . getFilePath ( bucket , key )
}
2026-05-19 16:05:09 +08:00
}
2026-09-07 16:49:00 +08:00
export function getStorageBackend () : 's3' | 'local' {
return ( process . env . STORAGE_BACKEND as 's3' | 'local' ) || 'local'
}
const storageBackend = getStorageBackend ()
2026-06-18 10:22:16 +08:00
const port = process . env . SHUMAI_SERVER_PORT || '3000'
2026-06-25 18:46:14 +08:00
const s3Endpoint = process . env . AWS_ENDPOINT_URL_S3 || `http://localhost: ${ port } `
2026-10-19 15:35:08 +08:00
const s3PublicEndpoint =
process . env . AWS_PUBLIC_ENDPOINT_URL_S3 || process . env . S3_PUBLIC_ENDPOINT || undefined
2026-05-19 16:05:09 +08:00
export const s3Service : S3Service =
storageBackend === 's3'
? new S3StorageService (
s3Endpoint ,
process . env . S3_ACCESS_KEY_ID || 'minioadmin' ,
process . env . S3_SECRET_ACCESS_KEY || 'minioadmin' ,
process . env . S3_BUCKET || 'shumai' ,
process . env . S3_REGION || 'auto' ,
2026-10-19 15:35:08 +08:00
s3PublicEndpoint ,
2026-05-19 16:05:09 +08:00
)
2026-06-25 18:46:14 +08:00
: new LocalStorageService ( s3Endpoint )