import { getConfig } from './config' import { sha256Hex, signRequest } from './sigv4' /** * 极简 S3 客户端(RustFS / S3 v4 兼容,零第三方依赖)。 * 手写 AWS SigV4 签名:putObject / getObject / deleteObject / listObjectsV2。 * 配置来自 env(NUXT_OSS_*),凭据绝不写入仓库。 */ export interface OssConfig { endpoint: string accessKey: string secretKey: string bucket: string region: string publicBase: string } export function getOssConfig(): OssConfig | null { const { oss } = getConfig() if (!oss.endpoint || !oss.accessKey || !oss.secretKey || !oss.bucket) return null return oss } export const isOssConfigured = (): boolean => getOssConfig() !== null const encodeKey = (key: string) => key.split('/').map(encodeURIComponent).join('/') const qs = (q: Record) => { const s = Object.keys(q) .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(q[k]))}`) .join('&') return s ? `?${s}` : '' } async function s3Request( method: string, key: string, opts: { query?: Record; body?: string | Buffer; contentType?: string; isList?: boolean } = {}, ): Promise { const cfg = getOssConfig() if (!cfg) throw new Error('OSS 未配置') const path = opts.isList ? `/${cfg.bucket}` : `/${cfg.bucket}/${encodeKey(key)}` const body = opts.body ?? '' const bodyHash = sha256Hex(body) const date = new Date().toISOString() const headers: Record = { host: cfg.endpoint, 'x-amz-content-sha256': bodyHash, ...(opts.contentType ? { 'content-type': opts.contentType } : {}), } const { authorization, amzDate } = signRequest({ method, path, query: opts.query ?? {}, headers, bodyHash, date, accessKey: cfg.accessKey, secretKey: cfg.secretKey, region: cfg.region, }) headers['x-amz-date'] = amzDate const url = `https://${cfg.endpoint}${path}${qs(opts.query ?? {})}` return fetch(url, { method, headers: { ...headers, authorization }, body: method === 'GET' || method === 'DELETE' ? undefined : body, }) } // ---------- 对象操作 ---------- export async function putObject(key: string, body: Buffer, contentType: string): Promise { const res = await s3Request('PUT', key, { body, contentType }) if (!res.ok) throw new Error(`OSS 上传失败: ${res.status}`) return key } export async function getObject(key: string): Promise { const res = await s3Request('GET', key) if (res.status === 404) return null if (!res.ok) throw new Error(`OSS 读取失败: ${res.status}`) return res } export async function deleteObject(key: string): Promise { const res = await s3Request('DELETE', key) return res.ok || res.status === 204 } export interface OssFile { name: string size: number modified: string url: string } export async function listObjectsV2(prefix = ''): Promise { const res = await s3Request('GET', '', { isList: true, query: { 'list-type': '2', prefix, 'max-keys': '1000' }, }) if (!res.ok) throw new Error(`OSS 列表失败: ${res.status}`) const xml = await res.text() const files: OssFile[] = [] const contentRe = /([\s\S]*?)<\/Contents>/g let m: RegExpExecArray | null while ((m = contentRe.exec(xml))) { const item = m[1] const name = /([\s\S]*?)<\/Key>/.exec(item)?.[1] if (!name) continue const size = Number(/([\s\S]*?)<\/Size>/.exec(item)?.[1] || 0) const modified = /([\s\S]*?)<\/LastModified>/.exec(item)?.[1] || '' files.push({ name, size, modified, url: `/uploads/${encodeKey(name)}` }) } files.sort((a, b) => b.modified.localeCompare(a.modified)) return files }