mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 23:54:25 +00:00
Compare commits
6
Commits
e02cbddb14
..
v0.6.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c0b887b8d | ||
|
|
f304caea00 | ||
|
|
65e2ac1383 | ||
|
|
0dc0bbeb03 | ||
|
|
2ecbd49d18 | ||
|
|
ba3c6dbfee |
+14
-1
@@ -8,14 +8,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
## [0.6.4] - 2026-11-05
|
||||
|
||||
### Added
|
||||
|
||||
- **storage**: Add optional archive storage support (`local` folder/NAS or `s3` with configurable storage class and Glacier restore) allowing editors and owners to archive and restore original files while keeping previews, proxy streams, comments, and metadata available in main storage
|
||||
- **storage**: Add team-level automatic asset archival based on age policies (creation time or last modified time) with configurable post-restore grace periods, an hourly background scanning worker, and a dedicated Storage settings page displaying read-only archive backend status and policy configurations
|
||||
|
||||
### Fixed
|
||||
|
||||
- **asset**: Fix an issue where version cards in the manage versions dialog horizontally overflowed when containing long file names
|
||||
- **security**: ⚠️ Several security improvements and access control hardenings. Upgrading to this release is strongly recommended.
|
||||
- **mcp**: Gracefully disable MCP OAuth 2.1 with an error log when deploying on remote HTTP IP addresses without breaking the main server or API token MCP access
|
||||
- **web**: Add immutable cache headers and conditional 304 Not Modified support for production JavaScript and CSS chunks to prevent unnecessary refetches on page reload
|
||||
|
||||
### Changed
|
||||
|
||||
- **file-browser**: Replace the legacy combined "Copy name and download link" action with a context-aware Copy submenu in file browser context menus and card action dropdowns, enabling users to copy image, asset names, in-app links, download links, IDs, Markdown links and storage paths(team-owner only)
|
||||
|
||||
## [0.6.3] - 2026-11-01
|
||||
|
||||
### Added
|
||||
|
||||
@@ -30,6 +30,8 @@ RUN bun run scripts/extract-runtime-deps.ts
|
||||
# Stage 2: Runner
|
||||
FROM oven/bun:1.4.4 AS runner
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Install system dependencies and Jellyfin-FFmpeg (with VA-API support)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
python3 \
|
||||
|
||||
@@ -25,6 +25,8 @@ RUN bun run scripts/extract-runtime-deps.ts
|
||||
# Stage 2: Runner
|
||||
FROM oven/bun:1.4.4 AS runner
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Install transcoding system dependencies and Jellyfin-FFmpeg (with VA-API/hardware acceleration support)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl \
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
Shumai is an open-source Frame.io alternative built for creative teams to collaborate and share media with ease:
|
||||
|
||||
* **S3-Compatible & Local Storage**: Store and serve creative assets securely using the local filesystem or any S3-compatible storage service, including AWS S3, Cloudflare R2, and MinIO.
|
||||
* **Cold Archive Storage**: Offload original master media files to secondary local storage (e.g. NAS) or cold S3 storage classes (e.g. AWS S3 Glacier, Google Cloud Storage Coldline) to save on storage costs while keeping proxies, previews, and metadata hot for instant browsing and playback. See [Archive Storage documentation](https://docs.shumai.one/configuration/archive-storage).
|
||||
* **Archive Storage & Auto-Archival**: Offload original master media files to secondary local storage or cold S3 storage—manually or automatically via team lifecycle policies—to save on storage costs while keeping proxies for instant browsing and playback. See [Archive Storage documentation](https://docs.shumai.one/configuration/archive-storage).
|
||||
* **Frame-by-Frame Annotations & Comments**: Leave precise feedback with frame-specific drawing tools and timestamped comments on both video and image assets.
|
||||
* **Secure Sharing & Collections**: Create private share links and curated media collections for clients, stakeholders, and collaborators.
|
||||
* **Granular Access Control**: Manage workspace permissions with team-level and project-level role-based access control.
|
||||
@@ -109,7 +109,7 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
|
||||
> By default, the Docker Compose setups use CPU software transcoding. If your server has a GPU (NVIDIA NVENC, Intel QuickSync, AMD/Intel VA-API, or Rockchip RKMPP) and you want to enable GPU hardware acceleration, check the [Hardware Transcoding Guide](https://docs.shumai.one/configuration/hardware-transcoding).
|
||||
3. Configure environment variables:
|
||||
|
||||
* `BETTER_AUTH_URL`: The public base URL of your Shumai server (e.g., `https://shumai.example.com` or `http://12.34.56.78:3000`). This is required for remote servers and production deployments.
|
||||
* `BETTER_AUTH_URL`: The public base URL of your Shumai server (e.g., `https://shumai.example.com` or `http://12.34.56.78:3000`). This is required for remote servers and production deployments. Note: Remote deployments must use HTTPS for MCP OAuth 2.1; if an HTTP IP address or domain is used, MCP OAuth 2.1 is gracefully disabled while the Web UI and MCP API tokens remain functional.
|
||||
* `AWS_ENDPOINT_URL_S3`: By default, `AWS_ENDPOINT_URL_S3` is set to `http://localhost:{SHUMAI_SERVER_PORT}`. When you use local storage (the default storage backend with `STORAGE_BACKEND: local`) and expose Shumai on a remote server, custom domain, or custom host/port combination, set `AWS_ENDPOINT_URL_S3` to the external URL that client browsers will use to upload and download files.
|
||||
|
||||
For example, if you change the port mapping in `docker-compose.yaml` from `3000:3000` to `12345:3000` and deploy on a server with IP address `12.34.56.78`, set:
|
||||
|
||||
+1
-1
@@ -127,7 +127,7 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
|
||||
|
||||
|
||||
3. 配置环境变量:
|
||||
* `BETTER_AUTH_URL`:Shumai 服务的外部公开访问地址(例如 `https://shumai.example.com` 或 `http://12.34.56.78:3000`)。在远程服务器或生产环境中部署时必须配置该变量。
|
||||
* `BETTER_AUTH_URL`:Shumai 服务的外部公开访问地址(例如 `https://shumai.example.com` 或 `http://12.34.56.78:3000`)。在远程服务器或生产环境中部署时必须配置该变量。注意:MCP OAuth 2.1 依赖 HTTPS(本地 loopback 除外);若远程部署使用 HTTP,系统会优雅禁用 MCP OAuth 2.1 并记录日志,Web UI 与基于 API Token 的 MCP 访问不受影响。
|
||||
* `AWS_ENDPOINT_URL_S3`:默认情况下指向 `http://localhost:{SHUMAI_SERVER_PORT}`。当你使用本地存储(即默认配置 `STORAGE_BACKEND: local`)并在远程服务器、自定义域名或自定义端口上公开访问 Shumai 时,请将 `AWS_ENDPOINT_URL_S3` 设置为客户端浏览器上传和下载文件所使用的外部 URL。
|
||||
|
||||
例如,如果你将 `docker-compose.yaml` 中的端口映射从 `3000:3000` 修改为了 `12345:3000`,且服务部署在 IP 为 `12.34.56.78` 的服务器上,请进行如下设置:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -99,6 +99,7 @@ apps/web/e2e/
|
||||
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Owner views a file and it appears in recents | `tests/project/recents.spec.ts` |
|
||||
| Owner archives a file to archive storage and restores it back to main storage | `tests/project/archive-restore.spec.ts` |
|
||||
| Owner opens Copy submenu in context menu and copies file name | `tests/project/copy-menu.spec.ts` |
|
||||
|
||||
### file
|
||||
| Test | File |
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner sees Copy submenu in context menu and copies file name', async ({
|
||||
file,
|
||||
browserName,
|
||||
}) => {
|
||||
const { page, projectId, fileName } = file
|
||||
|
||||
if (browserName === 'chromium') {
|
||||
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
|
||||
}
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, fileName)).toBeVisible()
|
||||
|
||||
// Right-click context menu
|
||||
await fileCard(page, fileName).click({ button: 'right' })
|
||||
const copySubTrigger = page.getByRole('menuitem', { name: /^Copy$|^复制$/i })
|
||||
await expect(copySubTrigger).toBeVisible()
|
||||
await copySubTrigger.click()
|
||||
|
||||
// Verify submenu items are visible
|
||||
await expect(page.getByRole('menuitem', { name: /^Name$|^名称$/i })).toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: /^Link$|^链接$/i })).toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: /^Download link$|^下载链接$/i })).toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: /^ID$/i })).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('menuitem', { name: /^Markdown link$|^Markdown 链接$/i }),
|
||||
).toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: /^Storage path$|^存储路径$/i })).toBeVisible()
|
||||
|
||||
// Click "Name"
|
||||
await page.getByRole('menuitem', { name: /^Name$|^名称$/i }).click()
|
||||
const toast = page.locator('[data-sonner-toast]').filter({
|
||||
hasText: /Copied name to clipboard|已复制名称到剪贴板/i,
|
||||
})
|
||||
await expect(toast).toBeVisible()
|
||||
|
||||
if (browserName === 'chromium') {
|
||||
const clipboardText = await page.evaluate(() => navigator.clipboard.readText())
|
||||
expect(clipboardText).toBe(fileName)
|
||||
}
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
+24
-13
@@ -20,6 +20,8 @@ import { authService } from '@shumai/core/src/auth/auth'
|
||||
import { embeddingService } from '@shumai/core/src/search/embedding-service'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
|
||||
import { autoArchiveJobService } from '@shumai/core/src/asset/auto-archive-job'
|
||||
import { createHtmlHandler, createStaticFileHandler } from './static'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
@@ -91,6 +93,7 @@ async function run() {
|
||||
await agentService.ensureSystemEmbeddingAgents().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
notificationJobService.start()
|
||||
autoArchiveJobService.start()
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = process.env.SHUMAI_WORKERS || 'all'
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -149,7 +152,8 @@ async function run() {
|
||||
for (const file of bundle.files) {
|
||||
const routePath = file.path.startsWith('.') ? file.path.slice(1) : file.path
|
||||
const filePath = join(import.meta.dir, file.path)
|
||||
routes[routePath] = () => new Response(Bun.file(filePath), { headers: file.headers })
|
||||
const isHtml = file.loader === 'html' || file.path.endsWith('.html')
|
||||
routes[routePath] = createStaticFileHandler(filePath, file.headers, !isHtml)
|
||||
}
|
||||
|
||||
const sampleFile = bundle.files[0]?.path || bundle.index || ''
|
||||
@@ -161,13 +165,14 @@ async function run() {
|
||||
const routePath = '/' + pdfWorkerFile
|
||||
const filePath = join(bundleDir, pdfWorkerFile)
|
||||
const bunFile = Bun.file(filePath)
|
||||
routes[routePath] = () =>
|
||||
new Response(bunFile, {
|
||||
headers: {
|
||||
'content-type': 'text/javascript;charset=utf-8',
|
||||
etag: `"${bunFile.size}-${bunFile.lastModified}"`,
|
||||
},
|
||||
})
|
||||
routes[routePath] = createStaticFileHandler(
|
||||
filePath,
|
||||
{
|
||||
'content-type': 'text/javascript;charset=utf-8',
|
||||
etag: `"${bunFile.size}-${bunFile.lastModified}"`,
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to register pdf.worker route:', err)
|
||||
@@ -183,16 +188,22 @@ async function run() {
|
||||
.replaceAll('href="./', 'href="/')
|
||||
.replaceAll('src="./', 'src="/')
|
||||
.replaceAll('content="./', 'content="/')
|
||||
const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
|
||||
const serveMainHtml = createHtmlHandler(mainHtmlText, mainHtmlHeaders)
|
||||
|
||||
routes['/'] = serveMainHtml
|
||||
routes['/*'] = serveMainHtml
|
||||
} else {
|
||||
const fallbackHtmlPath = join(import.meta.dir, 'shumai-app.html')
|
||||
const serveFallbackHtml = () =>
|
||||
new Response(Bun.file(fallbackHtmlPath), {
|
||||
headers: { 'content-type': 'text/html;charset=utf-8' },
|
||||
})
|
||||
const fallbackHtmlFile = Bun.file(fallbackHtmlPath)
|
||||
if (!(await fallbackHtmlFile.exists())) {
|
||||
throw new Error(
|
||||
`Production HTML bundle is missing: neither bundle.files nor ${fallbackHtmlPath} exists.`,
|
||||
)
|
||||
}
|
||||
const fallbackRaw = await fallbackHtmlFile.text()
|
||||
const serveFallbackHtml = createHtmlHandler(fallbackRaw, {
|
||||
'content-type': 'text/html;charset=utf-8',
|
||||
})
|
||||
routes['/'] = serveFallbackHtml
|
||||
routes['/*'] = serveFallbackHtml
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { writeFileSync, unlinkSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { createHtmlHandler, createStaticFileHandler, isEtagMatching, normalizeEtag } from './static'
|
||||
|
||||
describe('Static Asset Serving & Caching', () => {
|
||||
const tempChunkPath = join(tmpdir(), `test-chunk-${Date.now()}.js`)
|
||||
const chunkContent = 'console.log("chunk loaded");'
|
||||
|
||||
beforeAll(() => {
|
||||
writeFileSync(tempChunkPath, chunkContent, 'utf8')
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
try {
|
||||
unlinkSync(tempChunkPath)
|
||||
} catch {
|
||||
// Ignore cleanup error if already deleted
|
||||
}
|
||||
})
|
||||
|
||||
describe('normalizeEtag', () => {
|
||||
it('quotes unquoted ETags according to RFC 9110', () => {
|
||||
expect(normalizeEtag('hHRmXFeFVSk')).toBe('"hHRmXFeFVSk"')
|
||||
expect(normalizeEtag('ACJrxcts9Iw')).toBe('"ACJrxcts9Iw"')
|
||||
})
|
||||
|
||||
it('preserves already-quoted strong and weak ETags', () => {
|
||||
expect(normalizeEtag('"hHRmXFeFVSk"')).toBe('"hHRmXFeFVSk"')
|
||||
expect(normalizeEtag('W/"hHRmXFeFVSk"')).toBe('W/"hHRmXFeFVSk"')
|
||||
})
|
||||
|
||||
it('returns undefined for empty or missing ETags', () => {
|
||||
expect(normalizeEtag(undefined)).toBeUndefined()
|
||||
expect(normalizeEtag('')).toBeUndefined()
|
||||
expect(normalizeEtag(' ')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isEtagMatching', () => {
|
||||
it('matches exact etag string', () => {
|
||||
expect(isEtagMatching('"12345"', '"12345"')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches weak etag to strong or weak candidates', () => {
|
||||
expect(isEtagMatching('W/"12345"', '"12345"')).toBe(true)
|
||||
expect(isEtagMatching('"12345"', 'W/"12345"')).toBe(true)
|
||||
expect(isEtagMatching('W/"12345"', 'W/"12345"')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches wildcard *', () => {
|
||||
expect(isEtagMatching('"12345"', '*')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches comma-separated candidate lists', () => {
|
||||
expect(isEtagMatching('"12345"', '"old-etag", "12345", "other"')).toBe(true)
|
||||
expect(isEtagMatching('"12345"', '"old-etag", "mismatch"')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when etag or ifNoneMatch is missing or empty', () => {
|
||||
expect(isEtagMatching(undefined, '"12345"')).toBe(false)
|
||||
expect(isEtagMatching('"12345"', null)).toBe(false)
|
||||
expect(isEtagMatching('', '"12345"')).toBe(false)
|
||||
expect(isEtagMatching('"12345"', '')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createStaticFileHandler', () => {
|
||||
it('sets immutable Cache-Control for immutable content-hashed assets', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: '"chunk-hash-1"' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('text/javascript;charset=utf-8')
|
||||
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable')
|
||||
expect(res.headers.get('etag')).toBe('"chunk-hash-1"')
|
||||
expect(await res.text()).toBe(chunkContent)
|
||||
})
|
||||
|
||||
it('returns 304 Not Modified when If-None-Match matches the file etag', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: '"chunk-hash-1"' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js', {
|
||||
headers: { 'if-none-match': '"chunk-hash-1"' },
|
||||
})
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(304)
|
||||
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable')
|
||||
expect(res.headers.get('etag')).toBe('"chunk-hash-1"')
|
||||
expect(await res.text()).toBe('')
|
||||
})
|
||||
|
||||
it('sets no-cache Cache-Control for non-immutable static assets', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/plain', etag: '"plain-1"' },
|
||||
false,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/robots.txt')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('cache-control')).toBe('no-cache')
|
||||
})
|
||||
|
||||
it('normalizes unquoted manifest ETags to quoted RFC 9110 strings', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: 'hHRmXFeFVSk' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('etag')).toBe('"hHRmXFeFVSk"')
|
||||
|
||||
const revalidateRes = handler(
|
||||
new Request('http://localhost/chunk-123.js', {
|
||||
headers: { 'if-none-match': '"hHRmXFeFVSk"' },
|
||||
}),
|
||||
)
|
||||
expect(revalidateRes.status).toBe(304)
|
||||
expect(revalidateRes.headers.get('etag')).toBe('"hHRmXFeFVSk"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createHtmlHandler', () => {
|
||||
const htmlText = '<!DOCTYPE html><html><head><title>Shumai</title></head><body></body></html>'
|
||||
|
||||
it('sets no-cache and generates deterministic ETag for HTML', async () => {
|
||||
const handler = createHtmlHandler(htmlText, { 'content-type': 'text/html;charset=utf-8' })
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('text/html;charset=utf-8')
|
||||
expect(res.headers.get('cache-control')).toBe('no-cache')
|
||||
const etag = res.headers.get('etag')
|
||||
expect(etag).toBeTruthy()
|
||||
expect(await res.text()).toBe(htmlText)
|
||||
})
|
||||
|
||||
it('returns 304 Not Modified when HTML If-None-Match matches', async () => {
|
||||
const handler = createHtmlHandler(htmlText, { 'content-type': 'text/html;charset=utf-8' })
|
||||
|
||||
const initialRes = handler(new Request('http://localhost/'))
|
||||
const etag = initialRes.headers.get('etag')!
|
||||
|
||||
const revalidateReq = new Request('http://localhost/', {
|
||||
headers: { 'if-none-match': etag },
|
||||
})
|
||||
const revalidateRes = handler(revalidateReq)
|
||||
|
||||
expect(revalidateRes.status).toBe(304)
|
||||
expect(revalidateRes.headers.get('cache-control')).toBe('no-cache')
|
||||
expect(await revalidateRes.text()).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Helpers for serving static production assets with caching headers and ETag revalidation.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks whether an incoming `If-None-Match` header matches the asset's ETag.
|
||||
* Supports weak ETags (`W/"..."`), exact matches, and comma-separated lists.
|
||||
*/
|
||||
export function isEtagMatching(etag: string | undefined, ifNoneMatch: string | null): boolean {
|
||||
if (!etag || !ifNoneMatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
const cleanTarget = etag.trim().replace(/^W\//, '').replace(/^"|"$/g, '')
|
||||
if (!cleanTarget) {
|
||||
return false
|
||||
}
|
||||
|
||||
const candidates = ifNoneMatch
|
||||
.split(',')
|
||||
.map((candidate) => candidate.trim().replace(/^W\//, '').replace(/^"|"$/g, ''))
|
||||
|
||||
return candidates.includes(cleanTarget) || candidates.includes('*')
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes an ETag to ensure it is enclosed in quotes according to RFC 9110.
|
||||
* Preserves weak validators (`W/"..."`).
|
||||
*/
|
||||
export function normalizeEtag(etag: string | undefined): string | undefined {
|
||||
if (!etag) {
|
||||
return undefined
|
||||
}
|
||||
const trimmed = etag.trim()
|
||||
if (!trimmed) {
|
||||
return undefined
|
||||
}
|
||||
if (trimmed.startsWith('W/"') && trimmed.endsWith('"')) {
|
||||
return trimmed
|
||||
}
|
||||
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
||||
return trimmed
|
||||
}
|
||||
return `"${trimmed.replace(/^"|"$/g, '')}"`
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a route handler for a static file on disk.
|
||||
* Content-hashed assets (e.g. `chunk-*.js`, `chunk-*.css`) should be marked `isImmutable: true`
|
||||
* to be aggressively cached locally by browsers across page reloads.
|
||||
*/
|
||||
export function createStaticFileHandler(
|
||||
filePath: string,
|
||||
baseHeaders: Record<string, string>,
|
||||
isImmutable: boolean,
|
||||
): (req: Request) => Response {
|
||||
const bunFile = Bun.file(filePath)
|
||||
const rawEtag = baseHeaders.etag || baseHeaders.ETag
|
||||
const normalizedEtag = normalizeEtag(rawEtag)
|
||||
const headers: Record<string, string> = {
|
||||
...baseHeaders,
|
||||
...(normalizedEtag ? { etag: normalizedEtag } : {}),
|
||||
'cache-control': isImmutable ? 'public, max-age=31536000, immutable' : 'no-cache',
|
||||
}
|
||||
const etag = headers.etag
|
||||
|
||||
return (req: Request): Response => {
|
||||
const ifNoneMatch = req.headers.get('if-none-match')
|
||||
if (etag && isEtagMatching(etag, ifNoneMatch)) {
|
||||
return new Response(null, {
|
||||
status: 304,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
return new Response(bunFile, { headers })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a route handler for in-memory transformed HTML entry points.
|
||||
* Sets `cache-control: no-cache` with a deterministic ETag, allowing browsers to cache locally
|
||||
* while always revalidating to ensure new chunk hashes are picked up immediately after deployment.
|
||||
*/
|
||||
export function createHtmlHandler(
|
||||
htmlText: string,
|
||||
baseHeaders: Record<string, string>,
|
||||
): (req: Request) => Response {
|
||||
const rawEtag = baseHeaders.etag || baseHeaders.ETag
|
||||
const etag = normalizeEtag(rawEtag) || `"${Bun.hash(htmlText).toString(16)}"`
|
||||
const headers: Record<string, string> = {
|
||||
...baseHeaders,
|
||||
etag,
|
||||
'cache-control': 'no-cache',
|
||||
}
|
||||
|
||||
return (req: Request): Response => {
|
||||
const ifNoneMatch = req.headers.get('if-none-match')
|
||||
if (isEtagMatching(etag, ifNoneMatch)) {
|
||||
return new Response(null, {
|
||||
status: 304,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
return new Response(htmlText, { headers })
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -44,7 +44,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -61,7 +61,7 @@
|
||||
},
|
||||
"apps/premiere-uxp": {
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
@@ -115,7 +115,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -127,7 +127,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -147,7 +147,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -171,7 +171,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
@@ -191,7 +191,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "2.0.38",
|
||||
"@ai-sdk/amazon-bedrock": "5.0.67",
|
||||
@@ -255,7 +255,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.10.0",
|
||||
@@ -271,7 +271,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.5.4",
|
||||
@@ -279,7 +279,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "2.28.0",
|
||||
@@ -294,18 +294,18 @@
|
||||
},
|
||||
"packages/operations": {
|
||||
"name": "@shumai/operations",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"zod": "4.5.4",
|
||||
},
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -316,7 +316,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.7.0",
|
||||
"@better-auth/oauth-provider": "1.7.12",
|
||||
@@ -419,7 +419,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"dependencies": {
|
||||
"@dbos-inc/dbos-sdk": "5.2.11",
|
||||
"@shumai/core": "workspace:*",
|
||||
|
||||
@@ -3,6 +3,25 @@ title: "Changelog"
|
||||
description: "Recent updates, new features, and improvements in Shumai"
|
||||
---
|
||||
|
||||
<Update label="v0.6.4" description="November 5, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
- **storage**: Add optional archive storage support (`local` folder/NAS or `s3` with configurable storage class and Glacier restore) allowing editors and owners to archive and restore original files while keeping previews, proxy streams, comments, and metadata available in main storage
|
||||
- **storage**: Add team-level automatic asset archival based on age policies (creation time or last modified time) with configurable post-restore grace periods, an hourly background scanning worker, and a dedicated Storage settings page displaying read-only archive backend status and policy configurations
|
||||
|
||||
### Fixed
|
||||
|
||||
- **security**: ⚠️ Several security improvements and access control hardenings. Upgrading to this release is strongly recommended.
|
||||
- **mcp**: Gracefully disable MCP OAuth 2.1 with an error log when deploying on remote HTTP IP addresses without breaking the main server or API token MCP access
|
||||
- **web**: Add immutable cache headers and conditional 304 Not Modified support for production JavaScript and CSS chunks to prevent unnecessary refetches on page reload
|
||||
|
||||
### Changed
|
||||
|
||||
- **file-browser**: Replace the legacy combined "Copy name and download link" action with a context-aware Copy submenu in file browser context menus and card action dropdowns, enabling users to copy image, asset names, in-app links, download links, IDs, Markdown links and storage paths(team-owner only)
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.6.3" description="November 1, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
@@ -15,7 +15,7 @@ Team members can continue to browse, search, scrub, and review archived assets i
|
||||
2. **Durable Asynchronous Workflows**: Moving and restoring files is handled by background worker tasks on a dedicated queue (`archive_queue`) managed by DBOS. Tasks automatically survive network interruptions, slow S3 transfers, and server restarts.
|
||||
3. **Transparent Asset Lifecycle**:
|
||||
- When an asset is being archived, its status transitions to `archiving` and settles at `archived`.
|
||||
- When an asset is being restored, its status transitions to `restoring` and returns to `ready` (or `processed`) once the original file is back in primary storage.
|
||||
- When an asset is being restored, its status transitions to `restoring` and returns to `processed` once the original file is back in primary storage.
|
||||
- Trashed assets that are permanently purged automatically delete their original file from archive storage as well.
|
||||
4. **Folder & Version Stack Support**: Archiving a folder or version stack recursively archives all contained file assets. Restoring a folder or version stack restores all archived files inside it.
|
||||
|
||||
@@ -39,36 +39,38 @@ Configure archive storage by adding the following environment variables to your
|
||||
|
||||
### General Configuration
|
||||
|
||||
| Variable | Description | Required | Default |
|
||||
| :------------------------ | :--------------------------------------------------------------------------------------------------------- | :------- | :--------------- |
|
||||
| `ARCHIVE_STORAGE_BACKEND` | Storage backend for archives: `local` or `s3`. When unset, archive functionality is disabled in the WebUI. | No | Unset (Disabled) |
|
||||
| `CONCURRENCY_ARCHIVE` | Maximum concurrent archive and restore tasks executed by background workers. | No | `5` |
|
||||
| `SHUMAI_WORKERS` | Queues listened to by the application server. Set to `all` or include `archive`. | No | `all` |
|
||||
| Variable | Description | Required | Default |
|
||||
| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :--------------- |
|
||||
| `ARCHIVE_STORAGE_BACKEND` | Storage backend for archives: `local` or `s3`. When unset, archive functionality is disabled in the WebUI. | No | Unset (Disabled) |
|
||||
| `CONCURRENCY_ARCHIVE` | Maximum concurrent archive and restore tasks executed by background workers. | No | `5` |
|
||||
| `SHUMAI_WORKERS` | Worker queues listened to by the application server: `all` (default), `none`, `agent` (or `ai`), `transcode`, `archive`. Set to `all` or `archive` to process tasks. | No | `all` |
|
||||
| `AUTO_ARCHIVE_INTERVAL_MINUTES` | Frequency (in minutes) of the background auto-archive scanner job. Accepts decimal numbers (e.g. `0.02` for testing). | No | `60` (1 hour) |
|
||||
|
||||
### Local Archive Storage
|
||||
|
||||
Used when `ARCHIVE_STORAGE_BACKEND=local`:
|
||||
|
||||
| Variable | Description | Required | Default |
|
||||
| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------- | :------- | :------------------ |
|
||||
| `ARCHIVE_LOCAL_STORAGE_PATH` | Host filesystem directory path for storing archived original files. Useful for mounting a secondary disk or NAS volume. | No | `./storage-archive` |
|
||||
| Variable | Description | Required | Default |
|
||||
| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :--------------- |
|
||||
| `ARCHIVE_LOCAL_ROOT` | Host filesystem directory path where archived files are stored. Must not overlap with main local storage directory (`./data` or `./data/<S3_BUCKET>`). | Yes | Unset (Required) |
|
||||
|
||||
### S3 Archive Storage
|
||||
|
||||
Used when `ARCHIVE_STORAGE_BACKEND=s3`:
|
||||
Used when `ARCHIVE_STORAGE_BACKEND=s3`. Note that archive storage maintains its own configuration and **never falls back** to the primary `S3_*` environment variables:
|
||||
|
||||
| Variable | Description | Required | Default |
|
||||
| :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :------- | :------------------------------------ |
|
||||
| `ARCHIVE_S3_BUCKET` | The destination S3 bucket for archived files. Defaults to `S3_BUCKET` if unset. | No | Falls back to `S3_BUCKET` |
|
||||
| `ARCHIVE_AWS_ENDPOINT_URL_S3` | S3 endpoint URL for archive storage. Defaults to `AWS_ENDPOINT_URL_S3` if unset. | No | Falls back to `AWS_ENDPOINT_URL_S3` |
|
||||
| `ARCHIVE_S3_REGION` | S3 region for the archive bucket. Defaults to `S3_REGION` if unset. | No | Falls back to `S3_REGION` |
|
||||
| `ARCHIVE_S3_ACCESS_KEY_ID` | Access key ID for the archive S3 service. Defaults to `S3_ACCESS_KEY_ID` if unset. | No | Falls back to `S3_ACCESS_KEY_ID` |
|
||||
| `ARCHIVE_S3_SECRET_ACCESS_KEY` | Secret access key for the archive S3 service. Defaults to `S3_SECRET_ACCESS_KEY` if unset. | No | Falls back to `S3_SECRET_ACCESS_KEY` |
|
||||
| `ARCHIVE_S3_FORCE_PATH_STYLE` | Set to `true` for MinIO or path-style S3 storage endpoints. | No | `false` |
|
||||
| `ARCHIVE_S3_STORAGE_CLASS` | S3 storage class to apply to archived objects (e.g. `GLACIER`, `GLACIER_IR`, `DEEP_ARCHIVE`, `COLDLINE`). | No | `STANDARD` |
|
||||
| `ARCHIVE_S3_RESTORE_DAYS` | Number of days a restored temporary copy remains readable in S3 for asynchronous Glacier restores. | No | `7` |
|
||||
| `ARCHIVE_S3_RESTORE_TIER` | S3 Glacier retrieval tier (`Expedited`, `Standard`, or `Bulk`). Omit when using providers that do not require asynchronous retrieval. | No | Unset |
|
||||
| `ARCHIVE_RESTORE_POLL_INTERVAL_MS` | Milliseconds between status checks while waiting for an asynchronous cold storage restore. | No | `60000` (1 min initial, 5 min steady) |
|
||||
| Variable | Description | Required | Default |
|
||||
| :--------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------------------------------ |
|
||||
| `ARCHIVE_S3_BUCKET` | Destination S3 bucket for archived files (can be a dedicated bucket or the same bucket as `S3_BUCKET` for in-place tiering). | Yes | Unset (Required) |
|
||||
| `ARCHIVE_S3_ACCESS_KEY_ID` | Access key ID for the archive S3 service. | Yes | Unset (Required) |
|
||||
| `ARCHIVE_S3_SECRET_ACCESS_KEY` | Secret access key for the archive S3 service. | Yes | Unset (Required) |
|
||||
| `ARCHIVE_AWS_ENDPOINT_URL_S3` | S3 endpoint URL for archive storage (e.g. MinIO, Cloudflare R2, Google Cloud Storage). | No | Unset (AWS standard endpoint) |
|
||||
| `ARCHIVE_S3_REGION` | S3 region for the archive bucket. | No | `auto` |
|
||||
| `ARCHIVE_S3_FORCE_PATH_STYLE` | Use path-style S3 URLs (`true` for MinIO/path-style, `false` for virtual-hosted style). | No | `true` |
|
||||
| `ARCHIVE_S3_STORAGE_CLASS` | S3 storage class to apply to archived objects (e.g. `GLACIER`, `GLACIER_IR`, `DEEP_ARCHIVE`, `COLDLINE`). Required and must not be `STANDARD` when archiving to the same S3 bucket. | No | Unset |
|
||||
| `ARCHIVE_S3_USE_RESTORE_OBJECT` | Controls whether S3 `RestoreObject` is called before reading archived objects (`auto`, `true`, or `false`). | No | `auto` |
|
||||
| `ARCHIVE_S3_RESTORE_DAYS` | Number of days a restored temporary copy remains readable in S3 for asynchronous Glacier restores. | No | `1` |
|
||||
| `ARCHIVE_S3_RESTORE_TIER` | S3 Glacier retrieval tier (`Expedited`, `Standard`, or `Bulk`). Omit when using providers that do not require asynchronous retrieval. | No | Unset |
|
||||
| `ARCHIVE_RESTORE_POLL_INTERVAL_MS` | Milliseconds between status checks while waiting for an asynchronous cold storage restore. | No | `60000` (1 min initial, 5 min steady) |
|
||||
|
||||
---
|
||||
|
||||
@@ -85,7 +87,7 @@ LOCAL_STORAGE_PATH=./storage
|
||||
|
||||
# Archive storage pointing to your mounted NAS directory
|
||||
ARCHIVE_STORAGE_BACKEND=local
|
||||
ARCHIVE_LOCAL_STORAGE_PATH=/mnt/nas/shumai-archive
|
||||
ARCHIVE_LOCAL_ROOT=/mnt/nas/shumai-archive
|
||||
```
|
||||
|
||||
In `docker-compose.yaml`, mount the host NAS volume into the container:
|
||||
@@ -97,7 +99,7 @@ services:
|
||||
- /mnt/nas/shumai-archive:/mnt/nas/shumai-archive
|
||||
environment:
|
||||
ARCHIVE_STORAGE_BACKEND: local
|
||||
ARCHIVE_LOCAL_STORAGE_PATH: /mnt/nas/shumai-archive
|
||||
ARCHIVE_LOCAL_ROOT: /mnt/nas/shumai-archive
|
||||
```
|
||||
|
||||
---
|
||||
@@ -119,8 +121,13 @@ S3_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
|
||||
S3_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
|
||||
AWS_ENDPOINT_URL_S3=https://s3.us-east-1.amazonaws.com
|
||||
|
||||
# Archive Storage (re-uses main bucket & credentials automatically)
|
||||
# Archive Storage (same bucket & credentials with cold storage class)
|
||||
ARCHIVE_STORAGE_BACKEND=s3
|
||||
ARCHIVE_S3_BUCKET=my-shumai-production
|
||||
ARCHIVE_S3_REGION=us-east-1
|
||||
ARCHIVE_S3_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
|
||||
ARCHIVE_S3_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
|
||||
ARCHIVE_AWS_ENDPOINT_URL_S3=https://s3.us-east-1.amazonaws.com
|
||||
ARCHIVE_S3_STORAGE_CLASS=GLACIER_IR
|
||||
```
|
||||
|
||||
@@ -188,7 +195,49 @@ ARCHIVE_S3_STORAGE_CLASS=COLDLINE
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> Do not set `ARCHIVE_S3_RESTORE_TIER` when using Google Cloud Storage, as GCS objects are readable immediately and do not accept AWS Glacier retrieval parameters.
|
||||
> Google Cloud Storage objects are readable immediately and do not accept AWS Glacier retrieval parameters. Do not set `ARCHIVE_S3_RESTORE_TIER`. If using GCS's `ARCHIVE` storage class, set `ARCHIVE_S3_USE_RESTORE_OBJECT=false` to bypass S3 `RestoreObject` calls.
|
||||
|
||||
---
|
||||
|
||||
## Automatic Asset Archival
|
||||
|
||||
In addition to manual on-demand archival, Shumai allows teams to automate cold storage tiering based on asset age lifecycle policies. This ensures heavy original master files are automatically offloaded to secondary cold storage without requiring manual housekeeping from creative staff or administrators.
|
||||
|
||||
### WebUI Configuration
|
||||
|
||||
Team owners can configure automatic archival under **Team Settings > Storage**:
|
||||
|
||||
1. **Archive Storage Status Overview**:
|
||||
- Displays the current system archive storage backend (`local` or `s3`), endpoint, bucket, or root directory configured on the server.
|
||||
- If archive storage is not configured in server environment variables, a warning alert is displayed, and auto-archive controls are disabled.
|
||||
- For security, credentials and private server settings are not exposed to client browsers.
|
||||
|
||||
2. **Automatic Asset Archival Policy**:
|
||||
- **Enable Auto Archive**: Toggle automated background archival on or off for the team (disabled by default; requires an active archive storage backend).
|
||||
- **Archive Criteria (`method`)**:
|
||||
- **Not modified for specified days (`not_updated`)**: Evaluates the last modification timestamp (`updatedAt`). Ideal for active production workflows—files stay in fast primary storage as long as team members are actively commenting, annotating, or modifying them. Once no modifications have occurred for the configured duration, the asset is moved to cold storage.
|
||||
- **After creation for specified days (`after_created`)**: Evaluates the initial upload/creation timestamp (`createdAt`). Ideal for strict retention or compliance pipelines where footage is tiered based on its age (e.g., 60 or 90 days after delivery) regardless of recent review comments.
|
||||
- **Age Threshold (`days`)**: The threshold in days (between 1 and 3,650 days) after which eligible assets are queued for archival.
|
||||
- **Post-Restore Grace Period (`postRestoreGraceDays`)**:
|
||||
- When an asset is restored from archive back to primary storage, its modification date is refreshed to the restore time.
|
||||
- When using the **After creation** rule, an asset older than the threshold (e.g. 100 days old) would otherwise be immediately picked up and re-archived by the very next hourly scan.
|
||||
- The post-restore grace period (default: 30 days) guarantees that restored files remain in primary storage for at least the specified number of days before becoming eligible for automated archival again. This value should be set smaller than the Age Threshold. Under this policy, only files that are older than the Age Threshold and have also surpassed the Post-Restore Grace Period since restoration are auto-archived.
|
||||
|
||||
### Sibling Deduplication & Safety
|
||||
|
||||
Shumai uses content-addressable storage keys (`storage_keys`) to deduplicate identical files across projects and folders:
|
||||
|
||||
- **Sibling Protection**: If multiple asset records reference the same underlying storage object (e.g., copied or duplicated files across folders or projects), the auto-archive scanner inspects all sibling assets.
|
||||
- **Strict Consensus**: The underlying storage file is **only** archived if **all active sibling files** satisfy the team's auto-archive criteria and are in a stable `processed` state.
|
||||
- **Starvation-Free Scheduling**: If any sibling copy was modified recently or is currently in an active workflow, the storage key is safely skipped without blocking other eligible assets from being archived.
|
||||
|
||||
### Background Scanner & Execution Semantics
|
||||
|
||||
The auto-archive job runs periodically in the background:
|
||||
|
||||
- **Scan Frequency**: Configured via the `AUTO_ARCHIVE_INTERVAL_MINUTES` environment variable (defaults to `60` minutes; accepts decimal values such as `0.02` for automated testing).
|
||||
- **Distributed Leader Election**: Uses PostgreSQL transaction-scoped advisory locks (`pg_try_advisory_xact_lock`) during the candidate discovery phase. In multi-pod or multi-replica container deployments, only one server instance performs the scan per interval while other replicas cleanly skip.
|
||||
- **Race Condition Prevention**: During archival, candidate assets transition atomically via conditional SQL (`UPDATE assets SET status = 'archiving' WHERE status = 'processed'`) protected by row-level `storage_keys FOR UPDATE` locks. This guarantees zero race conditions with concurrent manual user archival, restoration, or file deletion.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -78,6 +78,7 @@ Shumai supports configuring an optional **Archive Storage** tier (`local` NAS/di
|
||||
| `ARCHIVE_S3_USE_RESTORE_OBJECT` | Controls whether S3 `RestoreObject` is called before reading archived objects (`auto`, `true`, or `false`). | `auto` (default) |
|
||||
| `ARCHIVE_S3_RESTORE_DAYS` | Number of days a restored copy of a cold S3 object remains readable during restoration. | `1` (default) |
|
||||
| `ARCHIVE_S3_RESTORE_TIER` | Optional S3 Glacier retrieval tier (`Expedited`, `Standard`, `Bulk`). Omitted when unset for S3-compatible providers that reject `GlacierJobParameters`. | Unset (default) |
|
||||
| `AUTO_ARCHIVE_INTERVAL_MINUTES` | Frequency (in minutes) of the background auto-archive scanner job. Accepts decimal values (e.g. `0.02` for testing). | `60` (1 hour default) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
|
||||
3. **Configure Environment Variables**:
|
||||
Open `docker-compose.yaml` to adjust environment variables for your deployment:
|
||||
|
||||
- `BETTER_AUTH_URL`: The public base URL of your Shumai server (e.g., `https://shumai.example.com` or `http://12.34.56.78:3000`). This is required for remote servers and production deployments.
|
||||
- `BETTER_AUTH_URL`: The public base URL of your Shumai server (e.g., `https://shumai.example.com` or `http://12.34.56.78:3000`). This is required for remote servers and production deployments. Note: Remote deployments must use HTTPS for MCP OAuth 2.1; if an HTTP IP address or domain is used, MCP OAuth 2.1 is gracefully disabled while the Web UI and MCP API tokens remain functional.
|
||||
- `AWS_ENDPOINT_URL_S3`: By default, `AWS_ENDPOINT_URL_S3` is set to `http://localhost:{SHUMAI_SERVER_PORT}`. When you use local storage (the default storage backend with `STORAGE_BACKEND: local`) and expose Shumai on a remote server, custom domain, or custom host/port combination, set `AWS_ENDPOINT_URL_S3` to the external URL that client browsers will use to upload and download files.
|
||||
|
||||
For example, if you change the port mapping in `docker-compose.yaml` from `3000:3000` to `12345:3000` and deploy on a server with IP address `12.34.56.78`, set:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -3,8 +3,9 @@ import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import type { User } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
@@ -54,26 +55,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
|
||||
type: ResourceType.Asset,
|
||||
id: owningAssetId,
|
||||
})
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { key },
|
||||
include: {
|
||||
assets: {
|
||||
where: { isDeleted: false },
|
||||
select: { status: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
if (
|
||||
sk &&
|
||||
(sk.isArchived ||
|
||||
sk.assets.some(
|
||||
(a) => a.status === 'archiving' || a.status === 'archived' || a.status === 'restoring',
|
||||
))
|
||||
) {
|
||||
throw new Error(
|
||||
`Original file for storage key "${key}" is archived. Restore the asset first or download its proxy using assetIds with proxy: true.`,
|
||||
)
|
||||
}
|
||||
await assertStorageKeyNotArchived(key)
|
||||
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
|
||||
const saved = await saveToSandbox(key, filename)
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,16 +2,19 @@ import { Hono } from 'hono'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
|
||||
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
|
||||
import { z } from 'zod'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { ulid } from 'ulid'
|
||||
import { setCookie } from 'hono/cookie'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const identifySchema = z.object({
|
||||
username: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
shareId: z.string().min(1).optional(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
@@ -30,7 +33,7 @@ const route = app
|
||||
return c.json({ id: session?.user?.id ?? null })
|
||||
})
|
||||
.post('/identify', zValidator('json', identifySchema), async (c) => {
|
||||
const { username, email } = c.req.valid('json')
|
||||
const { username, email, shareId } = c.req.valid('json')
|
||||
|
||||
const dummyEmail = `guest_${ulid()}@guest.local`
|
||||
const user = await userService.createGuestUser({
|
||||
@@ -39,6 +42,17 @@ const route = app
|
||||
guestEmail: email,
|
||||
})
|
||||
|
||||
if (shareId) {
|
||||
const token = createGuestToken({ userId: user.id, shareId })
|
||||
setCookie(c, `shumai_guest_${shareId}`, token, {
|
||||
httpOnly: true,
|
||||
path: '/',
|
||||
sameSite: 'Lax',
|
||||
secure: c.req.url.startsWith('https://') || process.env.NODE_ENV === 'production',
|
||||
maxAge: 30 * 24 * 60 * 60,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({ id: user.id })
|
||||
})
|
||||
.all('/auth/*', (c) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
@@ -819,10 +820,13 @@ describe('file api', () => {
|
||||
.spyOn(assetService, 'getProjectIds')
|
||||
.mockResolvedValue(['project-id-1'])
|
||||
|
||||
const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue([
|
||||
{ id: 'file1', name: 'file1.txt', url: 'http://link1' },
|
||||
{ id: 'file2', name: 'file2.txt', url: 'http://link2' },
|
||||
])
|
||||
const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue({
|
||||
files: [
|
||||
{ id: 'file1', name: 'file1.txt', url: 'http://link1' },
|
||||
{ id: 'file2', name: 'file2.txt', url: 'http://link2' },
|
||||
],
|
||||
skippedArchivedCount: 0,
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/download-links', {
|
||||
@@ -868,6 +872,127 @@ describe('file api', () => {
|
||||
mockGetProjectIds.mockRestore()
|
||||
})
|
||||
|
||||
describe('POST /files/storage-paths', () => {
|
||||
it('returns empty paths if ids are empty', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/storage-paths', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toEqual({ paths: [] })
|
||||
})
|
||||
|
||||
it('rejects if assets belong to multiple projects', async () => {
|
||||
const mockGetProjectIds = vi
|
||||
.spyOn(assetService, 'getProjectIds')
|
||||
.mockResolvedValue(['proj-1', 'proj-2'])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/storage-paths', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['asset-1', 'asset-2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const json = await res.json()
|
||||
expect(json.error).toBe('All selected items must belong to the same project')
|
||||
|
||||
mockGetProjectIds.mockRestore()
|
||||
})
|
||||
|
||||
it('denies access if user is not a team owner (admin)', async () => {
|
||||
const mockGetProjectIds = vi
|
||||
.spyOn(assetService, 'getProjectIds')
|
||||
.mockResolvedValue(['proj-1'])
|
||||
const mockGetProjectTeam = vi
|
||||
.spyOn(projectService, 'getProjectTeam')
|
||||
.mockResolvedValue('team-1')
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
|
||||
new HTTPException(403, { message: 'Permission denied' }),
|
||||
)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/storage-paths', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['asset-1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 'team-1',
|
||||
})
|
||||
|
||||
mockGetProjectIds.mockRestore()
|
||||
mockGetProjectTeam.mockRestore()
|
||||
})
|
||||
|
||||
it('returns storage paths if user has team admin permission', async () => {
|
||||
const mockGetProjectIds = vi
|
||||
.spyOn(assetService, 'getProjectIds')
|
||||
.mockResolvedValue(['proj-1'])
|
||||
const mockGetProjectTeam = vi
|
||||
.spyOn(projectService, 'getProjectTeam')
|
||||
.mockResolvedValue('team-1')
|
||||
const mockGetStoragePaths = vi.spyOn(assetService, 'getStoragePaths').mockResolvedValue({
|
||||
paths: [
|
||||
{
|
||||
id: 'asset-1',
|
||||
name: 'clip.mp4',
|
||||
path: 's3://shumai/files/1/clip.mp4',
|
||||
backend: 's3',
|
||||
isArchived: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/storage-paths', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['asset-1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.paths).toHaveLength(1)
|
||||
expect(json.paths[0].name).toBe('clip.mp4')
|
||||
expect(json.paths[0].path).toBe('s3://shumai/files/1/clip.mp4')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 'team-1',
|
||||
})
|
||||
expect(assetService.getStoragePaths).toHaveBeenCalledWith(['asset-1'])
|
||||
|
||||
mockGetProjectIds.mockRestore()
|
||||
mockGetProjectTeam.mockRestore()
|
||||
mockGetStoragePaths.mockRestore()
|
||||
})
|
||||
|
||||
it('rejects if more than 100 ids are provided', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const ids = Array.from({ length: 101 }, (_, i) => `asset-${i}`)
|
||||
const res = await app.request('/files/storage-paths', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /files/:fileId/m3u8 routes', () => {
|
||||
it('returns master playlist with correct content-type', async () => {
|
||||
const mockMaster = vi
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { commentService } from '@shumai/core/src/comment/comment'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
updateFileRequestSchema,
|
||||
uploadFileRequestSchema,
|
||||
getDownloadLinksRequestSchema,
|
||||
getStoragePathsRequestSchema,
|
||||
completeCommentRequestSchema,
|
||||
exportCommentsRequestSchema,
|
||||
addCommentReactionRequestSchema,
|
||||
@@ -450,13 +452,43 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
})
|
||||
|
||||
// 4. Generate download links
|
||||
const files = await assetService.getDownloadLinks(req.ids)
|
||||
const skippedArchivedCount = files.skippedArchivedCount
|
||||
const { files, skippedArchivedCount } = await assetService.getDownloadLinks(req.ids)
|
||||
return c.json({
|
||||
files,
|
||||
...(skippedArchivedCount !== undefined ? { skippedArchivedCount } : {}),
|
||||
...(skippedArchivedCount > 0 ? { skippedArchivedCount } : {}),
|
||||
})
|
||||
})
|
||||
.post('/files/storage-paths', zValidator('json', getStoragePathsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
if (req.ids.length === 0) {
|
||||
return c.json({ paths: [] })
|
||||
}
|
||||
|
||||
const projectIds = await assetService.getProjectIds(req.ids)
|
||||
if (projectIds.length === 0) {
|
||||
return c.json({ paths: [] })
|
||||
}
|
||||
|
||||
if (projectIds.length !== 1) {
|
||||
return c.json({ error: 'All selected items must belong to the same project' }, 400)
|
||||
}
|
||||
|
||||
const projectId = projectIds[0]
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
|
||||
// Verify user has Admin (owner) permission on the team
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await assetService.getStoragePaths(req.ids)
|
||||
return c.json(result)
|
||||
})
|
||||
.post(
|
||||
'/files/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1), assetId: z.string().min(1) })),
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
|
||||
describe('MCP server on remote HTTP BETTER_AUTH_URL', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const originalEnv = process.env.BETTER_AUTH_URL
|
||||
let user: User
|
||||
let token: string
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let app: Hono<any>
|
||||
let isMcpOauthEnabled: boolean
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.BETTER_AUTH_URL = 'http://43.133.100.178:3000'
|
||||
vi.resetModules()
|
||||
|
||||
const authModule = await import('@shumai/core/src/auth/auth')
|
||||
isMcpOauthEnabled = authModule.isMcpOauthEnabled
|
||||
const mcpServerModule = await import('./mcp-server')
|
||||
|
||||
app = new Hono().route('/', mcpServerModule.default)
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: { name: 'Remote HTTP User', email: `remote-http-${Date.now()}@test.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Remote HTTP Team' } })
|
||||
await prisma.teamMember.create({ data: { teamId: team.id, userId: user.id, role: 'owner' } })
|
||||
await projectService.createProject(user, { teamId: team.id, name: 'Remote HTTP Project' })
|
||||
|
||||
const tokenRes = await apiTokenService.createToken(user.id, 'remote-http-test')
|
||||
token = tokenRes.token
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.BETTER_AUTH_URL = originalEnv
|
||||
} else {
|
||||
delete process.env.BETTER_AUTH_URL
|
||||
}
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
it('omits MCP OAuth plugin and disables isMcpOauthEnabled', () => {
|
||||
expect(isMcpOauthEnabled).toBe(false)
|
||||
})
|
||||
|
||||
it('returns 503 Service Unavailable for unauthenticated requests to /mcp', async () => {
|
||||
const res = await app.request('/mcp', { method: 'POST' })
|
||||
expect(res.status).toBe(503)
|
||||
const body = await res.json()
|
||||
expect(body).toMatchObject({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32000,
|
||||
message: expect.stringContaining(
|
||||
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS',
|
||||
),
|
||||
},
|
||||
id: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('allows valid API tokens to access /mcp and execute tools even when OAuth is disabled', async () => {
|
||||
const transport = new StreamableHTTPClientTransport(new URL('http://localhost/mcp'), {
|
||||
fetch: async (input, init) => {
|
||||
const headers = new Headers(init?.headers)
|
||||
headers.set('Authorization', `Bearer ${token}`)
|
||||
return app.request(String(input), {
|
||||
...init,
|
||||
headers,
|
||||
})
|
||||
},
|
||||
})
|
||||
const client = new Client({ name: 'remote-http-client', version: '1.0.0' })
|
||||
await client.connect(transport)
|
||||
|
||||
expect(client.getServerVersion()).toMatchObject({ name: 'shumai' })
|
||||
const { tools } = await client.listTools()
|
||||
expect(tools.length).toBeGreaterThan(0)
|
||||
expect(tools.map((t) => t.name)).toContain('list_projects')
|
||||
|
||||
await client.close()
|
||||
})
|
||||
|
||||
it('rejects invalid API tokens with 401 Unauthorized', async () => {
|
||||
const res = await app.request('/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer shumai_invalidtoken1234567890',
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@ import { teamService } from '@shumai/core/src/team/team'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { createFolderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { MAX_INLINE_IMAGE_BYTES, MAX_INLINE_IMAGES } from './mcp-extensions/read-asset'
|
||||
import mcpServerRoute, { MCP_SERVER_INSTRUCTIONS } from './mcp-server'
|
||||
import mcpServerRoute, { disabledOauthHandler, MCP_SERVER_INSTRUCTIONS } from './mcp-server'
|
||||
|
||||
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
|
||||
@@ -402,4 +402,22 @@ describe('MCP server', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Disabled OAuth Fallback', () => {
|
||||
it('returns 503 Service Unavailable with standard JSON-RPC error payload', async () => {
|
||||
const res = await disabledOauthHandler()
|
||||
expect(res.status).toBe(503)
|
||||
expect(res.headers.get('content-type')).toContain('application/json')
|
||||
const body = await res.json()
|
||||
expect(body).toEqual({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32000,
|
||||
message:
|
||||
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS or a loopback address. Please configure HTTPS or authenticate with a Shumai API token.',
|
||||
},
|
||||
id: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { z } from 'zod'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { dropNullOptionals } from '@shumai/operations'
|
||||
import { getOperationsForSurface, runOperation, type Operation } from '@shumai/core/src/operations'
|
||||
import { auth, authBaseUrl, mcpResource } from '@shumai/core/src/auth/auth'
|
||||
import { auth, authBaseUrl, isMcpOauthEnabled, mcpResource } from '@shumai/core/src/auth/auth'
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import { mcpExtensions, type McpToolExtension } from './mcp-extensions'
|
||||
import { assertWritableInDemoMode, describeOperationError } from './operation-support'
|
||||
@@ -134,40 +134,60 @@ const mcpHandler = createMcpHandler(({ authInfo }) => {
|
||||
return buildMcpServer(userId)
|
||||
})
|
||||
|
||||
const oauthHandler = requireMcpAuth(
|
||||
auth,
|
||||
(req, claims) => {
|
||||
const userId = claims.sub
|
||||
if (!userId) {
|
||||
throw new Error('OAuth token has no sub claim')
|
||||
}
|
||||
const clientId = (claims.azp as string) ?? (claims.client_id as string) ?? ''
|
||||
const scopes =
|
||||
typeof claims.scope === 'string'
|
||||
? claims.scope.split(' ')
|
||||
: ((claims.scopes as string[]) ?? [])
|
||||
return mcpHandler.fetch(req, {
|
||||
authInfo: {
|
||||
token: '',
|
||||
clientId,
|
||||
scopes,
|
||||
extra: { userId },
|
||||
export const disabledOauthHandler = async (): Promise<Response> => {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32000,
|
||||
message:
|
||||
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS or a loopback address. Please configure HTTPS or authenticate with a Shumai API token.',
|
||||
},
|
||||
})
|
||||
},
|
||||
{
|
||||
resource: mcpResource,
|
||||
// In-process verification: avoids HTTP loopback round-trip and works even in test environments
|
||||
// where no HTTP port is bound.
|
||||
jwksUrl: (async () => {
|
||||
const res = await auth.handler(new Request(`${authBaseUrl}/api/auth/jwks`))
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load JWKS in-process: ${res.statusText}`)
|
||||
}
|
||||
return await res.json()
|
||||
}) as unknown as string,
|
||||
},
|
||||
)
|
||||
id: null,
|
||||
}),
|
||||
{
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const oauthHandler = isMcpOauthEnabled
|
||||
? requireMcpAuth(
|
||||
auth,
|
||||
(req, claims) => {
|
||||
const userId = claims.sub
|
||||
if (!userId) {
|
||||
throw new Error('OAuth token has no sub claim')
|
||||
}
|
||||
const clientId = (claims.azp as string) ?? (claims.client_id as string) ?? ''
|
||||
const scopes =
|
||||
typeof claims.scope === 'string'
|
||||
? claims.scope.split(' ')
|
||||
: ((claims.scopes as string[]) ?? [])
|
||||
return mcpHandler.fetch(req, {
|
||||
authInfo: {
|
||||
token: '',
|
||||
clientId,
|
||||
scopes,
|
||||
extra: { userId },
|
||||
},
|
||||
})
|
||||
},
|
||||
{
|
||||
resource: mcpResource,
|
||||
// In-process verification: avoids HTTP loopback round-trip and works even in test environments
|
||||
// where no HTTP port is bound.
|
||||
jwksUrl: (async () => {
|
||||
const res = await auth.handler(new Request(`${authBaseUrl}/api/auth/jwks`))
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load JWKS in-process: ${res.statusText}`)
|
||||
}
|
||||
return await res.json()
|
||||
}) as unknown as string,
|
||||
},
|
||||
)
|
||||
: disabledOauthHandler
|
||||
|
||||
/** Shumai's MCP server (Streamable HTTP). Mounted at `/mcp` with dual API token and OAuth 2.1 auth. */
|
||||
const route = new Hono<{ Variables: { user: User } }>().all('/mcp', async (c) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import { getCookie } from 'hono/cookie'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
@@ -12,6 +13,7 @@ import type { Prisma as PrismaType } from '@shumai/db'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { verifyGuestToken } from '@shumai/core/src/auth/guest-token'
|
||||
import { createCommentRequestSchema } from '@shumai/dtos'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import {
|
||||
@@ -160,7 +162,7 @@ const route = app
|
||||
const password = c.req.header('x-share-password')
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
await shareService.verifyPublicAccess(shareId, shareLink.rootFolderId, password)
|
||||
return c.json({
|
||||
id: shareLink.id,
|
||||
name: shareLink.name,
|
||||
@@ -184,7 +186,7 @@ const route = app
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
await shareService.verifyPublicAccess(shareId, shareLink.rootFolderId, password)
|
||||
|
||||
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
|
||||
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
|
||||
@@ -202,13 +204,14 @@ const route = app
|
||||
'/shares/:shareId/folders/:folderId/children',
|
||||
zValidator('query', sharedChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const folderId = c.req.param('folderId')
|
||||
const password =
|
||||
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(folderId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, folderId, password)
|
||||
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
@@ -264,11 +267,12 @@ const route = app
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
let asset = await assetService.getAsset({ assetId: fileId })
|
||||
|
||||
@@ -303,12 +307,13 @@ const route = app
|
||||
'/shares/:shareId/files/:fileId/download-url',
|
||||
zValidator('json', z.object({ key: z.string().min(1) })),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const { key } = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
if (!shareLink.allowDownload) {
|
||||
throw new ShareLinkDownloadDisabledError('Download is disabled for this share link')
|
||||
@@ -329,12 +334,13 @@ const route = app
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
let userId: string | undefined
|
||||
@@ -343,6 +349,18 @@ const route = app
|
||||
})
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else {
|
||||
const cookieName = `shumai_guest_${shareId}`
|
||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
||||
if (token) {
|
||||
const verified = verifyGuestToken(token, shareId)
|
||||
if (verified) {
|
||||
const guestUser = await userService.getUserById(verified.userId)
|
||||
if (guestUser && guestUser.guestEmail) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const res = await assetService.listComments(targetFileId, req, userId)
|
||||
return c.json(res)
|
||||
@@ -358,12 +376,15 @@ const route = app
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const guestUserId = c.req.header('x-guest-user-id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
if (req.attachmentIds && req.attachmentIds.length > 0) {
|
||||
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
@@ -377,10 +398,17 @@ const route = app
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else if (guestUserId) {
|
||||
const guestUser = await userService.getUserById(guestUserId)
|
||||
if (guestUser) {
|
||||
userId = guestUser.id
|
||||
} else {
|
||||
const cookieName = `shumai_guest_${shareId}`
|
||||
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
|
||||
if (token) {
|
||||
const verified = verifyGuestToken(token, shareId)
|
||||
if (verified) {
|
||||
const guestUser = await userService.getUserById(verified.userId)
|
||||
if (guestUser && guestUser.guestEmail) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,7 +428,7 @@ const route = app
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
await notificationService.create({
|
||||
type: notifType,
|
||||
teamId: teamId,
|
||||
creatorId: userId,
|
||||
@@ -415,11 +443,12 @@ const route = app
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId/m3u8', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
let playlist = await assetService.getHlsMasterPlaylist({
|
||||
assetId: targetAssetId,
|
||||
@@ -438,11 +467,12 @@ const route = app
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/files/:fileId/m3u8/master.m3u8', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
let playlist = await assetService.getHlsMasterPlaylist({
|
||||
assetId: targetAssetId,
|
||||
@@ -461,6 +491,7 @@ const route = app
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/files/:fileId/m3u8/:resolution', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
let resolution = c.req.param('resolution')
|
||||
if (resolution.endsWith('.m3u8')) {
|
||||
@@ -469,7 +500,7 @@ const route = app
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
const playlist = await assetService.getHlsVariantPlaylist({
|
||||
assetId: targetAssetId,
|
||||
@@ -483,12 +514,13 @@ const route = app
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/files/:fileId/m3u8/:resolution/index.m3u8', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const resolution = c.req.param('resolution')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(fileId, password)
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
const playlist = await assetService.getHlsVariantPlaylist({
|
||||
assetId: targetAssetId,
|
||||
|
||||
+54
-15
@@ -16,11 +16,14 @@ describe('S3 API', () => {
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
it('GET /files/* calls serveStatic with correct options', async () => {
|
||||
it('GET /files/* calls serveStatic with correct options when valid signature is provided', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('static-file')
|
||||
@@ -39,7 +42,40 @@ describe('S3 API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('GET /files/* returns 403 Forbidden when signature is missing', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
expect(res.status).toBe(403)
|
||||
const json = await res.json()
|
||||
expect(json.error).toContain('Forbidden')
|
||||
})
|
||||
|
||||
it('GET /files/* returns 403 Forbidden when signature is invalid', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp?Signature=invalidsig&Expires=9999999999')
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('GET /files/* returns 403 Forbidden when signature is expired', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
// Signed with -10 seconds (expired)
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp', -10)
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
|
||||
|
||||
// We need to capture the onFound callback from serveStatic options
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let onFoundCallback: ((path: string, c: any) => void) | undefined
|
||||
@@ -54,7 +90,9 @@ describe('S3 API', () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
await app.request('/files/b1/test.webp?download=1&filename=foo.png')
|
||||
await app.request(
|
||||
`/files/b1/test.webp?Signature=${signature}&Expires=${expires}&download=1&filename=foo.png`,
|
||||
)
|
||||
|
||||
expect(onFoundCallback).toBeDefined()
|
||||
|
||||
@@ -101,10 +139,7 @@ describe('S3 API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
|
||||
const { s3Service: service } = await import('@shumai/core/src/s3/s3')
|
||||
const mockPut = vi.spyOn(service, 'putObject').mockResolvedValue(undefined)
|
||||
|
||||
it('PUT /files/:bucket/:key returns 404', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
const body = new TextEncoder().encode('test-data')
|
||||
@@ -117,13 +152,17 @@ describe('S3 API', () => {
|
||||
body,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('OK')
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'b1',
|
||||
'test.webp',
|
||||
expect.any(ReadableStream),
|
||||
body.byteLength,
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('GET /files/* returns 404 when STORAGE_BACKEND is not local', async () => {
|
||||
const s3Module = await import('@shumai/core/src/s3/s3')
|
||||
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3')
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
+29
-15
@@ -1,10 +1,38 @@
|
||||
import { Hono } from 'hono'
|
||||
import { buildContentDisposition, s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
buildContentDisposition,
|
||||
getStorageBackend,
|
||||
verifyLocalGetUrlSignature,
|
||||
} from '@shumai/core/src/s3/s3'
|
||||
import { serveStatic } from 'hono/bun'
|
||||
|
||||
const route = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
if (getStorageBackend() !== 'local') {
|
||||
return c.notFound()
|
||||
}
|
||||
return next()
|
||||
})
|
||||
.get(
|
||||
'/*',
|
||||
async (c, next) => {
|
||||
const fullPath = c.req.path.replace(/^\/files\//, '').replace(/^\//, '')
|
||||
const slashIdx = fullPath.indexOf('/')
|
||||
if (slashIdx === -1) {
|
||||
return c.notFound()
|
||||
}
|
||||
const bucket = fullPath.slice(0, slashIdx)
|
||||
const key = fullPath.slice(slashIdx + 1)
|
||||
|
||||
const signature = c.req.query('Signature')
|
||||
const expires = c.req.query('Expires')
|
||||
|
||||
if (!verifyLocalGetUrlSignature(bucket, key, signature, expires)) {
|
||||
return c.json({ error: 'Forbidden: invalid or expired signature' }, 403)
|
||||
}
|
||||
|
||||
return next()
|
||||
},
|
||||
serveStatic({
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
@@ -15,19 +43,5 @@ const route = new Hono()
|
||||
},
|
||||
}),
|
||||
)
|
||||
.put('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
const contentLength = parseInt(c.req.header('content-length') || '0', 10)
|
||||
|
||||
try {
|
||||
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
|
||||
await s3Service.putObject(bucket, key, body, contentLength)
|
||||
return c.text('OK')
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -7,6 +7,9 @@ import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors'
|
||||
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
@@ -121,7 +124,7 @@ describe('Share API', () => {
|
||||
expect(body.name).toBe('Public Share')
|
||||
expect(body.hasPassword).toBe(true)
|
||||
expect(body.allowDownload).toBe(false)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass')
|
||||
})
|
||||
|
||||
test('Unauthorized', async () => {
|
||||
@@ -206,7 +209,7 @@ describe('Share API', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass')
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'folder1',
|
||||
@@ -989,7 +992,7 @@ describe('Share API', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.url).toBe('https://s3.example.com/download')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('symlink1', undefined)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
|
||||
expect(assetService.getDownloadUrl).toHaveBeenCalledWith('symlink1', 'files/target1/fly.png')
|
||||
})
|
||||
|
||||
@@ -1033,7 +1036,7 @@ describe('Share API', () => {
|
||||
expect(res.headers.get('content-type')).toContain('application/vnd.apple.mpegurl')
|
||||
const text = await res.text()
|
||||
expect(text).toContain('1080p/index.m3u8?p=secret123')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('file1', 'secret123')
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'file1', 'secret123')
|
||||
expect(assetService.getHlsMasterPlaylist).toHaveBeenCalledWith({
|
||||
assetId: 'file1',
|
||||
watermarkConfigId: null,
|
||||
@@ -1093,4 +1096,106 @@ describe('Share API', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /shares/:shareId/files/:fileId/comments', () => {
|
||||
test('rejects comments with attachmentIds on public shares', async () => {
|
||||
const res = await app.request('/shares/share1/files/file1/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: 'hi',
|
||||
attachmentIds: ['att1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toContain('Attachments are not allowed')
|
||||
})
|
||||
|
||||
test('rejects spoofed x-guest-user-id header without cookie', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
projectId: 'p1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1')
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1/comments', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-guest-user-id': 'victim_user',
|
||||
},
|
||||
body: JSON.stringify({ message: 'spoofed comment', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('allows valid guest cookie bound to shareId and creates comment', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
projectId: 'p1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1')
|
||||
vi.spyOn(userService, 'getUserById').mockResolvedValue({
|
||||
id: 'guest1',
|
||||
name: 'Guest Alice',
|
||||
guestEmail: 'alice@guest.com',
|
||||
} as unknown as Awaited<ReturnType<typeof userService.getUserById>>)
|
||||
vi.spyOn(assetService, 'createComment').mockResolvedValue({
|
||||
id: 'comm1',
|
||||
message: 'hello from alice',
|
||||
} as unknown as Awaited<ReturnType<typeof assetService.createComment>>)
|
||||
vi.spyOn(notificationService, 'create').mockResolvedValue(
|
||||
undefined as unknown as Awaited<ReturnType<typeof notificationService.create>>,
|
||||
)
|
||||
|
||||
const token = createGuestToken({ userId: 'guest1', shareId: 'share1' })
|
||||
const res = await app.request('/shares/share1/files/file1/comments', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: `shumai_guest_share1=${token}`,
|
||||
},
|
||||
body: JSON.stringify({ message: 'hello from alice', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(assetService.createComment).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 'guest1',
|
||||
message: 'hello from alice',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test('rejects guest cookie bound to a different shareId', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
projectId: 'p1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
|
||||
|
||||
const wrongToken = createGuestToken({ userId: 'guest1', shareId: 'other-share' })
|
||||
const res = await app.request('/shares/share1/files/file1/comments', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: `shumai_guest_share1=${wrongToken}`,
|
||||
},
|
||||
body: JSON.stringify({ message: 'should fail', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,6 @@ import teamRoute from './team'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
@@ -80,14 +79,12 @@ describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
@@ -95,14 +92,12 @@ describe('team api', () => {
|
||||
beforeEach(() => {
|
||||
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
|
||||
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
|
||||
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
|
||||
mockGetMe = vi.spyOn(teamService, 'getMe')
|
||||
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
|
||||
mockGetSettings = vi.spyOn(teamService, 'getSettings')
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
|
||||
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
|
||||
mockUpdateMe = vi.spyOn(teamService, 'updateMe')
|
||||
@@ -148,20 +143,9 @@ describe('team api', () => {
|
||||
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/members joins team and sends notification', async () => {
|
||||
mockJoinTeam.mockResolvedValue(undefined)
|
||||
|
||||
it('POST /teams/:teamId/members returns 404', async () => {
|
||||
const res = await app.request('/teams/t1/members', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
|
||||
expect(mockCreateNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'new_user_join_team',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/me returns user role in team', async () => {
|
||||
@@ -244,7 +228,23 @@ describe('team api', () => {
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1', { isAdmin: true })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings passes isAdmin: false when user lacks admin permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockImplementation(async (params) => {
|
||||
if (params.permission === Permission.Admin) {
|
||||
throw new Error('Forbidden')
|
||||
}
|
||||
})
|
||||
mockGetSettings.mockResolvedValue({
|
||||
archiveStorage: { enabled: true },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1', { isAdmin: false })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings does not return emailNotification to readers', async () => {
|
||||
@@ -381,6 +381,65 @@ describe('team api', () => {
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'appearance.hideAgent', true)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates autoArchive settings object', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
key: 'autoArchive',
|
||||
value: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.autoArchive.enabled).toBe(true)
|
||||
expect(data.autoArchive.days).toBe(30)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'autoArchive', {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates autoArchive.enabled individual field', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
key: 'autoArchive.enabled',
|
||||
value: false,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'autoArchive.enabled', false)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
|
||||
+11
-27
@@ -3,7 +3,6 @@ import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import {
|
||||
createTeamRequestSchema,
|
||||
getUserTeamsRequestSchema,
|
||||
@@ -31,7 +30,6 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
@@ -67,30 +65,6 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
},
|
||||
})
|
||||
})
|
||||
.post('/teams/:teamId/members', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await teamService.joinTeam({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.team_member_add,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
itemId: user.id,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/me', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
@@ -210,7 +184,17 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
const isAdmin = await authzService
|
||||
.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
|
||||
const settings = await teamService.getSettings(teamId, { isAdmin })
|
||||
return c.json(settings)
|
||||
})
|
||||
.patch(
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import uploadRoute from './upload'
|
||||
import uploadRoute, { localUploadRoute } from './upload'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import * as s3Module from '@shumai/core/src/s3/s3'
|
||||
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
|
||||
import type { PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
@@ -243,4 +244,15 @@ describe('Upload API', () => {
|
||||
)
|
||||
expect(uploadService.cancelUploadTask).toHaveBeenCalledWith('team1', 'user1', 'task1')
|
||||
})
|
||||
|
||||
describe('PUT /upload/local', () => {
|
||||
it('returns 404 when STORAGE_BACKEND is s3', async () => {
|
||||
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3')
|
||||
const localApp = new Hono().route('/', localUploadRoute)
|
||||
const res = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', {
|
||||
method: 'PUT',
|
||||
})
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,7 +14,7 @@ import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
|
||||
import { getStorageBackend, s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
@@ -23,6 +23,10 @@ export const localUploadRoute = new Hono().put(
|
||||
'/upload/local',
|
||||
zValidator('query', localUploadQuerySchema),
|
||||
async (c) => {
|
||||
if (getStorageBackend() !== 'local') {
|
||||
return c.text('Not found', 404)
|
||||
}
|
||||
|
||||
const { bucket, key, Signature } = c.req.valid('query')
|
||||
|
||||
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -262,6 +262,46 @@ describe('download_asset Operation', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('downloads PDF rendition when proxy: true is requested for Office documents with a pdfTranscode', async () => {
|
||||
const doc = await createFile('presentation.pptx', {
|
||||
key: 'files/up-office/presentation.pptx',
|
||||
media: {
|
||||
duration: 0,
|
||||
filesize: 1024,
|
||||
frames: 0,
|
||||
finishedAt: '2026-01-01T00:00:00Z',
|
||||
metadata: null,
|
||||
original: null,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
proxyType: 'pdf',
|
||||
pdfTranscode: {
|
||||
key: 'files/up-office/presentation.pdf',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const originalDownload = await runOperation(downloadAssetOp, as(owner), {
|
||||
assetIds: [doc.id],
|
||||
proxy: false,
|
||||
})
|
||||
expect(originalDownload.files[0]).toMatchObject({
|
||||
assetId: doc.id,
|
||||
kind: 'original',
|
||||
name: 'presentation.pptx',
|
||||
})
|
||||
|
||||
const proxyDownload = await runOperation(downloadAssetOp, as(owner), {
|
||||
assetIds: [doc.id],
|
||||
proxy: true,
|
||||
})
|
||||
expect(proxyDownload.files[0]).toMatchObject({
|
||||
assetId: doc.id,
|
||||
kind: 'proxy',
|
||||
name: 'presentation.pdf',
|
||||
})
|
||||
})
|
||||
|
||||
it.each([[[]], [Array.from({ length: 51 }, (_, i) => `a-${i}`)]])(
|
||||
'rejects %# asset ID lists outside 1 to 50',
|
||||
async (assetIds) => {
|
||||
|
||||
@@ -332,8 +332,8 @@ describe('AssetService Archive & Restore', () => {
|
||||
|
||||
// Batch getDownloadLinks skips archivedVideo and returns hotVideo + skippedArchivedCount = 1
|
||||
const links = await assetService.getDownloadLinks([archivedVideo.id, hotVideo.id])
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0].id).toBe(hotVideo.id)
|
||||
expect(links.files).toHaveLength(1)
|
||||
expect(links.files[0].id).toBe(hotVideo.id)
|
||||
expect(links.skippedArchivedCount).toBe(1)
|
||||
})
|
||||
|
||||
@@ -417,4 +417,101 @@ describe('AssetService Archive & Restore', () => {
|
||||
})
|
||||
expect(skAfter).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses to archive when a sibling copy sharing storageKeyId is processing or has an active task', async () => {
|
||||
const originalFile = await createProcessedFile({
|
||||
name: 'original.mp4',
|
||||
key: 'files/01SIB/original.mp4',
|
||||
})
|
||||
|
||||
// Sibling copy sharing the same storageKeyId
|
||||
const siblingFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'sibling.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processing,
|
||||
storageKeyId: originalFile.storageKeyId,
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
creatorId: owner.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Trying to archive originalFile when siblingFile is processing throws 409
|
||||
await expect(assetService.archiveAssets([originalFile.id])).rejects.toMatchObject({
|
||||
status: 409,
|
||||
message: 'Only processed assets can be archived',
|
||||
})
|
||||
|
||||
// Now set sibling to processed, but give it an active workflowTask
|
||||
await prisma.asset.update({
|
||||
where: { id: siblingFile.id },
|
||||
data: { status: AssetStatus.processed },
|
||||
})
|
||||
const activeTask = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: siblingFile.id,
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
projectId,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(assetService.archiveAssets([originalFile.id])).rejects.toMatchObject({
|
||||
status: 409,
|
||||
message: 'Cannot archive asset while a workflow task is in progress',
|
||||
})
|
||||
|
||||
// Once task completes, archive succeeds
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: activeTask.id },
|
||||
data: { status: WorkflowTaskStatus.completed },
|
||||
})
|
||||
const res = await assetService.archiveAssets([originalFile.id])
|
||||
expect(res.archivedAssetIds.sort()).toEqual([originalFile.id, siblingFile.id].sort())
|
||||
})
|
||||
|
||||
it('ignores symlinks inside folders during recursive folder archiving', async () => {
|
||||
const folder = await assetService.createAsset({
|
||||
name: 'archive-folder',
|
||||
type: 'folder',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
creatorId: owner.id,
|
||||
})
|
||||
|
||||
const realFile = await createProcessedFile({
|
||||
name: 'nested-real.mp4',
|
||||
key: 'files/01NEST/nested-real.mp4',
|
||||
parentId: folder.id,
|
||||
})
|
||||
|
||||
// External target file
|
||||
const externalFile = await createProcessedFile({
|
||||
name: 'external.mp4',
|
||||
key: 'files/01EXT/external.mp4',
|
||||
parentId: rootFolderId,
|
||||
})
|
||||
|
||||
// Create a symlink inside the folder pointing to externalFile
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'symlink-inside.mp4',
|
||||
type: AssetType.symlink,
|
||||
status: AssetStatus.processed,
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
targetId: externalFile.id,
|
||||
creatorId: owner.id,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetService.archiveAssets([folder.id])
|
||||
// Only realFile should be archived, NOT externalFile
|
||||
expect(res.archivedAssetIds).toEqual([realFile.id])
|
||||
|
||||
const extRow = await prisma.asset.findUniqueOrThrow({ where: { id: externalFile.id } })
|
||||
expect(extRow.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
import {
|
||||
AssetStatus,
|
||||
AssetType,
|
||||
Prisma,
|
||||
prisma,
|
||||
type PrismaClient,
|
||||
WorkflowTaskStatus,
|
||||
WorkflowTaskType,
|
||||
} from '@shumai/db'
|
||||
import type { ArchiveAssetsResponse, RestoreArchivedAssetsResponse } from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
|
||||
|
||||
export class AssetArchiveService {
|
||||
constructor(private readonly prismaClient: PrismaClient = prisma) {}
|
||||
|
||||
async resolveCandidateFileAssetsForArchiveOrRestore(assetIds: string[]) {
|
||||
if (assetIds.length === 0) return []
|
||||
|
||||
const topAssets = await this.prismaClient.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: { id: true, type: true },
|
||||
})
|
||||
|
||||
const foundIds = new Set(topAssets.map((a) => a.id))
|
||||
const uniqueRequested = Array.from(new Set(assetIds))
|
||||
if (foundIds.size !== uniqueRequested.length) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
|
||||
if (topAssets.some((a) => a.type === AssetType.symlink)) {
|
||||
throw new HTTPException(400, { message: 'Symlinks cannot be archived or restored' })
|
||||
}
|
||||
|
||||
const startingIds = topAssets.map((a) => a.id)
|
||||
|
||||
const expandIdsRecursively = async (rootIds: string[]) => {
|
||||
if (rootIds.length === 0) return []
|
||||
return this.prismaClient.$queryRaw<
|
||||
Array<{
|
||||
id: string
|
||||
type: string
|
||||
}>
|
||||
>`
|
||||
WITH RECURSIVE descendant AS (
|
||||
SELECT id, type::text AS type, is_deleted
|
||||
FROM assets
|
||||
WHERE id IN (${Prisma.join(rootIds)}) AND is_deleted = false AND type != 'symlink'
|
||||
UNION ALL
|
||||
SELECT a.id, a.type::text AS type, a.is_deleted
|
||||
FROM assets a
|
||||
INNER JOIN descendant d ON a.parent_id = d.id
|
||||
WHERE a.is_deleted = false AND a.type != 'symlink'
|
||||
)
|
||||
SELECT id, type FROM descendant;
|
||||
`
|
||||
}
|
||||
|
||||
const descendants = await expandIdsRecursively(startingIds)
|
||||
const fileIds = Array.from(
|
||||
new Set(descendants.filter((r) => r.type === AssetType.file).map((r) => r.id)),
|
||||
)
|
||||
|
||||
if (fileIds.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
return this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
id: { in: fileIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: {
|
||||
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: { select: { id: true, teamId: true } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
}
|
||||
|
||||
async archiveAssets(
|
||||
assetIds: string[],
|
||||
options?: {
|
||||
suppressBusyErrors?: boolean
|
||||
autoArchivePolicy?: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
},
|
||||
): Promise<ArchiveAssetsResponse> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, { message: 'Archive storage is not configured' })
|
||||
}
|
||||
if (assetIds.length === 0) {
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
|
||||
if (candidateFiles.length === 0) {
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateStorageKeyIds = Array.from(
|
||||
new Set(candidateFiles.map((f) => f.storageKeyId).filter((id): id is string => !!id)),
|
||||
)
|
||||
|
||||
// Sibling copies sharing the same storageKeyId must also be protected
|
||||
const allFilesForKeys = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
storageKeyId: { in: candidateStorageKeyIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
select: { id: true, storageKeyId: true, status: true },
|
||||
})
|
||||
|
||||
const allFileIds = allFilesForKeys.map((f) => f.id)
|
||||
|
||||
// Check active transcode/watermark tasks across candidate files AND all siblings sharing storage keys
|
||||
const activeTasks = await this.prismaClient.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: { in: allFileIds },
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
type: {
|
||||
in: [
|
||||
WorkflowTaskType.transcode,
|
||||
WorkflowTaskType.transcode_video,
|
||||
WorkflowTaskType.transcode_image,
|
||||
WorkflowTaskType.transcode_pdf,
|
||||
WorkflowTaskType.transcode_pdf_pages,
|
||||
WorkflowTaskType.transcode_screenshot,
|
||||
WorkflowTaskType.transcode_image_annotation,
|
||||
WorkflowTaskType.transcode_watermark,
|
||||
],
|
||||
},
|
||||
},
|
||||
select: { assetId: true },
|
||||
})
|
||||
const busyAssetIds = new Set(activeTasks.map((t) => t.assetId))
|
||||
|
||||
const storageKeysWithBusyTask = new Set<string>()
|
||||
const storageKeysWithUnprocessedSiblings = new Set<string>()
|
||||
|
||||
for (const f of allFilesForKeys) {
|
||||
if (!f.storageKeyId) continue
|
||||
if (busyAssetIds.has(f.id)) {
|
||||
storageKeysWithBusyTask.add(f.storageKeyId)
|
||||
}
|
||||
if (f.status === AssetStatus.uploading || f.status === AssetStatus.processing) {
|
||||
storageKeysWithUnprocessedSiblings.add(f.storageKeyId)
|
||||
}
|
||||
}
|
||||
|
||||
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
|
||||
let skippedCount = 0
|
||||
let alreadyArchivedCount = 0
|
||||
let invalidStateCount = 0
|
||||
let busyCount = 0
|
||||
|
||||
for (const file of candidateFiles) {
|
||||
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
|
||||
skippedCount++
|
||||
continue
|
||||
}
|
||||
if (
|
||||
file.status === AssetStatus.archiving ||
|
||||
file.status === AssetStatus.archived ||
|
||||
file.storageKey.isArchived
|
||||
) {
|
||||
skippedCount++
|
||||
alreadyArchivedCount++
|
||||
continue
|
||||
}
|
||||
if (busyAssetIds.has(file.id) || storageKeysWithBusyTask.has(file.storageKeyId)) {
|
||||
skippedCount++
|
||||
busyCount++
|
||||
continue
|
||||
}
|
||||
if (
|
||||
file.status !== AssetStatus.processed ||
|
||||
storageKeysWithUnprocessedSiblings.has(file.storageKeyId)
|
||||
) {
|
||||
skippedCount++
|
||||
invalidStateCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const list = eligibleByStorageKey.get(file.storageKeyId) || []
|
||||
list.push(file)
|
||||
eligibleByStorageKey.set(file.storageKeyId, list)
|
||||
}
|
||||
|
||||
if (eligibleByStorageKey.size === 0) {
|
||||
if (!options?.suppressBusyErrors) {
|
||||
if (alreadyArchivedCount === 0 && busyCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Cannot archive asset while a workflow task is in progress',
|
||||
})
|
||||
}
|
||||
if (alreadyArchivedCount === 0 && invalidStateCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Only processed assets can be archived',
|
||||
})
|
||||
}
|
||||
}
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount }
|
||||
}
|
||||
|
||||
const archivedAssetIdsSet = new Set<string>()
|
||||
const taskIds: string[] = []
|
||||
|
||||
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
|
||||
const primaryFile = filesForKey[0]
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
// 1. Lock the storageKey row to serialize concurrent archive requests
|
||||
const lockedKeys = await tx.$queryRaw<Array<{ id: string; isArchived: boolean }>>`
|
||||
SELECT id, is_archived AS "isArchived"
|
||||
FROM storage_keys
|
||||
WHERE id = ${storageKeyId}
|
||||
FOR UPDATE
|
||||
`
|
||||
if (!lockedKeys || lockedKeys.length === 0 || lockedKeys[0].isArchived) {
|
||||
return
|
||||
}
|
||||
|
||||
// If an auto-archive policy was specified, re-verify under lock that all sibling assets meet the age policy
|
||||
if (options?.autoArchivePolicy) {
|
||||
const policy = options.autoArchivePolicy
|
||||
const ineligible = await tx.asset.findFirst({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
OR: [
|
||||
{ type: { not: AssetType.file } },
|
||||
{ status: { not: AssetStatus.processed } },
|
||||
...(policy.method === 'not_updated'
|
||||
? [{ updatedAt: { gt: policy.cutoffDate } }]
|
||||
: [
|
||||
{
|
||||
OR: [
|
||||
{ createdAt: { gt: policy.cutoffDate } },
|
||||
{ updatedAt: { gt: policy.restoreCutoffDate } },
|
||||
],
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
if (ineligible) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Atomic Filter + Update: only files that are currently 'processed' transition to 'archiving'
|
||||
const updatedAssets = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
UPDATE assets
|
||||
SET status = 'archiving'::"AssetStatus", updated_at = NOW()
|
||||
WHERE storage_key_id = ${storageKeyId}
|
||||
AND type = 'file'::"AssetType"
|
||||
AND status = 'processed'::"AssetStatus"
|
||||
AND is_deleted = false
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
if (!updatedAssets || updatedAssets.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const row of updatedAssets) {
|
||||
archivedAssetIdsSet.add(row.id)
|
||||
}
|
||||
|
||||
const existingTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: { in: filesForKey.map((f) => f.id) },
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingTask) {
|
||||
taskIds.push(existingTask.id)
|
||||
} else {
|
||||
const createdTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: primaryFile.id,
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: primaryFile.project!.teamId,
|
||||
projectId: primaryFile.projectId!,
|
||||
payload: {
|
||||
projectId: primaryFile.projectId!,
|
||||
archive: { storageKeyId },
|
||||
},
|
||||
},
|
||||
})
|
||||
taskIds.push(createdTask.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
archivedAssetIds: Array.from(archivedAssetIdsSet),
|
||||
taskIds,
|
||||
skippedCount,
|
||||
}
|
||||
}
|
||||
|
||||
async restoreArchivedAssets(assetIds: string[]): Promise<RestoreArchivedAssetsResponse> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, { message: 'Archive storage is not configured' })
|
||||
}
|
||||
if (assetIds.length === 0) {
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
|
||||
if (candidateFiles.length === 0) {
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateStorageKeyIds = Array.from(
|
||||
new Set(candidateFiles.map((f) => f.storageKeyId).filter((id): id is string => !!id)),
|
||||
)
|
||||
|
||||
const allFilesForKeys = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
storageKeyId: { in: candidateStorageKeyIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
},
|
||||
select: { id: true, storageKeyId: true, status: true },
|
||||
})
|
||||
|
||||
const storageKeysWithArchivingSibling = new Set<string>()
|
||||
for (const f of allFilesForKeys) {
|
||||
if (!f.storageKeyId) continue
|
||||
if (f.status === AssetStatus.archiving) {
|
||||
storageKeysWithArchivingSibling.add(f.storageKeyId)
|
||||
}
|
||||
}
|
||||
|
||||
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
|
||||
let skippedCount = 0
|
||||
let alreadyRestoringOrHotCount = 0
|
||||
let currentlyArchivingCount = 0
|
||||
|
||||
for (const file of candidateFiles) {
|
||||
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
|
||||
skippedCount++
|
||||
continue
|
||||
}
|
||||
if (
|
||||
file.status === AssetStatus.archiving ||
|
||||
storageKeysWithArchivingSibling.has(file.storageKeyId)
|
||||
) {
|
||||
skippedCount++
|
||||
currentlyArchivingCount++
|
||||
continue
|
||||
}
|
||||
if (file.status === AssetStatus.restoring) {
|
||||
skippedCount++
|
||||
alreadyRestoringOrHotCount++
|
||||
continue
|
||||
}
|
||||
if (file.status !== AssetStatus.archived && !file.storageKey.isArchived) {
|
||||
skippedCount++
|
||||
alreadyRestoringOrHotCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const list = eligibleByStorageKey.get(file.storageKeyId) || []
|
||||
list.push(file)
|
||||
eligibleByStorageKey.set(file.storageKeyId, list)
|
||||
}
|
||||
|
||||
if (eligibleByStorageKey.size === 0) {
|
||||
if (alreadyRestoringOrHotCount === 0 && currentlyArchivingCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Cannot restore asset while it is currently archiving',
|
||||
})
|
||||
}
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount }
|
||||
}
|
||||
|
||||
const restoredAssetIdsSet = new Set<string>()
|
||||
const taskIds: string[] = []
|
||||
|
||||
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
|
||||
const primaryFile = filesForKey[0]
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const sharedAssets = await tx.asset.findMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.archived,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
const sharedAssetIds = sharedAssets.map((a) => a.id)
|
||||
|
||||
if (sharedAssetIds.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: sharedAssetIds } },
|
||||
data: { status: AssetStatus.restoring },
|
||||
})
|
||||
|
||||
for (const id of sharedAssetIds) {
|
||||
restoredAssetIdsSet.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
const existingTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: { in: filesForKey.map((f) => f.id) },
|
||||
type: WorkflowTaskType.restore_asset,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingTask) {
|
||||
taskIds.push(existingTask.id)
|
||||
} else {
|
||||
const createdTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: primaryFile.id,
|
||||
type: WorkflowTaskType.restore_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: primaryFile.project!.teamId,
|
||||
projectId: primaryFile.projectId!,
|
||||
payload: {
|
||||
projectId: primaryFile.projectId!,
|
||||
archive: { storageKeyId },
|
||||
},
|
||||
},
|
||||
})
|
||||
taskIds.push(createdTask.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
restoredAssetIds: Array.from(restoredAssetIdsSet),
|
||||
taskIds,
|
||||
skippedCount,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const assetArchiveService = new AssetArchiveService()
|
||||
|
||||
/**
|
||||
* Reverts assets referencing a StorageKey back to their baseline status (archived vs processed)
|
||||
* when an archive or restore task fails or recovers.
|
||||
*/
|
||||
export async function revertArchiveStateForStorageKey(
|
||||
storageKeyId: string,
|
||||
client: PrismaClient | Prisma.TransactionClient = prisma,
|
||||
): Promise<void> {
|
||||
const sk = await client.storageKey.findUnique({
|
||||
where: { id: storageKeyId },
|
||||
select: { isArchived: true },
|
||||
})
|
||||
if (!sk) return
|
||||
|
||||
const fallbackStatus = sk.isArchived ? AssetStatus.archived : AssetStatus.processed
|
||||
await client.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
deletedAt: null,
|
||||
type: AssetType.file,
|
||||
status: { in: [AssetStatus.archiving, AssetStatus.restoring] },
|
||||
},
|
||||
data: { status: fallbackStatus },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures an asset's storage key is not archived before allowing direct download of the original raw file.
|
||||
*/
|
||||
export async function assertStorageKeyNotArchived(
|
||||
key: string,
|
||||
client: PrismaClient | Prisma.TransactionClient = prisma,
|
||||
): Promise<void> {
|
||||
const sk = await client.storageKey.findUnique({
|
||||
where: { key },
|
||||
include: {
|
||||
assets: {
|
||||
where: { isDeleted: false },
|
||||
select: { status: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
if (
|
||||
sk &&
|
||||
(sk.isArchived ||
|
||||
sk.assets.some(
|
||||
(a) =>
|
||||
a.status === AssetStatus.archiving ||
|
||||
a.status === AssetStatus.archived ||
|
||||
a.status === AssetStatus.restoring,
|
||||
))
|
||||
) {
|
||||
throw new Error(
|
||||
`Original file for storage key "${key}" is archived. Restore the asset first or download its proxy using assetIds with proxy: true.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
import { AssetType, AssetStatus, Prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3'
|
||||
import * as archiveStorageModule from '@shumai/core/src/s3/archive-storage'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { AssetService } from './asset'
|
||||
@@ -20,7 +21,9 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
deleteObject: vi.fn().mockResolvedValue(1),
|
||||
deletePrefix: vi.fn().mockResolvedValue(1),
|
||||
copyObject: vi.fn().mockResolvedValue(undefined),
|
||||
getStoragePath: vi.fn((bucket: string, key: string) => `/mock/data/${bucket}/${key}`),
|
||||
},
|
||||
getStorageBackend: vi.fn().mockReturnValue('local'),
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/s3/preview-converter', async (importOriginal) => {
|
||||
@@ -3010,7 +3013,7 @@ describe('AssetService — natural sort by name', () => {
|
||||
// 4. file1.txt (from symlinkToFile target resolution, deduplicated)
|
||||
// 5. version2.txt (from symlinkToStack target resolution, deduplicated)
|
||||
|
||||
const fileNames = result.map((r) => r.name)
|
||||
const fileNames = result.files.map((r) => r.name)
|
||||
expect(fileNames).toHaveLength(3) // 3 unique files
|
||||
expect(fileNames).toContain('file1.txt')
|
||||
expect(fileNames).toContain('file2.txt')
|
||||
@@ -3021,7 +3024,7 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(fileNames).not.toContain('stack')
|
||||
|
||||
// Check urls are returned correctly (mock s3 presign resolves to 'http://mock-s3-url')
|
||||
for (const item of result) {
|
||||
for (const item of result.files) {
|
||||
expect(item.url).toBe('http://mock-s3-url')
|
||||
}
|
||||
|
||||
@@ -3070,9 +3073,251 @@ describe('AssetService — natural sort by name', () => {
|
||||
})
|
||||
|
||||
const result = await assetService.getDownloadLinks([symlink.id])
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].name).toBe('file1.txt')
|
||||
expect(result[0].id).toBe(file1.id)
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0].name).toBe('file1.txt')
|
||||
expect(result.files[0].id).toBe(file1.id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getStoragePaths', () => {
|
||||
it('returns empty array for empty inputs', async () => {
|
||||
const result = await assetService.getStoragePaths([])
|
||||
expect(result).toEqual({ paths: [] })
|
||||
})
|
||||
|
||||
it('resolves files, symlinks, and version stacks while skipping folders', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'StoragePathUser',
|
||||
email: `storage-path-${Date.now()}@example.com`,
|
||||
},
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'StoragePathTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'StoragePathProject', teamId: team.id },
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'MyFolder',
|
||||
type: AssetType.folder,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
storageKey: { create: { key: 'files/ulid1/clip.mp4' } },
|
||||
},
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip-symlink',
|
||||
type: AssetType.symlink,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.uploaded,
|
||||
target: { connect: { id: file.id } },
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stack.png',
|
||||
type: AssetType.version_stack,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stack_v1.png',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
sortIndex: 'b',
|
||||
storageKey: { create: { key: 'files/ulid2/stack_v1.png' } },
|
||||
},
|
||||
})
|
||||
|
||||
const latestChild = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stack_v2.png',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
sortIndex: 'a',
|
||||
storageKey: { create: { key: 'files/ulid3/stack_v2.png' } },
|
||||
},
|
||||
})
|
||||
|
||||
const result = await assetService.getStoragePaths([folder.id, file.id, symlink.id, stack.id])
|
||||
|
||||
// folder should be skipped, symlink deduplicated to file, stack resolved to latest child
|
||||
expect(result.paths).toHaveLength(2)
|
||||
const names = result.paths.map((p) => p.name)
|
||||
expect(names).toContain('clip.mp4')
|
||||
expect(names).toContain('stack_v2.png')
|
||||
|
||||
const clipPath = result.paths.find((p) => p.name === 'clip.mp4')!
|
||||
expect(clipPath.path).toContain('files/ulid1/clip.mp4')
|
||||
expect(clipPath.isArchived).toBe(false)
|
||||
|
||||
const stackPath = result.paths.find((p) => p.name === 'stack_v2.png')!
|
||||
expect(stackPath.id).toBe(latestChild.id)
|
||||
expect(stackPath.path).toContain('files/ulid3/stack_v2.png')
|
||||
})
|
||||
|
||||
it('returns S3 path when main storage backend is s3', async () => {
|
||||
vi.mocked(getStorageBackend).mockReturnValueOnce('s3')
|
||||
vi.mocked(s3Service.getStoragePath).mockReturnValueOnce('s3://shumai/files/test/s3-file.mp4')
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'P-S3', team: { create: { name: 'T-S3' } } },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'U-S3', email: `s3-${Date.now()}@example.com` },
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 's3-file.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.processed,
|
||||
storageKey: { create: { key: 'files/test/s3-file.mp4' } },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetService.getStoragePaths([file.id])
|
||||
expect(res.paths).toEqual([
|
||||
{
|
||||
id: file.id,
|
||||
name: 's3-file.mp4',
|
||||
path: 's3://shumai/files/test/s3-file.mp4',
|
||||
backend: 's3',
|
||||
isArchived: false,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('returns archive S3 path when asset is archived and archive backend is s3', async () => {
|
||||
vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce({
|
||||
path: 's3://my-archive-bucket/files/archived/clip.mp4',
|
||||
backend: 's3',
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'P-Archive-S3', team: { create: { name: 'T-Archive-S3' } } },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'U-Arch', email: `arch-${Date.now()}@example.com` },
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.archived,
|
||||
storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetService.getStoragePaths([file.id])
|
||||
expect(res.paths).toEqual([
|
||||
{
|
||||
id: file.id,
|
||||
name: 'clip.mp4',
|
||||
path: 's3://my-archive-bucket/files/archived/clip.mp4',
|
||||
backend: 's3',
|
||||
isArchived: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('returns archive local path when asset is archived and archive backend is local', async () => {
|
||||
vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce({
|
||||
path: '/mnt/archive/files/archived/clip.mp4',
|
||||
backend: 'local',
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'P-Archive-Local', team: { create: { name: 'T-Archive-Local' } } },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'U-ArchLocal', email: `archloc-${Date.now()}@example.com` },
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.archived,
|
||||
storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetService.getStoragePaths([file.id])
|
||||
expect(res.paths).toEqual([
|
||||
{
|
||||
id: file.id,
|
||||
name: 'clip.mp4',
|
||||
path: '/mnt/archive/files/archived/clip.mp4',
|
||||
backend: 'local',
|
||||
isArchived: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('marks isArchived: true with main storage path when archive storage is disabled', async () => {
|
||||
vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce(null)
|
||||
vi.mocked(s3Service.getStoragePath).mockReturnValueOnce(
|
||||
'/mock/data/shumai/files/archived/clip.mp4',
|
||||
)
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'P-DisabledArchive', team: { create: { name: 'T-DisabledArchive' } } },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'U-DisArch', email: `disarch-${Date.now()}@example.com` },
|
||||
})
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: project.id } },
|
||||
creator: { connect: { id: user.id } },
|
||||
status: AssetStatus.archived,
|
||||
storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetService.getStoragePaths([file.id])
|
||||
expect(res.paths).toEqual([
|
||||
{
|
||||
id: file.id,
|
||||
name: 'clip.mp4',
|
||||
path: '/mock/data/shumai/files/archived/clip.mp4',
|
||||
backend: 'local',
|
||||
isArchived: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+166
-350
@@ -23,6 +23,8 @@ import {
|
||||
CommentExportFormat,
|
||||
PreviewFormat,
|
||||
TRASH_RETENTION_DAYS,
|
||||
GetStoragePathsResponse,
|
||||
StoragePathItem,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
exportCommentsToFormat,
|
||||
@@ -43,11 +45,13 @@ import {
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
getArchiveStorageService,
|
||||
isArchiveStorageEnabled,
|
||||
getArchiveStoragePath,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import { assetArchiveService } from './asset-archive'
|
||||
import {
|
||||
ensureJpegInStorage,
|
||||
getJpegKeyForWebp,
|
||||
@@ -1247,6 +1251,75 @@ export class AssetService {
|
||||
return currentId
|
||||
}
|
||||
|
||||
async resolveLatestVersionIds(assetIds: string[]): Promise<string[]> {
|
||||
if (assetIds.length === 0) return []
|
||||
|
||||
const initialAssets = await this.prismaClient.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: { id: true, type: true, targetId: true },
|
||||
})
|
||||
const assetMap = new Map(initialAssets.map((a) => [a.id, a]))
|
||||
|
||||
// Find symlinks to resolve
|
||||
const symlinks = initialAssets.filter((a) => a.type === AssetType.symlink && a.targetId)
|
||||
const targetIds = Array.from(new Set(symlinks.map((s) => s.targetId!)))
|
||||
|
||||
const symlinkTargetMap = new Map<string, { id: string; type: AssetType }>()
|
||||
if (targetIds.length > 0) {
|
||||
const targets = await this.prismaClient.asset.findMany({
|
||||
where: { id: { in: targetIds }, isDeleted: false },
|
||||
select: { id: true, type: true },
|
||||
})
|
||||
for (const t of targets) {
|
||||
symlinkTargetMap.set(t.id, t)
|
||||
}
|
||||
}
|
||||
|
||||
// Determine current ID and type for each input ID
|
||||
const intermediate = assetIds.map((id) => {
|
||||
const asset = assetMap.get(id)
|
||||
if (!asset) return { originalId: id, currentId: id, type: null }
|
||||
if (asset.type === AssetType.symlink && asset.targetId) {
|
||||
const target = symlinkTargetMap.get(asset.targetId)
|
||||
if (target) {
|
||||
return { originalId: id, currentId: target.id, type: target.type }
|
||||
}
|
||||
}
|
||||
return { originalId: id, currentId: asset.id, type: asset.type }
|
||||
})
|
||||
|
||||
// Find version stacks to resolve to their latest child
|
||||
const versionStackIds = Array.from(
|
||||
new Set(
|
||||
intermediate
|
||||
.filter((item) => item.type === AssetType.version_stack)
|
||||
.map((item) => item.currentId),
|
||||
),
|
||||
)
|
||||
|
||||
const latestChildByParent = new Map<string, string>()
|
||||
if (versionStackIds.length > 0) {
|
||||
const children = await this.prismaClient.asset.findMany({
|
||||
where: { parentId: { in: versionStackIds }, isDeleted: false },
|
||||
select: { id: true, parentId: true, sortIndex: true },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
for (const child of children) {
|
||||
if (child.parentId && !latestChildByParent.has(child.parentId)) {
|
||||
latestChildByParent.set(child.parentId, child.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return intermediate.map((item) => {
|
||||
if (item.type === AssetType.version_stack) {
|
||||
const childId = latestChildByParent.get(item.currentId)
|
||||
if (childId) return childId
|
||||
}
|
||||
return item.currentId
|
||||
})
|
||||
}
|
||||
|
||||
async updateAssetName(req: UpdateAssetNameRequest): Promise<AssetInfo> {
|
||||
const existing = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.id },
|
||||
@@ -1886,7 +1959,12 @@ export class AssetService {
|
||||
const attachmentAsset = await tx.asset.findUnique({
|
||||
where: { id: attachmentId },
|
||||
})
|
||||
if (attachmentAsset) {
|
||||
if (
|
||||
attachmentAsset &&
|
||||
(attachmentAsset.type === AssetType.attachment ||
|
||||
attachmentAsset.type === AssetType.file) &&
|
||||
attachmentAsset.projectId === a.projectId
|
||||
) {
|
||||
await tx.assetCommentAttachment.create({
|
||||
data: {
|
||||
assetId: attachmentAsset.id,
|
||||
@@ -2701,10 +2779,11 @@ export class AssetService {
|
||||
return Array.from(projectIds)
|
||||
}
|
||||
|
||||
async getDownloadLinks(
|
||||
ids: string[],
|
||||
): Promise<Array<{ id: string; name: string; url: string }> & { skippedArchivedCount?: number }> {
|
||||
if (ids.length === 0) return []
|
||||
async getDownloadLinks(ids: string[]): Promise<{
|
||||
files: Array<{ id: string; name: string; url: string }>
|
||||
skippedArchivedCount: number
|
||||
}> {
|
||||
if (ids.length === 0) return { files: [], skippedArchivedCount: 0 }
|
||||
|
||||
// Resolve starting IDs (dereference top-level symlinks)
|
||||
const assets = await this.prismaClient.asset.findMany({
|
||||
@@ -2723,7 +2802,7 @@ export class AssetService {
|
||||
return asset.id
|
||||
})
|
||||
|
||||
if (startingIds.length === 0) return []
|
||||
if (startingIds.length === 0) return { files: [], skippedArchivedCount: 0 }
|
||||
|
||||
const descendants = await this.prismaClient.$queryRaw<
|
||||
Array<{
|
||||
@@ -2876,15 +2955,77 @@ export class AssetService {
|
||||
|
||||
const filteredLinks = downloadLinks.filter(
|
||||
(link): link is { id: string; name: string; url: string } => !!link,
|
||||
) as Array<{ id: string; name: string; url: string }> & { skippedArchivedCount?: number }
|
||||
)
|
||||
|
||||
Object.defineProperty(filteredLinks, 'skippedArchivedCount', {
|
||||
value: skippedArchivedCount,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
return {
|
||||
files: filteredLinks,
|
||||
skippedArchivedCount,
|
||||
}
|
||||
}
|
||||
|
||||
async getStoragePaths(ids: string[]): Promise<GetStoragePathsResponse> {
|
||||
if (ids.length === 0) return { paths: [] }
|
||||
|
||||
const targetAssetIds = await this.resolveLatestVersionIds(ids)
|
||||
const uniqueTargetIds = Array.from(new Set(targetAssetIds))
|
||||
|
||||
const assets = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
id: { in: uniqueTargetIds },
|
||||
isDeleted: false,
|
||||
type: {
|
||||
notIn: [AssetType.folder, AssetType.root, AssetType.share_root, AssetType.share],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
storageKey: {
|
||||
select: {
|
||||
key: true,
|
||||
isArchived: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return filteredLinks
|
||||
const defaultBackend = getStorageBackend()
|
||||
const mainBucket = process.env.S3_BUCKET || 'shumai'
|
||||
const paths: StoragePathItem[] = []
|
||||
|
||||
for (const asset of assets) {
|
||||
const sk = asset.storageKey
|
||||
if (!sk?.key) continue
|
||||
|
||||
const isArchived =
|
||||
asset.status === AssetStatus.archived ||
|
||||
asset.status === AssetStatus.archiving ||
|
||||
asset.status === AssetStatus.restoring ||
|
||||
sk.isArchived
|
||||
|
||||
const archivePathInfo = isArchived ? getArchiveStoragePath(sk.key) : null
|
||||
if (archivePathInfo) {
|
||||
paths.push({
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
path: archivePathInfo.path,
|
||||
backend: archivePathInfo.backend,
|
||||
isArchived: true,
|
||||
})
|
||||
} else {
|
||||
const storagePath = s3Service.getStoragePath(mainBucket, sk.key)
|
||||
paths.push({
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
path: storagePath,
|
||||
backend: defaultBackend,
|
||||
isArchived,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { paths }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2992,347 +3133,22 @@ export class AssetService {
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
||||
}
|
||||
|
||||
private async resolveCandidateFileAssetsForArchiveOrRestore(assetIds: string[]) {
|
||||
if (assetIds.length === 0) return []
|
||||
|
||||
const topAssets = await this.prismaClient.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: { id: true, type: true, targetId: true },
|
||||
})
|
||||
|
||||
const foundIds = new Set(topAssets.map((a) => a.id))
|
||||
const uniqueRequested = Array.from(new Set(assetIds))
|
||||
if (foundIds.size !== uniqueRequested.length) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
|
||||
const startingIds = topAssets.map((a) =>
|
||||
a.type === AssetType.symlink && a.targetId ? a.targetId : a.id,
|
||||
)
|
||||
|
||||
const expandIdsRecursively = async (rootIds: string[]) => {
|
||||
if (rootIds.length === 0) return []
|
||||
return this.prismaClient.$queryRaw<
|
||||
Array<{
|
||||
id: string
|
||||
type: string
|
||||
targetId: string | null
|
||||
}>
|
||||
>`
|
||||
WITH RECURSIVE descendant AS (
|
||||
SELECT id, type::text AS type, target_id, is_deleted
|
||||
FROM assets
|
||||
WHERE id IN (${Prisma.join(rootIds)}) AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.type::text AS type, a.target_id, a.is_deleted
|
||||
FROM assets a
|
||||
INNER JOIN descendant d ON a.parent_id = d.id
|
||||
WHERE a.is_deleted = false
|
||||
)
|
||||
SELECT id, type, target_id AS "targetId" FROM descendant;
|
||||
`
|
||||
}
|
||||
|
||||
const firstPass = await expandIdsRecursively(startingIds)
|
||||
const nestedSymlinkTargets = firstPass
|
||||
.filter((r) => r.type === AssetType.symlink && r.targetId)
|
||||
.map((r) => r.targetId!)
|
||||
const secondPass =
|
||||
nestedSymlinkTargets.length > 0 ? await expandIdsRecursively(nestedSymlinkTargets) : []
|
||||
|
||||
const fileIds = Array.from(
|
||||
new Set(
|
||||
[...firstPass, ...secondPass].filter((r) => r.type === AssetType.file).map((r) => r.id),
|
||||
),
|
||||
)
|
||||
|
||||
if (fileIds.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
return this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
id: { in: fileIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: {
|
||||
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: { select: { id: true, teamId: true } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
}
|
||||
|
||||
async archiveAssets(assetIds: string[]): Promise<ArchiveAssetsResponse> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, { message: 'Archive storage is not configured' })
|
||||
}
|
||||
if (assetIds.length === 0) {
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
|
||||
if (candidateFiles.length === 0) {
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
// Check active transcode/watermark tasks on candidate files
|
||||
const activeTasks = await this.prismaClient.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: { in: candidateFiles.map((f) => f.id) },
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
type: {
|
||||
in: [
|
||||
WorkflowTaskType.transcode,
|
||||
WorkflowTaskType.transcode_video,
|
||||
WorkflowTaskType.transcode_image,
|
||||
WorkflowTaskType.transcode_pdf,
|
||||
WorkflowTaskType.transcode_pdf_pages,
|
||||
WorkflowTaskType.transcode_screenshot,
|
||||
WorkflowTaskType.transcode_image_annotation,
|
||||
WorkflowTaskType.transcode_watermark,
|
||||
],
|
||||
},
|
||||
},
|
||||
select: { assetId: true },
|
||||
})
|
||||
const busyAssetIds = new Set(activeTasks.map((t) => t.assetId))
|
||||
|
||||
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
|
||||
let skippedCount = 0
|
||||
let alreadyArchivedCount = 0
|
||||
let invalidStateCount = 0
|
||||
let busyCount = 0
|
||||
|
||||
for (const file of candidateFiles) {
|
||||
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
|
||||
skippedCount++
|
||||
continue
|
||||
async archiveAssets(
|
||||
assetIds: string[],
|
||||
options?: {
|
||||
suppressBusyErrors?: boolean
|
||||
autoArchivePolicy?: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
if (
|
||||
file.status === AssetStatus.archiving ||
|
||||
file.status === AssetStatus.archived ||
|
||||
file.storageKey.isArchived
|
||||
) {
|
||||
skippedCount++
|
||||
alreadyArchivedCount++
|
||||
continue
|
||||
}
|
||||
if (busyAssetIds.has(file.id)) {
|
||||
skippedCount++
|
||||
busyCount++
|
||||
continue
|
||||
}
|
||||
if (file.status !== AssetStatus.processed) {
|
||||
skippedCount++
|
||||
invalidStateCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const list = eligibleByStorageKey.get(file.storageKeyId) || []
|
||||
list.push(file)
|
||||
eligibleByStorageKey.set(file.storageKeyId, list)
|
||||
}
|
||||
|
||||
if (eligibleByStorageKey.size === 0) {
|
||||
if (alreadyArchivedCount === 0 && busyCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Cannot archive asset while a workflow task is in progress',
|
||||
})
|
||||
}
|
||||
if (alreadyArchivedCount === 0 && invalidStateCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Only processed assets can be archived',
|
||||
})
|
||||
}
|
||||
return { archivedAssetIds: [], taskIds: [], skippedCount }
|
||||
}
|
||||
|
||||
const archivedAssetIdsSet = new Set<string>()
|
||||
const taskIds: string[] = []
|
||||
|
||||
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
|
||||
const primaryFile = filesForKey[0]
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const sharedAssets = await tx.asset.findMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: {
|
||||
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
const sharedAssetIds = sharedAssets.map((a) => a.id)
|
||||
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: sharedAssetIds } },
|
||||
data: { status: AssetStatus.archiving },
|
||||
})
|
||||
|
||||
for (const id of sharedAssetIds) {
|
||||
archivedAssetIdsSet.add(id)
|
||||
}
|
||||
|
||||
const existingTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: { in: sharedAssetIds },
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingTask) {
|
||||
taskIds.push(existingTask.id)
|
||||
} else {
|
||||
const createdTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: primaryFile.id,
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: primaryFile.project!.teamId,
|
||||
projectId: primaryFile.projectId!,
|
||||
payload: {
|
||||
projectId: primaryFile.projectId!,
|
||||
archive: { storageKeyId },
|
||||
},
|
||||
},
|
||||
})
|
||||
taskIds.push(createdTask.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
archivedAssetIds: Array.from(archivedAssetIdsSet),
|
||||
taskIds,
|
||||
skippedCount,
|
||||
}
|
||||
},
|
||||
): Promise<ArchiveAssetsResponse> {
|
||||
return assetArchiveService.archiveAssets(assetIds, options)
|
||||
}
|
||||
|
||||
async restoreArchivedAssets(assetIds: string[]): Promise<RestoreArchivedAssetsResponse> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, { message: 'Archive storage is not configured' })
|
||||
}
|
||||
if (assetIds.length === 0) {
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const candidateFiles = await this.resolveCandidateFileAssetsForArchiveOrRestore(assetIds)
|
||||
if (candidateFiles.length === 0) {
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount: 0 }
|
||||
}
|
||||
|
||||
const eligibleByStorageKey = new Map<string, typeof candidateFiles>()
|
||||
let skippedCount = 0
|
||||
let alreadyRestoringOrHotCount = 0
|
||||
let currentlyArchivingCount = 0
|
||||
|
||||
for (const file of candidateFiles) {
|
||||
if (!file.storageKeyId || !file.storageKey || !file.projectId || !file.project?.teamId) {
|
||||
skippedCount++
|
||||
continue
|
||||
}
|
||||
if (file.status === AssetStatus.archiving) {
|
||||
skippedCount++
|
||||
currentlyArchivingCount++
|
||||
continue
|
||||
}
|
||||
if (file.status === AssetStatus.restoring) {
|
||||
skippedCount++
|
||||
alreadyRestoringOrHotCount++
|
||||
continue
|
||||
}
|
||||
if (file.status !== AssetStatus.archived && !file.storageKey.isArchived) {
|
||||
skippedCount++
|
||||
alreadyRestoringOrHotCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const list = eligibleByStorageKey.get(file.storageKeyId) || []
|
||||
list.push(file)
|
||||
eligibleByStorageKey.set(file.storageKeyId, list)
|
||||
}
|
||||
|
||||
if (eligibleByStorageKey.size === 0) {
|
||||
if (alreadyRestoringOrHotCount === 0 && currentlyArchivingCount > 0) {
|
||||
throw new HTTPException(409, {
|
||||
message: 'Cannot restore asset while it is currently archiving',
|
||||
})
|
||||
}
|
||||
return { restoredAssetIds: [], taskIds: [], skippedCount }
|
||||
}
|
||||
|
||||
const restoredAssetIdsSet = new Set<string>()
|
||||
const taskIds: string[] = []
|
||||
|
||||
for (const [storageKeyId, filesForKey] of eligibleByStorageKey.entries()) {
|
||||
const primaryFile = filesForKey[0]
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const sharedAssets = await tx.asset.findMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
type: AssetType.file,
|
||||
status: {
|
||||
notIn: [AssetStatus.trashed, AssetStatus.pending_purge],
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
const sharedAssetIds = sharedAssets.map((a) => a.id)
|
||||
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: sharedAssetIds } },
|
||||
data: { status: AssetStatus.restoring },
|
||||
})
|
||||
|
||||
for (const id of sharedAssetIds) {
|
||||
restoredAssetIdsSet.add(id)
|
||||
}
|
||||
|
||||
const existingTask = await tx.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: { in: sharedAssetIds },
|
||||
type: WorkflowTaskType.restore_asset,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingTask) {
|
||||
taskIds.push(existingTask.id)
|
||||
} else {
|
||||
const createdTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: primaryFile.id,
|
||||
type: WorkflowTaskType.restore_asset,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: primaryFile.project!.teamId,
|
||||
projectId: primaryFile.projectId!,
|
||||
payload: {
|
||||
projectId: primaryFile.projectId!,
|
||||
archive: { storageKeyId },
|
||||
},
|
||||
},
|
||||
})
|
||||
taskIds.push(createdTask.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
restoredAssetIds: Array.from(restoredAssetIdsSet),
|
||||
taskIds,
|
||||
skippedCount,
|
||||
}
|
||||
return assetArchiveService.restoreArchivedAssets(assetIds)
|
||||
}
|
||||
|
||||
async toPreviewInfo(
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import {
|
||||
AssetStatus,
|
||||
prisma,
|
||||
Prisma,
|
||||
WorkflowTaskType,
|
||||
WorkflowTaskStatus,
|
||||
type User,
|
||||
} from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { assetService } from './asset'
|
||||
import { assetArchiveService } from './asset-archive'
|
||||
import { resetArchiveStorageServiceForTests } from '../s3/archive-storage'
|
||||
import {
|
||||
AutoArchiveJobService,
|
||||
autoArchiveJobService,
|
||||
getAutoArchiveIntervalMs,
|
||||
} from './auto-archive-job'
|
||||
|
||||
describe('AutoArchiveJobService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const archiveRoot = path.join(process.cwd(), 'data-test-auto-archive')
|
||||
let originalEnv: NodeJS.ProcessEnv
|
||||
let owner: User
|
||||
let teamId: string
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
originalEnv = { ...process.env }
|
||||
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
|
||||
process.env.ARCHIVE_LOCAL_ROOT = archiveRoot
|
||||
resetArchiveStorageServiceForTests()
|
||||
|
||||
if (fs.existsSync(archiveRoot)) {
|
||||
fs.rmSync(archiveRoot, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
owner = await prisma.user.create({
|
||||
data: { name: 'Auto Archive Owner', email: 'auto-archive-owner@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Auto Archive Team',
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
teamId = team.id
|
||||
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
|
||||
|
||||
const project = await projectService.createProject(owner, { teamId, name: 'Archive Project' })
|
||||
projectId = project.id
|
||||
rootFolderId = project.rootFolder!
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
resetArchiveStorageServiceForTests()
|
||||
if (fs.existsSync(archiveRoot)) {
|
||||
fs.rmSync(archiveRoot, { recursive: true, force: true })
|
||||
}
|
||||
autoArchiveJobService.stop()
|
||||
})
|
||||
|
||||
async function createTestFile(params: {
|
||||
name: string
|
||||
key: string
|
||||
createdAt?: Date
|
||||
updatedAt?: Date
|
||||
status?: AssetStatus
|
||||
}) {
|
||||
const asset = await assetService.createAsset({
|
||||
name: params.name,
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: params.key,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
|
||||
const updated = await prisma.asset.update({
|
||||
where: { id: asset.id },
|
||||
data: {
|
||||
status: params.status ?? AssetStatus.processed,
|
||||
createdAt: params.createdAt ?? new Date(),
|
||||
updatedAt: params.updatedAt ?? new Date(),
|
||||
},
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
return updated
|
||||
}
|
||||
|
||||
describe('getAutoArchiveIntervalMs', () => {
|
||||
it('returns default 1 hour (3600000ms) when env not specified', () => {
|
||||
delete process.env.AUTO_ARCHIVE_INTERVAL_MINUTES
|
||||
expect(getAutoArchiveIntervalMs()).toBe(3600000)
|
||||
})
|
||||
|
||||
it('parses integer minute strings', () => {
|
||||
process.env.AUTO_ARCHIVE_INTERVAL_MINUTES = '30'
|
||||
expect(getAutoArchiveIntervalMs()).toBe(1800000)
|
||||
})
|
||||
|
||||
it('parses decimal floating point minute strings', () => {
|
||||
process.env.AUTO_ARCHIVE_INTERVAL_MINUTES = '0.02'
|
||||
expect(getAutoArchiveIntervalMs()).toBe(1200)
|
||||
})
|
||||
})
|
||||
|
||||
it('skips scan when archive storage is not configured', async () => {
|
||||
delete process.env.ARCHIVE_STORAGE_BACKEND
|
||||
resetArchiveStorageServiceForTests()
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('skips teams where autoArchive is disabled', async () => {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
await createTestFile({
|
||||
name: 'old-file.mp4',
|
||||
key: 'files/test/old-file.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('archives assets exceeding not_updated threshold while leaving recent assets untouched', async () => {
|
||||
const oldDate = new Date(Date.now() - 35 * 86_400_000)
|
||||
const recentDate = new Date(Date.now() - 5 * 86_400_000)
|
||||
|
||||
const oldFile = await createTestFile({
|
||||
name: 'old-file.mp4',
|
||||
key: 'files/test/old-file.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const recentFile = await createTestFile({
|
||||
name: 'recent-file.mp4',
|
||||
key: 'files/test/recent-file.mp4',
|
||||
updatedAt: recentDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedOld = await prisma.asset.findUniqueOrThrow({ where: { id: oldFile.id } })
|
||||
const refreshedRecent = await prisma.asset.findUniqueOrThrow({ where: { id: recentFile.id } })
|
||||
|
||||
expect(refreshedOld.status).toBe(AssetStatus.archiving)
|
||||
expect(refreshedRecent.status).toBe(AssetStatus.processed)
|
||||
|
||||
const task = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: oldFile.id, type: WorkflowTaskType.archive_asset },
|
||||
})
|
||||
expect(task).not.toBeNull()
|
||||
expect(task?.status).toBe(WorkflowTaskStatus.pending)
|
||||
})
|
||||
|
||||
it('archives assets exceeding after_created threshold and respects postRestoreGraceDays', async () => {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 14,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const oldCreatedDate = new Date(Date.now() - 45 * 86_400_000)
|
||||
const recentlyRestoredDate = new Date(Date.now() - 2 * 86_400_000)
|
||||
const oldRestoredDate = new Date(Date.now() - 20 * 86_400_000)
|
||||
|
||||
// Old creation, but restored 2 days ago (within 14-day grace period) -> should NOT archive
|
||||
const restoredRecently = await createTestFile({
|
||||
name: 'restored-recently.mp4',
|
||||
key: 'files/test/restored-recently.mp4',
|
||||
createdAt: oldCreatedDate,
|
||||
updatedAt: recentlyRestoredDate,
|
||||
})
|
||||
|
||||
// Old creation, restored 20 days ago (> 14-day grace period) -> SHOULD archive
|
||||
const restoredLongAgo = await createTestFile({
|
||||
name: 'restored-long-ago.mp4',
|
||||
key: 'files/test/restored-long-ago.mp4',
|
||||
createdAt: oldCreatedDate,
|
||||
updatedAt: oldRestoredDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedRecently = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: restoredRecently.id },
|
||||
})
|
||||
const refreshedLongAgo = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: restoredLongAgo.id },
|
||||
})
|
||||
|
||||
expect(refreshedRecently.status).toBe(AssetStatus.processed)
|
||||
expect(refreshedLongAgo.status).toBe(AssetStatus.archiving)
|
||||
})
|
||||
|
||||
it('skips storage key if any sibling file sharing the key was recently modified', async () => {
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
const recentDate = new Date()
|
||||
|
||||
const sharedKey = 'files/test/shared-video.mp4'
|
||||
|
||||
const primaryFile = await createTestFile({
|
||||
name: 'primary.mp4',
|
||||
key: sharedKey,
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
// Create a sibling copy sharing the same storageKeyId but modified recently
|
||||
const siblingCopy = await assetService.createAsset({
|
||||
name: 'sibling-copy.mp4',
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: sharedKey,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id: siblingCopy.id },
|
||||
data: {
|
||||
status: AssetStatus.processed,
|
||||
updatedAt: recentDate,
|
||||
},
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(0)
|
||||
|
||||
const refreshedPrimary = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: primaryFile.id },
|
||||
})
|
||||
expect(refreshedPrimary.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('handles race conditions: concurrent archive attempts cleanly serialize without duplicate tasks', async () => {
|
||||
const oldDate = new Date(Date.now() - 50 * 86_400_000)
|
||||
const file = await createTestFile({
|
||||
name: 'concurrent-test.mp4',
|
||||
key: 'files/test/concurrent-test.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
|
||||
// Trigger auto-archive and manual archive concurrently
|
||||
const [jobRes, manualRes] = await Promise.all([
|
||||
job.processAutoArchive(),
|
||||
assetService.archiveAssets([file.id], { suppressBusyErrors: true }),
|
||||
])
|
||||
|
||||
// Together they should archive the asset exactly once
|
||||
const totalArchived = jobRes.archivedCount + manualRes.archivedAssetIds.length
|
||||
expect(totalArchived).toBe(1)
|
||||
|
||||
// Verify exactly ONE WorkflowTask was created
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: { assetId: file.id, type: WorkflowTaskType.archive_asset },
|
||||
})
|
||||
expect(tasks).toHaveLength(1)
|
||||
|
||||
const refreshedFile = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
|
||||
expect(refreshedFile.status).toBe(AssetStatus.archiving)
|
||||
})
|
||||
|
||||
it('prevents candidate starvation: storage keys with stuck siblings are ignored so eligible candidates are not blocked', async () => {
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
|
||||
// Key 1: has an old file AND a stuck sibling with status 'failed'
|
||||
const stuckKey = 'files/test/stuck-sibling.mp4'
|
||||
const fileWithStuckSibling = await createTestFile({
|
||||
name: 'stuck-primary.mp4',
|
||||
key: stuckKey,
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
const stuckSibling = await assetService.createAsset({
|
||||
name: 'stuck-sibling-failed.mp4',
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: stuckKey,
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/mp4',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: stuckSibling.id },
|
||||
data: {
|
||||
status: AssetStatus.failed,
|
||||
updatedAt: oldDate,
|
||||
},
|
||||
})
|
||||
|
||||
// Key 2: fully eligible old file
|
||||
const eligibleFile = await createTestFile({
|
||||
name: 'eligible-siblingless.mp4',
|
||||
key: 'files/test/eligible-siblingless.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
// With batchSize 1, the query must pick the eligible file instead of getting stuck on Key 1
|
||||
const res = await job.processAutoArchive(1)
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
|
||||
const refreshedEligible = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: eligibleFile.id },
|
||||
})
|
||||
expect(refreshedEligible.status).toBe(AssetStatus.archiving)
|
||||
|
||||
const refreshedStuck = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: fileWithStuckSibling.id },
|
||||
})
|
||||
expect(refreshedStuck.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('skips scan when another process holds the transaction advisory lock', async () => {
|
||||
const queryRawSpy = vi.spyOn(prisma, '$queryRaw').mockImplementation((query: unknown) => {
|
||||
const sqlText = String((query as { strings?: string[] })?.strings || '')
|
||||
if (sqlText.includes('pg_try_advisory_xact_lock')) {
|
||||
return Promise.resolve([{ locked: false }]) as unknown as Prisma.PrismaPromise<unknown>
|
||||
}
|
||||
queryRawSpy.mockRestore()
|
||||
return prisma.$queryRaw(query as TemplateStringsArray)
|
||||
})
|
||||
|
||||
try {
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
expect(res.archivedCount).toBe(0)
|
||||
} finally {
|
||||
queryRawSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('logs info level message on job start and finish with totalArchived count', async () => {
|
||||
const infoSpy = vi.spyOn(logger, 'info')
|
||||
|
||||
const oldDate = new Date(Date.now() - 40 * 86_400_000)
|
||||
await createTestFile({
|
||||
name: 'log-test.mp4',
|
||||
key: 'files/test/log-test.mp4',
|
||||
updatedAt: oldDate,
|
||||
})
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(1)
|
||||
expect(infoSpy).toHaveBeenCalledWith('Auto-archive job started')
|
||||
expect(infoSpy).toHaveBeenCalledWith({ totalArchived: 1 }, 'Auto-archive job finished')
|
||||
|
||||
infoSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('does not log info level messages when no files are eligible to archive', async () => {
|
||||
const infoSpy = vi.spyOn(logger, 'info')
|
||||
|
||||
const job = new AutoArchiveJobService()
|
||||
const res = await job.processAutoArchive()
|
||||
|
||||
expect(res.archivedCount).toBe(0)
|
||||
expect(infoSpy).not.toHaveBeenCalledWith('Auto-archive job started')
|
||||
expect(infoSpy).not.toHaveBeenCalledWith(expect.anything(), 'Auto-archive job finished')
|
||||
|
||||
infoSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('does not archive non-file assets even if their status is processed and age criteria met', async () => {
|
||||
const oldDate = new Date(Date.now() - 50 * 86_400_000)
|
||||
|
||||
const folder = await assetService.createAsset({
|
||||
name: 'Old Folder',
|
||||
type: 'folder',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
creatorId: owner.id,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: folder.id },
|
||||
data: {
|
||||
status: AssetStatus.processed,
|
||||
updatedAt: oldDate,
|
||||
createdAt: oldDate,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await assetArchiveService.archiveAssets([folder.id], {
|
||||
suppressBusyErrors: true,
|
||||
autoArchivePolicy: {
|
||||
method: 'not_updated',
|
||||
cutoffDate: new Date(),
|
||||
restoreCutoffDate: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
expect(res.archivedAssetIds).toHaveLength(0)
|
||||
|
||||
const refreshedFolder = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: folder.id },
|
||||
})
|
||||
expect(refreshedFolder.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
|
||||
it('can start and stop without errors', () => {
|
||||
const job = new AutoArchiveJobService()
|
||||
job.start(1000, 5000)
|
||||
job.stop()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { prisma, Prisma } from '@shumai/db'
|
||||
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
|
||||
import { assetArchiveService } from '@shumai/core/src/asset/asset-archive'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export function getAutoArchiveIntervalMs(): number {
|
||||
const raw = process.env.AUTO_ARCHIVE_INTERVAL_MINUTES
|
||||
if (raw) {
|
||||
const parsed = Number.parseFloat(raw)
|
||||
if (!Number.isNaN(parsed) && parsed > 0) {
|
||||
return Math.round(parsed * 60 * 1000)
|
||||
}
|
||||
}
|
||||
return 60 * 60 * 1000 // default 1 hour
|
||||
}
|
||||
|
||||
interface TeamArchiveBatch {
|
||||
teamId: string
|
||||
assetIds: string[]
|
||||
policy: {
|
||||
method: 'not_updated' | 'after_created'
|
||||
cutoffDate: Date
|
||||
restoreCutoffDate: Date
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoArchiveJobService {
|
||||
private isRunning = false
|
||||
private isProcessing = false
|
||||
private timer: NodeJS.Timeout | null = null
|
||||
|
||||
start(initialDelayMs = 60_000, intervalMs?: number): void {
|
||||
if (this.isRunning) return
|
||||
this.isRunning = true
|
||||
logger.info('Starting auto-archive background job')
|
||||
|
||||
const run = async () => {
|
||||
if (!this.isRunning) return
|
||||
try {
|
||||
await this.processAutoArchive()
|
||||
} catch (err: unknown) {
|
||||
logger.error({ err }, 'Error in auto-archive background job')
|
||||
}
|
||||
|
||||
if (this.isRunning) {
|
||||
const nextInterval = intervalMs ?? getAutoArchiveIntervalMs()
|
||||
this.timer = setTimeout(run, nextInterval)
|
||||
}
|
||||
}
|
||||
|
||||
this.timer = setTimeout(run, initialDelayMs)
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.isRunning = false
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
logger.info('Stopped auto-archive background job')
|
||||
}
|
||||
|
||||
async processAutoArchive(batchSize = 100): Promise<{ archivedCount: number }> {
|
||||
if (!isArchiveStorageEnabled()) {
|
||||
logger.debug('Archive storage is not configured; skipping auto-archive run')
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
if (this.isProcessing) {
|
||||
logger.debug('Auto-archive job turn already in progress, skipping')
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
this.isProcessing = true
|
||||
|
||||
try {
|
||||
let totalArchived = 0
|
||||
|
||||
// Phase 1: Query & Scan under transaction-scoped advisory lock.
|
||||
// Automatically released as soon as this transaction completes.
|
||||
const teamBatches = await prisma.$transaction(async (tx) => {
|
||||
const lockRes = await tx.$queryRaw<Array<{ locked: boolean }>>`
|
||||
SELECT pg_try_advisory_xact_lock(hashtext('auto_archive_job')) AS locked
|
||||
`
|
||||
if (!lockRes || !lockRes[0]?.locked) {
|
||||
logger.debug(
|
||||
'Could not acquire transaction advisory lock for auto-archive scan, skipping',
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
// Query only teams where autoArchive is enabled via JSON filter
|
||||
const eligibleTeams = await tx.team.findMany({
|
||||
where: {
|
||||
settings: {
|
||||
path: ['autoArchive', 'enabled'],
|
||||
equals: true,
|
||||
},
|
||||
},
|
||||
select: { id: true, settings: true },
|
||||
})
|
||||
|
||||
if (eligibleTeams.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const batches: TeamArchiveBatch[] = []
|
||||
|
||||
for (const team of eligibleTeams) {
|
||||
const settings = (team.settings || {}) as PrismaJson.Settings
|
||||
const autoArchive = settings.autoArchive
|
||||
const method = autoArchive?.method || 'not_updated'
|
||||
const days = Math.max(1, autoArchive?.days || 30)
|
||||
const postRestoreGraceDays = Math.max(1, autoArchive?.postRestoreGraceDays || 30)
|
||||
|
||||
const now = Date.now()
|
||||
const cutoffDate = new Date(now - days * 86_400_000)
|
||||
const restoreCutoffDate = new Date(now - postRestoreGraceDays * 86_400_000)
|
||||
|
||||
// Query candidate assets whose storage keys have NO ineligible sibling.
|
||||
// NOT EXISTS eliminates starvation from stuck/recent siblings at the database level.
|
||||
const candidateRows = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT a.id
|
||||
FROM assets a
|
||||
JOIN projects p ON a.project_id = p.id
|
||||
JOIN storage_keys sk ON a.storage_key_id = sk.id
|
||||
WHERE p.team_id = ${team.id}
|
||||
AND a.type = 'file'::"AssetType"
|
||||
AND a.status = 'processed'::"AssetStatus"
|
||||
AND a.is_deleted = false
|
||||
AND sk.is_archived = false
|
||||
AND ${
|
||||
method === 'not_updated'
|
||||
? Prisma.sql`a.updated_at <= ${cutoffDate}`
|
||||
: Prisma.sql`a.created_at <= ${cutoffDate} AND a.updated_at <= ${restoreCutoffDate}`
|
||||
}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM assets sib
|
||||
WHERE sib.storage_key_id = a.storage_key_id
|
||||
AND sib.is_deleted = false
|
||||
AND (
|
||||
sib.type != 'file'::"AssetType"
|
||||
OR sib.status != 'processed'::"AssetStatus"
|
||||
OR ${
|
||||
method === 'not_updated'
|
||||
? Prisma.sql`sib.updated_at > ${cutoffDate}`
|
||||
: Prisma.sql`sib.created_at > ${cutoffDate} OR sib.updated_at > ${restoreCutoffDate}`
|
||||
}
|
||||
)
|
||||
)
|
||||
ORDER BY a.id ASC
|
||||
LIMIT ${batchSize};
|
||||
`
|
||||
|
||||
if (candidateRows.length > 0) {
|
||||
batches.push({
|
||||
teamId: team.id,
|
||||
assetIds: candidateRows.map((r) => r.id),
|
||||
policy: { method, cutoffDate, restoreCutoffDate },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return batches
|
||||
})
|
||||
|
||||
if (!teamBatches || teamBatches.length === 0) {
|
||||
return { archivedCount: 0 }
|
||||
}
|
||||
|
||||
logger.info('Auto-archive job started')
|
||||
|
||||
// Phase 2: Execute archival in chunks per team batch.
|
||||
// Each asset/storageKey transition is protected by row-level lock and re-verifies policy.
|
||||
const chunkSize = 50
|
||||
|
||||
for (const batch of teamBatches) {
|
||||
for (let i = 0; i < batch.assetIds.length; i += chunkSize) {
|
||||
const chunk = batch.assetIds.slice(i, i + chunkSize)
|
||||
const result = await assetArchiveService.archiveAssets(chunk, {
|
||||
suppressBusyErrors: true,
|
||||
autoArchivePolicy: batch.policy,
|
||||
})
|
||||
totalArchived += result.archivedAssetIds.length
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({ totalArchived }, 'Auto-archive job finished')
|
||||
return { archivedCount: totalArchived }
|
||||
} finally {
|
||||
this.isProcessing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const autoArchiveJobService = new AutoArchiveJobService()
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { auth, authService } from './auth'
|
||||
import { auth, authService, isLoopbackHost, isMcpResourceValid } from './auth'
|
||||
import { userMetadataService } from '../user-metadata/user-metadata'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
@@ -326,3 +326,48 @@ describe('AuthService Password Reset', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('MCP Resource Validation & Loopback Checking', () => {
|
||||
it('correctly identifies loopback hostnames', () => {
|
||||
expect(isLoopbackHost('localhost')).toBe(true)
|
||||
expect(isLoopbackHost('127.0.0.1')).toBe(true)
|
||||
expect(isLoopbackHost('127.0.0.254')).toBe(true)
|
||||
expect(isLoopbackHost('[::1]')).toBe(true)
|
||||
|
||||
expect(isLoopbackHost('43.133.100.178')).toBe(false)
|
||||
expect(isLoopbackHost('192.168.1.100')).toBe(false)
|
||||
expect(isLoopbackHost('10.0.0.1')).toBe(false)
|
||||
expect(isLoopbackHost('example.com')).toBe(false)
|
||||
expect(isLoopbackHost('128.0.0.1')).toBe(false)
|
||||
})
|
||||
|
||||
it('validates MCP resource URLs according to RFC 9728 and MCP security rules', () => {
|
||||
// Loopback HTTP URLs are allowed for development
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('http://127.0.0.1:3000/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('http://[::1]:3000/mcp')).toEqual({ valid: true })
|
||||
|
||||
// HTTPS is allowed for any host (including domains and remote IPs)
|
||||
expect(isMcpResourceValid('https://shumai.example.com/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('https://43.133.100.178:3000/mcp')).toEqual({ valid: true })
|
||||
|
||||
// Remote HTTP IPs and hostnames are rejected (the user issue)
|
||||
const remoteIpResult = isMcpResourceValid('http://43.133.100.178:3000/mcp')
|
||||
expect(remoteIpResult.valid).toBe(false)
|
||||
expect(remoteIpResult.error).toContain(
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
)
|
||||
|
||||
const remoteDomainResult = isMcpResourceValid('http://shumai.example.com/mcp')
|
||||
expect(remoteDomainResult.valid).toBe(false)
|
||||
expect(remoteDomainResult.error).toContain(
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
)
|
||||
|
||||
// Invalid URL formats
|
||||
expect(isMcpResourceValid('not-a-url').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://user:pass@localhost:3000/mcp').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp#frag').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp?query=1').valid).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { teamService } from '@shumai/core/src/team/team'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { createAuthMiddleware } from 'better-auth/api'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
interface GeneratedResetLink {
|
||||
url: string
|
||||
@@ -22,22 +23,80 @@ export const authBaseUrl = (
|
||||
export const mcpResource = `${authBaseUrl}/mcp`
|
||||
export { hashPassword } from 'better-auth/crypto'
|
||||
|
||||
/**
|
||||
* Checks whether a host is a loopback address (localhost, 127.0.0.0/8, or [::1]).
|
||||
*/
|
||||
export function isLoopbackHost(hostname: string): boolean {
|
||||
const ipv4Octets = hostname.split('.')
|
||||
const isIpv4Loopback =
|
||||
ipv4Octets.length === 4 &&
|
||||
ipv4Octets[0] === '127' &&
|
||||
ipv4Octets.every((octet) => /^\d+$/.test(octet) && Number(octet) <= 255)
|
||||
return hostname === 'localhost' || hostname === '[::1]' || isIpv4Loopback
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates whether an MCP resource URL meets RFC 9728 and MCP security requirements
|
||||
* (HTTPS required unless using a localhost or loopback IP address).
|
||||
*/
|
||||
export function isMcpResourceValid(resource: string): { valid: boolean; error?: string } {
|
||||
if (typeof resource !== 'string' || !resource) {
|
||||
return { valid: false, error: 'MCP resource must be a non-empty string URL' }
|
||||
}
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(resource)
|
||||
} catch {
|
||||
return { valid: false, error: 'MCP resource must be an absolute URL' }
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain credentials' }
|
||||
}
|
||||
if (resource.includes('#')) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain a fragment' }
|
||||
}
|
||||
if (resource.includes('?')) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain a query' }
|
||||
}
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) {
|
||||
return {
|
||||
valid: false,
|
||||
error:
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
}
|
||||
}
|
||||
return { valid: true }
|
||||
}
|
||||
|
||||
const mcpValidation = isMcpResourceValid(mcpResource)
|
||||
export const isMcpOauthEnabled = mcpValidation.valid
|
||||
if (!isMcpOauthEnabled) {
|
||||
logger.error(
|
||||
{ mcpResource, error: mcpValidation.error },
|
||||
'MCP OAuth 2.1 is disabled: resource URL must use HTTPS for remote hosts. The main server and Web UI will continue running normally, but MCP OAuth clients cannot connect until HTTPS is configured.',
|
||||
)
|
||||
}
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: 'postgresql',
|
||||
}),
|
||||
plugins: [
|
||||
jwt(),
|
||||
mcp({
|
||||
loginPage: '/login',
|
||||
consentPage: '/consent',
|
||||
resource: mcpResource,
|
||||
resources: [{ identifier: mcpResource, allowedScopes: ['mcp'] }],
|
||||
scopes: ['openid', 'profile', 'email', 'offline_access', 'mcp'],
|
||||
allowDynamicClientRegistration: true,
|
||||
allowUnauthenticatedClientRegistration: true,
|
||||
clientRegistrationDefaultApplicationType: 'infer',
|
||||
}),
|
||||
...(isMcpOauthEnabled
|
||||
? [
|
||||
mcp({
|
||||
loginPage: '/login',
|
||||
consentPage: '/consent',
|
||||
resource: mcpResource,
|
||||
resources: [{ identifier: mcpResource, allowedScopes: ['mcp'] }],
|
||||
scopes: ['openid', 'profile', 'email', 'offline_access', 'mcp'],
|
||||
allowDynamicClientRegistration: true,
|
||||
allowUnauthenticatedClientRegistration: true,
|
||||
clientRegistrationDefaultApplicationType: 'infer',
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createGuestToken, verifyGuestToken } from './guest-token'
|
||||
|
||||
describe('guest-token', () => {
|
||||
it('creates and verifies a valid token for the expected shareId', () => {
|
||||
const token = createGuestToken({ userId: 'u1', shareId: 'share1' })
|
||||
const verified = verifyGuestToken(token, 'share1')
|
||||
expect(verified).not.toBeNull()
|
||||
expect(verified?.userId).toBe('u1')
|
||||
expect(verified?.shareId).toBe('share1')
|
||||
})
|
||||
|
||||
it('rejects a token when verified against a different shareId', () => {
|
||||
const token = createGuestToken({ userId: 'u1', shareId: 'share1' })
|
||||
const verified = verifyGuestToken(token, 'share2')
|
||||
expect(verified).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects an expired token', () => {
|
||||
const token = createGuestToken({ userId: 'u1', shareId: 'share1' }, -10)
|
||||
const verified = verifyGuestToken(token, 'share1')
|
||||
expect(verified).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a tampered signature', () => {
|
||||
const token = createGuestToken({ userId: 'u1', shareId: 'share1' })
|
||||
const [payload] = token.split('.')
|
||||
const tampered = `${payload}.invalidsignature`
|
||||
const verified = verifyGuestToken(tampered, 'share1')
|
||||
expect(verified).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects malformed token strings', () => {
|
||||
expect(verifyGuestToken('', 'share1')).toBeNull()
|
||||
expect(verifyGuestToken('singlepart', 'share1')).toBeNull()
|
||||
expect(verifyGuestToken('a.b.c', 'share1')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as crypto from 'crypto'
|
||||
|
||||
export interface GuestTokenPayload {
|
||||
userId: string
|
||||
shareId: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const GUEST_TOKEN_CONTEXT = 'shumai-guest-token:v1'
|
||||
const DEFAULT_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 days
|
||||
|
||||
function getSecret(): string {
|
||||
return process.env.BETTER_AUTH_SECRET || 'shumai-guest-secret'
|
||||
}
|
||||
|
||||
function signPayload(payloadB64: string): string {
|
||||
return crypto
|
||||
.createHmac('sha256', getSecret())
|
||||
.update(`${GUEST_TOKEN_CONTEXT}:${payloadB64}`)
|
||||
.digest('base64url')
|
||||
}
|
||||
|
||||
export function createGuestToken(
|
||||
params: { userId: string; shareId: string },
|
||||
ttlSeconds: number = DEFAULT_TTL_SECONDS,
|
||||
): string {
|
||||
const payload: GuestTokenPayload = {
|
||||
userId: params.userId,
|
||||
shareId: params.shareId,
|
||||
expiresAt: Date.now() + ttlSeconds * 1000,
|
||||
}
|
||||
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||
const signature = signPayload(payloadB64)
|
||||
return `${payloadB64}.${signature}`
|
||||
}
|
||||
|
||||
export function verifyGuestToken(token: string, expectedShareId: string): GuestTokenPayload | null {
|
||||
if (!token) return null
|
||||
const [payloadB64, signature, ...rest] = token.split('.')
|
||||
if (!payloadB64 || !signature || rest.length > 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(payloadB64)
|
||||
const actualBuf = Buffer.from(signature)
|
||||
const expectedBuf = Buffer.from(expectedSignature)
|
||||
|
||||
if (actualBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(actualBuf, expectedBuf)) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(payloadB64, 'base64url').toString('utf8'),
|
||||
) as GuestTokenPayload
|
||||
if (!payload.userId || !payload.shareId || typeof payload.expiresAt !== 'number') {
|
||||
return null
|
||||
}
|
||||
if (payload.shareId !== expectedShareId) {
|
||||
return null
|
||||
}
|
||||
if (Date.now() > payload.expiresAt) {
|
||||
return null
|
||||
}
|
||||
return payload
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export * from './agent/agent'
|
||||
export * from './asset/asset'
|
||||
export * from './asset/asset-archive'
|
||||
export * from './asset/auto-archive-job'
|
||||
export * from './auth/auth'
|
||||
export * from './authz/authz'
|
||||
export * from './collection/collection'
|
||||
|
||||
@@ -141,4 +141,33 @@ describe('Invite Service', () => {
|
||||
expect(updatedTm?.scope).toBe('team')
|
||||
expect(updatedTm?.role).toBe('editor')
|
||||
})
|
||||
|
||||
it('atomically claims invite and rejects concurrent redemptions', async () => {
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
teamId: team.id,
|
||||
role: 'editor',
|
||||
inviterId: admin.id,
|
||||
})
|
||||
|
||||
const userA = await prisma.user.create({
|
||||
data: { name: 'userA', email: 'userA-invite@example.com', password: 'pass' },
|
||||
})
|
||||
const userB = await prisma.user.create({
|
||||
data: { name: 'userB', email: 'userB-invite@example.com', password: 'pass' },
|
||||
})
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
inviteService.consumeInvite(inv.code, userA.id),
|
||||
inviteService.consumeInvite(inv.code, userB.id),
|
||||
])
|
||||
|
||||
const fulfilled = results.filter((r) => r.status === 'fulfilled')
|
||||
const rejected = results.filter((r) => r.status === 'rejected')
|
||||
|
||||
expect(fulfilled.length).toBe(1)
|
||||
expect(rejected.length).toBe(1)
|
||||
if (rejected[0].status === 'rejected') {
|
||||
expect(rejected[0].reason.message).toContain('invite code already used')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -84,7 +84,11 @@ export class InviteService {
|
||||
include: { team: true, project: true },
|
||||
})
|
||||
|
||||
if (inv.used) {
|
||||
const claimed = await tx.invite.updateMany({
|
||||
where: { id: inv.id, used: false },
|
||||
data: { used: true },
|
||||
})
|
||||
if (claimed.count !== 1) {
|
||||
throw new Error('invite code already used')
|
||||
}
|
||||
|
||||
@@ -155,11 +159,6 @@ export class InviteService {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.invite.update({
|
||||
where: { id: inv.id },
|
||||
data: { used: true },
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,4 +180,45 @@ describe('archive_assets and restore_archived_assets Operations', () => {
|
||||
await prisma.auditLog.count({ where: { action: AuditAction.asset_restore_archive } }),
|
||||
).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects symlinks directly with 400 and causes no side effects', async () => {
|
||||
const file = await assetService.createAsset({
|
||||
name: 'real.mov',
|
||||
type: 'file',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
key: 'files/01REAL/real.mov',
|
||||
sizeByte: 2048,
|
||||
contentType: 'video/quicktime',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: file.id },
|
||||
data: { status: AssetStatus.processed },
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'symlink.mov',
|
||||
type: 'symlink',
|
||||
parentId: rootFolderId,
|
||||
projectId,
|
||||
targetId: file.id,
|
||||
status: AssetStatus.processed,
|
||||
creatorId: owner.id,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
runOperation(archiveAssetsOp, as(owner), { assetIds: [symlink.id] }),
|
||||
).rejects.toMatchObject({ status: 400, message: 'Symlinks cannot be archived or restored' })
|
||||
|
||||
const unchangedFile = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
|
||||
expect(unchangedFile.status).toBe(AssetStatus.processed)
|
||||
expect(await prisma.auditLog.count({ where: { action: AuditAction.asset_archive } })).toBe(0)
|
||||
|
||||
await expect(
|
||||
runOperation(restoreArchivedAssetsOp, as(owner), { assetIds: [symlink.id] }),
|
||||
).rejects.toMatchObject({ status: 400, message: 'Symlinks cannot be archived or restored' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -541,5 +541,28 @@ describe('Archive Storage', () => {
|
||||
).toBe(true)
|
||||
expect(isColdStorageRestoreError(new Error('NetworkingError'))).toBe(false)
|
||||
})
|
||||
|
||||
it('headObject maps 404/NotFound to NoSuchKey, but rethrows 500 and other transient errors', async () => {
|
||||
const service = new S3ArchiveStorageService(baseS3Config)
|
||||
|
||||
s3SendSpy.mockRejectedValueOnce({ name: 'NotFound', $metadata: { httpStatusCode: 404 } })
|
||||
await expect(service.headObject('missing.mp4')).rejects.toThrow('NoSuchKey')
|
||||
|
||||
const internalErr = new Error('Internal S3 500')
|
||||
s3SendSpy.mockRejectedValueOnce(internalErr)
|
||||
await expect(service.headObject('error.mp4')).rejects.toThrow('Internal S3 500')
|
||||
})
|
||||
|
||||
it('deleteObject returns 0 on 404/NotFound, but rethrows non-404 errors', async () => {
|
||||
const service = new S3ArchiveStorageService(baseS3Config)
|
||||
|
||||
s3SendSpy.mockRejectedValueOnce({ name: 'NotFound', $metadata: { httpStatusCode: 404 } })
|
||||
const res404 = await service.deleteObject('missing.mp4')
|
||||
expect(res404).toBe(0)
|
||||
|
||||
const permErr = new Error('AccessDenied')
|
||||
s3SendSpy.mockRejectedValueOnce(permErr)
|
||||
await expect(service.deleteObject('forbidden.mp4')).rejects.toThrow('AccessDenied')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,9 +17,13 @@ import * as crypto from 'crypto'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Readable } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { ulid } from 'ulid'
|
||||
import { bodyToWebReadableStream, S3StreamObject, uploadStreamToS3Client } from './s3'
|
||||
import {
|
||||
bodyToWebReadableStream,
|
||||
isS3NotFoundError,
|
||||
S3StreamObject,
|
||||
uploadStreamToS3Client,
|
||||
writeStreamToLocalFile,
|
||||
} from './s3'
|
||||
|
||||
export type ArchiveStorageBackend = 'local' | 's3'
|
||||
export type ArchiveRestoreObjectMode = 'auto' | 'true' | 'false'
|
||||
@@ -299,6 +303,17 @@ export function validateArchiveStorageConfig(): ArchiveStorageConfig {
|
||||
return getArchiveStorageConfig()
|
||||
}
|
||||
|
||||
export function getArchiveStoragePath(
|
||||
key: string,
|
||||
): { path: string; backend: 's3' | 'local' } | null {
|
||||
const config = getArchiveStorageConfig()
|
||||
if (!config.enabled) return null
|
||||
if (config.backend === 's3') {
|
||||
return { path: `s3://${config.bucket}/${key}`, backend: 's3' }
|
||||
}
|
||||
return { path: path.join(config.localRoot, key), backend: 'local' }
|
||||
}
|
||||
|
||||
export class LocalArchiveStorageService implements ArchiveStorageService {
|
||||
readonly backend = 'local' as const
|
||||
readonly isSameS3Target = false
|
||||
@@ -333,21 +348,7 @@ export class LocalArchiveStorageService implements ArchiveStorageService {
|
||||
_contentType?: string,
|
||||
): Promise<void> {
|
||||
const filePath = this.getFilePath(key)
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
const tempPath = `${filePath}.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, filePath)
|
||||
} catch (err) {
|
||||
await fs.promises.unlink(tempPath).catch(() => {})
|
||||
throw err
|
||||
}
|
||||
await writeStreamToLocalFile(filePath, stream)
|
||||
}
|
||||
|
||||
async getObjectStream(key: string): Promise<S3StreamObject> {
|
||||
@@ -503,7 +504,10 @@ export class S3ArchiveStorageService implements ArchiveStorageService {
|
||||
restoreHeader: res.Restore,
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
throw new Error('NoSuchKey: The specified key does not exist.', { cause: err })
|
||||
if (isS3NotFoundError(err)) {
|
||||
throw new Error('NoSuchKey: The specified key does not exist.', { cause: err })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -511,8 +515,11 @@ export class S3ArchiveStorageService implements ArchiveStorageService {
|
||||
try {
|
||||
await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }))
|
||||
return 1
|
||||
} catch {
|
||||
return 0
|
||||
} catch (err: unknown) {
|
||||
if (isS3NotFoundError(err)) {
|
||||
return 0
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,13 @@ import {
|
||||
ListPartsCommand,
|
||||
AbortMultipartUploadCommand,
|
||||
} from '@aws-sdk/client-s3'
|
||||
import { buildContentDisposition, LocalStorageService, S3StorageService } from './s3'
|
||||
import {
|
||||
buildContentDisposition,
|
||||
LocalStorageService,
|
||||
S3StorageService,
|
||||
signLocalGetUrl,
|
||||
verifyLocalGetUrlSignature,
|
||||
} from './s3'
|
||||
|
||||
const s3ClientConstructorSpy = vi.fn()
|
||||
const s3SendSpy = vi.fn()
|
||||
@@ -710,19 +716,25 @@ describe('S3Service implementations', () => {
|
||||
|
||||
it('should generate a local presign URL', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET')
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
|
||||
expect(url).toContain('http://localhost:3000/files/my-bucket/dir/file.txt?')
|
||||
expect(url).toContain('Signature=')
|
||||
expect(url).toContain('Expires=')
|
||||
})
|
||||
|
||||
it('should generate a local presign URL with download param', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?download=1')
|
||||
expect(url).toContain('http://localhost:3000/files/my-bucket/dir/file.txt?')
|
||||
expect(url).toContain('Signature=')
|
||||
expect(url).toContain('Expires=')
|
||||
expect(url).toContain('download=1')
|
||||
})
|
||||
|
||||
it('should include an encoded filename in the local download URL', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true, 'foo bar.png')
|
||||
expect(url).toBe(
|
||||
'http://localhost:3000/files/my-bucket/dir/file.txt?download=1&filename=foo%20bar.png',
|
||||
)
|
||||
expect(url).toContain('http://localhost:3000/files/my-bucket/dir/file.txt?')
|
||||
expect(url).toContain('Signature=')
|
||||
expect(url).toContain('Expires=')
|
||||
expect(url).toContain('download=1&filename=foo%20bar.png')
|
||||
})
|
||||
|
||||
it('should not append a filename param when none is provided', async () => {
|
||||
@@ -730,6 +742,23 @@ describe('S3Service implementations', () => {
|
||||
expect(url).not.toContain('filename=')
|
||||
})
|
||||
|
||||
it('should cache GET presigned URLs using LRU cache', async () => {
|
||||
const url1 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET')
|
||||
const url2 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET')
|
||||
expect(url1).toBe(url2)
|
||||
|
||||
const urlOther = await localS3.presign('my-bucket', 'dir/other.txt', 'GET')
|
||||
expect(urlOther).not.toBe(url1)
|
||||
})
|
||||
|
||||
it('should not cache download URLs', async () => {
|
||||
const url1 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
|
||||
const url2 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
|
||||
// download URLs include download=1
|
||||
expect(url1).toContain('download=1')
|
||||
expect(url2).toContain('download=1')
|
||||
})
|
||||
|
||||
it('should throw an error for unsupported presign methods', async () => {
|
||||
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
|
||||
})
|
||||
@@ -742,7 +771,9 @@ describe('S3Service implementations', () => {
|
||||
|
||||
it('should resolveInput to presigned URL if file does not exist on disk', async () => {
|
||||
const input = await localS3.resolveInput('my-bucket', 'nonexistent.mp4')
|
||||
expect(input).toBe('http://localhost:3000/files/my-bucket/nonexistent.mp4')
|
||||
expect(input).toContain('http://localhost:3000/files/my-bucket/nonexistent.mp4?')
|
||||
expect(input).toContain('Signature=')
|
||||
expect(input).toContain('Expires=')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -832,4 +863,63 @@ describe('S3Service implementations', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('signLocalGetUrl and verifyLocalGetUrlSignature', () => {
|
||||
it('signs and verifies valid local get url', () => {
|
||||
const { signature, expires } = signLocalGetUrl('my-bucket', 'files/123/file.mp4')
|
||||
expect(signature).toBeDefined()
|
||||
expect(expires).toBeGreaterThan(Math.floor(Date.now() / 1000))
|
||||
|
||||
const isValid = verifyLocalGetUrlSignature(
|
||||
'my-bucket',
|
||||
'files/123/file.mp4',
|
||||
signature,
|
||||
String(expires),
|
||||
)
|
||||
expect(isValid).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects expired local get url signature', () => {
|
||||
// 10 seconds in the past
|
||||
const { signature, expires } = signLocalGetUrl('my-bucket', 'files/123/file.mp4', -10)
|
||||
const isValid = verifyLocalGetUrlSignature(
|
||||
'my-bucket',
|
||||
'files/123/file.mp4',
|
||||
signature,
|
||||
String(expires),
|
||||
)
|
||||
expect(isValid).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects tampered bucket or key', () => {
|
||||
const { signature, expires } = signLocalGetUrl('my-bucket', 'files/123/file.mp4')
|
||||
expect(
|
||||
verifyLocalGetUrlSignature(
|
||||
'other-bucket',
|
||||
'files/123/file.mp4',
|
||||
signature,
|
||||
String(expires),
|
||||
),
|
||||
).toBe(false)
|
||||
|
||||
expect(
|
||||
verifyLocalGetUrlSignature('my-bucket', 'files/999/other.mp4', signature, String(expires)),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects tampered or malformed signature or expires', () => {
|
||||
expect(
|
||||
verifyLocalGetUrlSignature('my-bucket', 'files/123/file.mp4', 'badsig', '1234567890'),
|
||||
).toBe(false)
|
||||
expect(
|
||||
verifyLocalGetUrlSignature('my-bucket', 'files/123/file.mp4', undefined, '1234567890'),
|
||||
).toBe(false)
|
||||
expect(
|
||||
verifyLocalGetUrlSignature('my-bucket', 'files/123/file.mp4', 'badsig', undefined),
|
||||
).toBe(false)
|
||||
expect(
|
||||
verifyLocalGetUrlSignature('my-bucket', 'files/123/file.mp4', 'badsig', 'not-a-number'),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+132
-22
@@ -46,6 +46,48 @@ export function verifyLocalUrlSignature(bucket: string, key: string, signature:
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Content-Disposition header value for downloads.
|
||||
* - Falls back to plain `attachment` when no filename is provided.
|
||||
@@ -123,6 +165,45 @@ export function bodyToWebReadableStream(body: unknown): ReadableStream<Uint8Arra
|
||||
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,
|
||||
@@ -133,6 +214,12 @@ export async function uploadStreamToS3Client(
|
||||
// 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(() => {})
|
||||
@@ -234,8 +321,8 @@ export async function uploadStreamToS3Client(
|
||||
if (value && value.byteLength > 0) {
|
||||
pendingChunks.push(value)
|
||||
pendingLength += value.byteLength
|
||||
while (pendingLength >= partSizeBytes) {
|
||||
await flushPart(partSizeBytes)
|
||||
while (pendingLength >= effectivePartSize) {
|
||||
await flushPart(effectivePartSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,7 +392,7 @@ export interface S3Service {
|
||||
download?: boolean,
|
||||
filename?: string,
|
||||
internal?: boolean,
|
||||
/** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h) for PUT, or PRESIGNED_URL_EXPIRES_IN (5h) for GET. Ignored by local storage. */
|
||||
/** 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. */
|
||||
expiresInSeconds?: number,
|
||||
) => Promise<string>
|
||||
presignMultipart: (
|
||||
@@ -315,6 +402,7 @@ export interface S3Service {
|
||||
) => Promise<{ url: string }>
|
||||
abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise<void>
|
||||
resolveInput: (bucket: string, key: string) => Promise<string>
|
||||
getStoragePath: (bucket: string, key: string) => string
|
||||
}
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
@@ -473,8 +561,11 @@ export class S3StorageService implements S3Service {
|
||||
try {
|
||||
await this.client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }))
|
||||
return 1
|
||||
} catch {
|
||||
return 0
|
||||
} catch (err: unknown) {
|
||||
if (isS3NotFoundError(err)) {
|
||||
return 0
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,7 +599,10 @@ export class S3StorageService implements S3Service {
|
||||
eTag: res.ETag || '',
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
throw new Error(`NoSuchKey: The specified key does not exist.`, { cause: err })
|
||||
if (isS3NotFoundError(err)) {
|
||||
throw new Error(`NoSuchKey: The specified key does not exist.`, { cause: err })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -709,11 +803,16 @@ export class S3StorageService implements S3Service {
|
||||
async resolveInput(bucket: string, key: string): Promise<string> {
|
||||
return this.presign(bucket, key, 'GET', false, undefined, true)
|
||||
}
|
||||
|
||||
getStoragePath(bucket: string, key: string): string {
|
||||
return `s3://${bucket}/${key}`
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalStorageService implements S3Service {
|
||||
private basePath: string
|
||||
private endpoint: string
|
||||
private presignCache = new LruTtlCache<string, string>(50000)
|
||||
|
||||
constructor(endpoint: string, basePath: string = 'data') {
|
||||
this.endpoint = endpoint.replace(/\/$/, '')
|
||||
@@ -809,20 +908,7 @@ export class LocalStorageService implements S3Service {
|
||||
|
||||
async uploadStream(params: UploadStreamParams): Promise<void> {
|
||||
const filePath = this.getFilePath(params.bucket, params.key)
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
const tempPath = `${filePath}.tmp-${ulid()}`
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const nodeStream = Readable.fromWeb(params.stream as any)
|
||||
await pipeline(nodeStream, fs.createWriteStream(tempPath))
|
||||
await fs.promises.rename(tempPath, filePath)
|
||||
} catch (err) {
|
||||
await fs.promises.unlink(tempPath).catch(() => {})
|
||||
throw err
|
||||
}
|
||||
await writeStreamToLocalFile(filePath, params.stream)
|
||||
}
|
||||
|
||||
async copyObject(
|
||||
@@ -967,6 +1053,8 @@ export class LocalStorageService implements S3Service {
|
||||
method: string,
|
||||
download?: boolean,
|
||||
filename?: string,
|
||||
_internal?: boolean,
|
||||
expiresInSeconds?: number,
|
||||
): Promise<string> {
|
||||
if (method !== 'GET' && method !== 'PUT') {
|
||||
throw new Error(`Invalid method: ${method}`)
|
||||
@@ -974,13 +1062,31 @@ export class LocalStorageService implements S3Service {
|
||||
if (method === 'PUT') {
|
||||
return `${this.endpoint}${signLocalUrl(bucket, key)}`
|
||||
}
|
||||
let url = `${this.endpoint}/files/${bucket}/${key}`
|
||||
|
||||
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}`
|
||||
if (download) {
|
||||
url += '?download=1'
|
||||
url += '&download=1'
|
||||
if (filename) {
|
||||
url += `&filename=${encodeURIComponent(filename)}`
|
||||
}
|
||||
}
|
||||
|
||||
if (method === 'GET' && !download) {
|
||||
this.presignCache.set(cacheKey, url, cacheTtlMs)
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
@@ -1011,6 +1117,10 @@ export class LocalStorageService implements S3Service {
|
||||
}
|
||||
return this.presign(bucket, key, 'GET')
|
||||
}
|
||||
|
||||
getStoragePath(bucket: string, key: string): string {
|
||||
return this.getFilePath(bucket, key)
|
||||
}
|
||||
}
|
||||
|
||||
export function getStorageBackend(): 's3' | 'local' {
|
||||
|
||||
@@ -106,5 +106,34 @@ describe('SqlQueryBuilder', () => {
|
||||
)
|
||||
expect(query.values).toEqual(['custom_field"test', 'hello'])
|
||||
})
|
||||
|
||||
it('isArchived eq true matches archived files and version stacks whose latest version is archived', () => {
|
||||
const builder = new SqlQueryBuilder()
|
||||
.from(Prisma.sql`assets a`)
|
||||
.addSearchConditions('AND', [{ field: 'isArchived', operator: 'eq', value: true }])
|
||||
|
||||
const query = builder.build()
|
||||
expect(query.text).toContain(
|
||||
`a."type" = 'file'::"AssetType" AND a."status" = 'archived'::"AssetStatus"`,
|
||||
)
|
||||
})
|
||||
|
||||
it('isArchived eq false matches non-archived files and version stacks', () => {
|
||||
const builder = new SqlQueryBuilder()
|
||||
.from(Prisma.sql`assets a`)
|
||||
.addSearchConditions('AND', [{ field: 'isArchived', operator: 'eq', value: false }])
|
||||
|
||||
const query = builder.build()
|
||||
expect(query.text).toContain(
|
||||
`a."type" = 'file'::"AssetType" AND a."status" != 'archived'::"AssetStatus"`,
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error for unsupported isArchived operators', () => {
|
||||
const builder = new SqlQueryBuilder().from(Prisma.sql`assets a`)
|
||||
expect(() =>
|
||||
builder.addSearchConditions('AND', [{ field: 'isArchived', operator: 'gt', value: true }]),
|
||||
).toThrow('Unsupported operator for isArchived field: gt')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -150,11 +150,11 @@ describe('ShareService', () => {
|
||||
expect(symlink).toBeDefined()
|
||||
|
||||
// Test password check
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id, 'wrong')).rejects.toThrow(
|
||||
'Invalid password',
|
||||
)
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(symlink!.id, 'secret-password'),
|
||||
shareService.verifyPublicAccess(shareLink.id, symlink!.id, 'wrong'),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, symlink!.id, 'secret-password'),
|
||||
).resolves.toBeDefined()
|
||||
|
||||
// Test expiration
|
||||
@@ -162,9 +162,9 @@ describe('ShareService', () => {
|
||||
where: { id: shareLink.id },
|
||||
data: { expireAt: new Date(Date.now() - 1000) },
|
||||
})
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id, 'secret-password')).rejects.toThrow(
|
||||
'expired',
|
||||
)
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareLink.id, symlink!.id, 'secret-password'),
|
||||
).rejects.toThrow('expired')
|
||||
})
|
||||
|
||||
it('traces deep ancestors for public access', async () => {
|
||||
@@ -192,7 +192,7 @@ describe('ShareService', () => {
|
||||
},
|
||||
})
|
||||
|
||||
await expect(shareService.verifyPublicAccess(deepFile.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, deepFile.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('verifies public access via symlink to a folder', async () => {
|
||||
@@ -220,10 +220,11 @@ describe('ShareService', () => {
|
||||
await shareService.addAssetToShare(shareLink.id, { assetIds: [realFolder.id] })
|
||||
|
||||
// 3. Verify access to the file inside the real folder (which is reached via the symlinked folder)
|
||||
await expect(shareService.verifyPublicAccess(realFile.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, realFile.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('fails public access for non-shared assets', async () => {
|
||||
const shareLink = await shareService.createShareLink(projectId, { name: 'Empty Share' })
|
||||
const privateFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'private.txt',
|
||||
@@ -232,7 +233,7 @@ describe('ShareService', () => {
|
||||
projectId,
|
||||
},
|
||||
})
|
||||
await expect(shareService.verifyPublicAccess(privateFile.id)).rejects.toThrow(
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, privateFile.id)).rejects.toThrow(
|
||||
'Asset is not shared',
|
||||
)
|
||||
})
|
||||
@@ -373,8 +374,8 @@ describe('ShareService', () => {
|
||||
where: { targetId: file.id, parentId: shareLink.rootFolderId },
|
||||
})
|
||||
expect(symlink).toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, symlink!.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the file (move to trash)
|
||||
await assetService.deleteAssets([file.id])
|
||||
@@ -393,8 +394,8 @@ describe('ShareService', () => {
|
||||
expect(afterDeleteShareRoot?.fileCount).toBe(0)
|
||||
|
||||
// Verify: public access is rejected
|
||||
await expect(shareService.verifyPublicAccess(file.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, file.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, symlink!.id)).rejects.toThrow()
|
||||
|
||||
// Verify: project's recently-deleted view does NOT list symlinks
|
||||
const recentlyDeleted = await assetService.listChildren({
|
||||
@@ -423,8 +424,8 @@ describe('ShareService', () => {
|
||||
expect(afterRestoreShareRoot?.fileCount).toBe(1)
|
||||
|
||||
// Verify: public access works again
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, symlink!.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('hides soft-deleted folders from share link and restores them upon folder restoration', async () => {
|
||||
@@ -463,7 +464,7 @@ describe('ShareService', () => {
|
||||
})
|
||||
expect(initialChildren.data).toHaveLength(1)
|
||||
expect(initialChildren.data[0].name).toBe('Shared Folder')
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, childFile.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the folder
|
||||
await assetService.deleteAssets([folder.id])
|
||||
@@ -476,7 +477,7 @@ describe('ShareService', () => {
|
||||
expect(afterDeleteChildren.data).toHaveLength(0)
|
||||
|
||||
// Verify: access to child file inside folder is rejected
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, childFile.id)).rejects.toThrow()
|
||||
|
||||
// 2. Restore the folder
|
||||
await assetService.restoreAssets([folder.id])
|
||||
@@ -490,6 +491,46 @@ describe('ShareService', () => {
|
||||
expect(afterRestoreChildren.data[0].name).toBe('Shared Folder')
|
||||
|
||||
// Verify: access to child file inside folder is restored
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(shareLink.id, childFile.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('binds public access strictly to the requested shareId', async () => {
|
||||
const fileA = await prisma.asset.create({
|
||||
data: { name: 'fileA.txt', type: AssetType.file, status: 'processed', projectId },
|
||||
})
|
||||
const fileB = await prisma.asset.create({
|
||||
data: { name: 'fileB.txt', type: AssetType.file, status: 'processed', projectId },
|
||||
})
|
||||
|
||||
const shareOpen = await shareService.createShareLink(projectId, { name: 'Open Share' })
|
||||
const shareProtected = await shareService.createShareLink(projectId, {
|
||||
name: 'Protected Share',
|
||||
password: 'password123',
|
||||
})
|
||||
|
||||
await shareService.addAssetToShare(shareOpen.id, { assetIds: [fileA.id, fileB.id] })
|
||||
await shareService.addAssetToShare(shareProtected.id, { assetIds: [fileA.id] })
|
||||
|
||||
// fileA in protected share requires password
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareProtected.id, fileA.id, 'wrong'),
|
||||
).rejects.toThrow('Invalid password')
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareProtected.id, fileA.id, 'password123'),
|
||||
).resolves.toBeDefined()
|
||||
|
||||
// fileB is only in shareOpen, accessing it via shareProtected must fail even with password
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareProtected.id, fileB.id, 'password123'),
|
||||
).rejects.toThrow('Asset is not shared')
|
||||
|
||||
// Disabled share must reject access even if file sits in another active share
|
||||
await prisma.shareLink.update({
|
||||
where: { id: shareProtected.id },
|
||||
data: { isDisabled: true },
|
||||
})
|
||||
await expect(
|
||||
shareService.verifyPublicAccess(shareProtected.id, fileA.id, 'password123'),
|
||||
).rejects.toThrow('disabled')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -249,57 +249,16 @@ export class ShareService {
|
||||
}
|
||||
|
||||
async verifyPublicAccess(
|
||||
shareLinkId: string,
|
||||
assetId: string,
|
||||
providedPassword?: string,
|
||||
): Promise<Prisma.ShareLinkGetPayload<true>> {
|
||||
// 1. Trace ancestors of the current asset in the real tree
|
||||
// 2. Find if any ancestor (including itself) is the target of a symlink that belongs to a share
|
||||
// 3. Or if the asset itself is a descendant of a 'share' type folder (direct share link root or subfolder within)
|
||||
|
||||
const rows = await prisma.$queryRaw<{ shareRootId: string }[]>`
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
),
|
||||
-- Find all symlinks pointing to any of these real ancestors
|
||||
found_symlinks AS (
|
||||
SELECT s.id, s.parent_id, s.type::text FROM assets s
|
||||
INNER JOIN real_ancestors ra ON s.target_id = ra.id
|
||||
WHERE s.type = 'symlink' AND s.is_deleted = false
|
||||
),
|
||||
-- Combine: start with either real ancestors that are 'share' type, or symlinks that lead to 'share' type
|
||||
search_starts AS (
|
||||
SELECT id, parent_id, type FROM real_ancestors WHERE type = 'share'
|
||||
UNION
|
||||
SELECT id, parent_id, type FROM found_symlinks
|
||||
),
|
||||
-- Trace UP from these search starts to find the ultimate 'share' root
|
||||
share_trace AS (
|
||||
SELECT id, parent_id, type FROM search_starts
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN share_trace st ON st.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
)
|
||||
SELECT id as "shareRootId" FROM share_trace WHERE type = 'share' LIMIT 1;
|
||||
`
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new ShareLinkNotFoundError('Asset is not shared')
|
||||
}
|
||||
|
||||
const shareRootId = rows[0].shareRootId
|
||||
const shareLink = await prisma.shareLink.findUnique({
|
||||
where: { rootFolderId: shareRootId },
|
||||
where: { id: shareLinkId },
|
||||
})
|
||||
|
||||
if (!shareLink) {
|
||||
throw new ShareLinkNotFoundError('Share link not found for this asset')
|
||||
throw new ShareLinkNotFoundError('Share link not found')
|
||||
}
|
||||
|
||||
if (shareLink.isDisabled) {
|
||||
@@ -314,6 +273,43 @@ export class ShareService {
|
||||
throw new ShareLinkPasswordInvalidError('Invalid password for share link')
|
||||
}
|
||||
|
||||
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text, a.target_id FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
),
|
||||
-- Find all symlinks pointing to any of these real ancestors
|
||||
found_symlinks AS (
|
||||
SELECT s.id, s.parent_id, s.type::text FROM assets s
|
||||
INNER JOIN real_ancestors ra ON s.target_id = ra.id
|
||||
WHERE s.type = 'symlink' AND s.is_deleted = false
|
||||
),
|
||||
-- Combine: start with either real ancestors, or symlinks that lead to them
|
||||
search_starts AS (
|
||||
SELECT id, parent_id, type FROM real_ancestors
|
||||
UNION
|
||||
SELECT id, parent_id, type FROM found_symlinks
|
||||
),
|
||||
-- Trace UP from these search starts to find the ultimate 'share' root
|
||||
share_trace AS (
|
||||
SELECT id, parent_id, type FROM search_starts
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN share_trace st ON st.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
)
|
||||
SELECT id FROM share_trace WHERE id = ${shareLink.rootFolderId} LIMIT 1;
|
||||
`
|
||||
|
||||
if (rows.length === 0) {
|
||||
throw new ShareLinkNotFoundError('Asset is not shared')
|
||||
}
|
||||
|
||||
return shareLink
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as path from 'path'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
@@ -388,6 +389,13 @@ describe('TeamService', () => {
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'theme', 'dark')
|
||||
@@ -417,6 +425,13 @@ describe('TeamService', () => {
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'multi')
|
||||
@@ -456,6 +471,13 @@ describe('TeamService', () => {
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
archiveStorage: { enabled: false },
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -633,4 +655,66 @@ describe('TeamService', () => {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects enabling auto-archive when archive storage is not configured', async () => {
|
||||
delete process.env.ARCHIVE_STORAGE_BACKEND
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner AA', email: 'owner-aa@example.com', password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'AA Team' })
|
||||
|
||||
await expect(
|
||||
teamService.updateSettings(team.id, 'autoArchive', {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
}),
|
||||
).rejects.toThrow('Cannot enable auto archive when archive storage is not configured')
|
||||
|
||||
await expect(teamService.updateSettings(team.id, 'autoArchive.enabled', true)).rejects.toThrow(
|
||||
'Cannot enable auto archive when archive storage is not configured',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows updating auto-archive settings when archive storage is configured', async () => {
|
||||
const saved = { ...process.env }
|
||||
process.env.ARCHIVE_STORAGE_BACKEND = 'local'
|
||||
process.env.ARCHIVE_LOCAL_ROOT = '/tmp/shumai-archive-test-team'
|
||||
|
||||
try {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner AA 2', email: 'owner-aa2@example.com', password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'AA Team 2' })
|
||||
|
||||
await teamService.updateSettings(team.id, 'autoArchive', {
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 45,
|
||||
postRestoreGraceDays: 15,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
expect(settings.autoArchive).toEqual({
|
||||
enabled: true,
|
||||
method: 'after_created',
|
||||
days: 45,
|
||||
postRestoreGraceDays: 15,
|
||||
})
|
||||
expect(settings.archiveStorage).toEqual({
|
||||
enabled: true,
|
||||
backend: 'local',
|
||||
localRoot: path.resolve('/tmp/shumai-archive-test-team'),
|
||||
})
|
||||
|
||||
// Non-admin call should mask backend/root details
|
||||
const readerSettings = await teamService.getSettings(team.id, { isAdmin: false })
|
||||
expect(readerSettings.archiveStorage).toEqual({
|
||||
enabled: true,
|
||||
})
|
||||
} finally {
|
||||
process.env = saved
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,6 +10,10 @@ import { AgentService, agentService } from '@shumai/core/src/agent/agent'
|
||||
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import {
|
||||
getArchiveStorageConfig,
|
||||
isArchiveStorageEnabled,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -23,6 +27,9 @@ import {
|
||||
SandboxSettings,
|
||||
UpdateSandboxSettingsRequest,
|
||||
TeamSettingsResponse,
|
||||
AutoArchiveMethod,
|
||||
AutoArchiveSettings,
|
||||
DEFAULT_AUTO_ARCHIVE_SETTINGS,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
export class TeamService {
|
||||
@@ -300,7 +307,10 @@ export class TeamService {
|
||||
})
|
||||
}
|
||||
|
||||
async getSettings(teamId: string): Promise<TeamSettingsResponse> {
|
||||
async getSettings(
|
||||
teamId: string,
|
||||
options?: { isAdmin?: boolean },
|
||||
): Promise<TeamSettingsResponse> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
@@ -355,6 +365,33 @@ export class TeamService {
|
||||
settings.turntable = await turntableService.getSettings(teamId)
|
||||
settings.gotenberg = await gotenbergService.getSettings(teamId)
|
||||
|
||||
const archiveConfig = getArchiveStorageConfig()
|
||||
if (!archiveConfig.enabled) {
|
||||
settings.archiveStorage = { enabled: false }
|
||||
} else if (options?.isAdmin === false) {
|
||||
settings.archiveStorage = { enabled: true }
|
||||
} else if (archiveConfig.backend === 'local') {
|
||||
settings.archiveStorage = {
|
||||
enabled: true,
|
||||
backend: 'local',
|
||||
localRoot: archiveConfig.localRoot,
|
||||
}
|
||||
} else {
|
||||
settings.archiveStorage = {
|
||||
enabled: true,
|
||||
backend: 's3',
|
||||
endpoint: archiveConfig.endpoint,
|
||||
bucket: archiveConfig.bucket,
|
||||
}
|
||||
}
|
||||
|
||||
settings.autoArchive = {
|
||||
enabled: settings.autoArchive?.enabled ?? false,
|
||||
method: settings.autoArchive?.method ?? 'not_updated',
|
||||
days: settings.autoArchive?.days ?? 30,
|
||||
postRestoreGraceDays: settings.autoArchive?.postRestoreGraceDays ?? 30,
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -421,6 +458,49 @@ export class TeamService {
|
||||
}
|
||||
settings.appearance.hideAgent = Boolean(value)
|
||||
delete settings['appearance.hideAgent']
|
||||
} else if (key === 'autoArchive') {
|
||||
const autoArchiveVal = value as AutoArchiveSettings
|
||||
if (autoArchiveVal.enabled && !isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Cannot enable auto archive when archive storage is not configured',
|
||||
})
|
||||
}
|
||||
settings.autoArchive = {
|
||||
enabled: Boolean(autoArchiveVal.enabled),
|
||||
method: autoArchiveVal.method || 'not_updated',
|
||||
days: Number(autoArchiveVal.days) || 30,
|
||||
postRestoreGraceDays: Number(autoArchiveVal.postRestoreGraceDays) || 30,
|
||||
}
|
||||
} else if (key === 'autoArchive.enabled') {
|
||||
const enabled = Boolean(value)
|
||||
if (enabled && !isArchiveStorageEnabled()) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Cannot enable auto archive when archive storage is not configured',
|
||||
})
|
||||
}
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.enabled = enabled
|
||||
delete settings['autoArchive.enabled']
|
||||
} else if (key === 'autoArchive.method') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.method = value as AutoArchiveMethod
|
||||
delete settings['autoArchive.method']
|
||||
} else if (key === 'autoArchive.days') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.days = Number(value)
|
||||
delete settings['autoArchive.days']
|
||||
} else if (key === 'autoArchive.postRestoreGraceDays') {
|
||||
if (!settings.autoArchive) {
|
||||
settings.autoArchive = { ...DEFAULT_AUTO_ARCHIVE_SETTINGS }
|
||||
}
|
||||
settings.autoArchive.postRestoreGraceDays = Number(value)
|
||||
delete settings['autoArchive.postRestoreGraceDays']
|
||||
} else {
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
@@ -170,6 +170,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -228,6 +229,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -268,6 +270,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -303,6 +306,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -336,6 +340,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -366,6 +371,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -399,6 +405,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -429,6 +436,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -484,6 +492,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -512,6 +521,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: htmlTask.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -547,6 +557,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -584,6 +595,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -616,6 +628,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -649,6 +662,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -752,6 +766,7 @@ describe('UploadService', () => {
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
@@ -1120,6 +1135,68 @@ describe('UploadService', () => {
|
||||
})
|
||||
expect(deletedAsset).toBeNull()
|
||||
})
|
||||
|
||||
it('should not increment task count if error arrives for an already finished or deleted asset', async () => {
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: userId,
|
||||
type: 'upload',
|
||||
name: 'task-late-err',
|
||||
total: 2,
|
||||
uploaded: 1,
|
||||
status: TaskStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/test/already-uploaded.mp4' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'already-uploaded.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
storageKeyId: storageKey.id,
|
||||
taskId: task.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(userId, task.id, {
|
||||
fileId: asset.id,
|
||||
errorMessage: 'Late network error',
|
||||
})
|
||||
|
||||
const taskAfter = await prisma.task.findUniqueOrThrow({ where: { id: task.id } })
|
||||
expect(taskAfter.uploaded).toBe(1)
|
||||
})
|
||||
|
||||
it('should reject confirmation if asset does not belong to specified task', async () => {
|
||||
const task1 = await prisma.task.create({
|
||||
data: { creatorId: userId, type: 'upload', total: 1, status: TaskStatus.uploading },
|
||||
})
|
||||
const task2 = await prisma.task.create({
|
||||
data: { creatorId: userId, type: 'upload', total: 1, status: TaskStatus.uploading },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/test/task-mismatch.mp4' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'task-mismatch.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
storageKeyId: storageKey.id,
|
||||
taskId: task1.id,
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
uploadService.confirmFileUpload(userId, task2.id, { fileId: asset.id }),
|
||||
).rejects.toThrow('Asset does not belong to specified task')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cancelUploadTask', () => {
|
||||
|
||||
@@ -206,23 +206,28 @@ export class UploadService {
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.taskId !== taskId) {
|
||||
throw new Error('Asset does not belong to specified task')
|
||||
}
|
||||
if (!asset.project) throw new Error('Project not found for asset')
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) throw new Error('Asset has no key')
|
||||
|
||||
if (req.errorMessage) {
|
||||
await this.discardUploadingAsset(asset)
|
||||
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
|
||||
if (t) {
|
||||
const updatedTask = await this.prismaClient.task.update({
|
||||
where: { id: taskId },
|
||||
data: { uploaded: { increment: 1 } },
|
||||
})
|
||||
if (updatedTask.uploaded === updatedTask.total) {
|
||||
await this.prismaClient.task.update({
|
||||
const discarded = await this.discardUploadingAsset(asset)
|
||||
if (discarded) {
|
||||
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
|
||||
if (t) {
|
||||
const updatedTask = await this.prismaClient.task.update({
|
||||
where: { id: taskId },
|
||||
data: { status: TaskStatus.completed },
|
||||
data: { uploaded: { increment: 1 } },
|
||||
})
|
||||
if (updatedTask.uploaded === updatedTask.total) {
|
||||
await this.prismaClient.task.update({
|
||||
where: { id: taskId },
|
||||
data: { status: TaskStatus.completed },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
@@ -242,15 +247,22 @@ export class UploadService {
|
||||
resolvedMediaType = Bun.file(asset.name).type || 'application/octet-stream'
|
||||
}
|
||||
|
||||
// Update asset
|
||||
const updatedAsset = await tx.asset.update({
|
||||
where: { id: asset.id },
|
||||
// Claim status transition atomically
|
||||
const claim = await tx.asset.updateMany({
|
||||
where: {
|
||||
id: asset.id,
|
||||
taskId: taskId,
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
data: {
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: size,
|
||||
mediaType: resolvedMediaType,
|
||||
},
|
||||
})
|
||||
if (claim.count !== 1) {
|
||||
throw new Error('Asset is not in uploading status')
|
||||
}
|
||||
|
||||
// Update parent and ancestors
|
||||
if (asset.parentId) {
|
||||
@@ -259,7 +271,7 @@ export class UploadService {
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
|
||||
await assetService.updateAncestorsSize(tx, asset.parentId, updatedAsset.sizeByte)
|
||||
await assetService.updateAncestorsSize(tx, asset.parentId, size)
|
||||
}
|
||||
|
||||
// Update task
|
||||
@@ -533,7 +545,7 @@ export class UploadService {
|
||||
storageKey: { key: string } | null
|
||||
},
|
||||
requestedUploadId?: string,
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
const deleteResult = await this.prismaClient.asset.deleteMany({
|
||||
where: {
|
||||
id: asset.id,
|
||||
@@ -542,7 +554,7 @@ export class UploadService {
|
||||
})
|
||||
|
||||
if (deleteResult.count === 0) {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -568,6 +580,8 @@ export class UploadService {
|
||||
.delete({ where: { id: asset.storageKeyId } })
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async cancelUploadTask(
|
||||
|
||||
@@ -547,4 +547,41 @@ describe('WorkflowTaskService', () => {
|
||||
expect(stopRes.task.fileSize).toBe(5242880)
|
||||
expect(stopRes.task.projectName).toBe('Enrich Project')
|
||||
})
|
||||
|
||||
it('reverts archiving and restoring asset status back to baseline on stopWorkflowTask', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Stop Task Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Stop Project', teamId: team.id },
|
||||
})
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key: 'keys/stop-test.mp4', isArchived: false },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stop-test.mp4',
|
||||
type: 'file',
|
||||
status: AssetStatus.archiving,
|
||||
storageKeyId: sk.id,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
type: WorkflowTaskType.archive_asset,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
payload: { projectId: project.id, archive: { storageKeyId: sk.id } },
|
||||
},
|
||||
})
|
||||
|
||||
await workflowTaskService.stopWorkflowTask({ teamId: team.id, taskId: task.id })
|
||||
|
||||
const updatedAsset = await prisma.asset.findUniqueOrThrow({ where: { id: asset.id } })
|
||||
expect(updatedAsset.status).toBe(AssetStatus.processed)
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: task.id } })
|
||||
expect(updatedTask.status).toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import type { WorkflowTaskItem, ListWorkflowTasksResponse } from '@shumai/dtos'
|
||||
import { paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { revertArchiveStateForStorageKey } from '@shumai/core/src/asset/asset-archive'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
export interface ListWorkflowTasksParams {
|
||||
@@ -311,20 +312,7 @@ export class WorkflowTaskService {
|
||||
storageKeyId = targetAsset?.storageKeyId ?? undefined
|
||||
}
|
||||
if (storageKeyId) {
|
||||
const sk = await tx.storageKey.findUnique({
|
||||
where: { id: storageKeyId },
|
||||
select: { isArchived: true },
|
||||
})
|
||||
const fallbackStatus = sk?.isArchived ? 'archived' : 'processed'
|
||||
await tx.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
isDeleted: false,
|
||||
type: 'file',
|
||||
status: { in: ['archiving', 'restoring'] },
|
||||
},
|
||||
data: { status: fallbackStatus },
|
||||
})
|
||||
await revertArchiveStateForStorageKey(storageKeyId, tx)
|
||||
}
|
||||
} else {
|
||||
await tx.$executeRaw`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -122,6 +122,7 @@ declare global {
|
||||
mediaGeneration?: MediaGenerationSettings
|
||||
appearance?: AppearanceSettings
|
||||
emailNotification?: EmailNotificationSettings
|
||||
autoArchive?: import('@shumai/dtos').AutoArchiveSettings
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -400,6 +400,25 @@ export const getDownloadLinksResponseSchema = z.object({
|
||||
})
|
||||
export type GetDownloadLinksResponse = z.infer<typeof getDownloadLinksResponseSchema>
|
||||
|
||||
export const getStoragePathsRequestSchema = z.object({
|
||||
ids: z.array(z.string()).max(100),
|
||||
})
|
||||
export type GetStoragePathsRequest = z.infer<typeof getStoragePathsRequestSchema>
|
||||
|
||||
export const storagePathItemSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
backend: z.enum(['s3', 'local']),
|
||||
isArchived: z.boolean(),
|
||||
})
|
||||
export type StoragePathItem = z.infer<typeof storagePathItemSchema>
|
||||
|
||||
export const getStoragePathsResponseSchema = z.object({
|
||||
paths: z.array(storagePathItemSchema),
|
||||
})
|
||||
export type GetStoragePathsResponse = z.infer<typeof getStoragePathsResponseSchema>
|
||||
|
||||
export const archiveAssetsRequestSchema = z.object({
|
||||
ids: z.array(z.string().min(1)).min(1),
|
||||
})
|
||||
|
||||
@@ -110,6 +110,32 @@ export type HlsResolutionLadder = (typeof HlsResolutionLadder)[keyof typeof HlsR
|
||||
|
||||
export const DEFAULT_HLS_RESOLUTIONS: HlsResolutionLadder[] = ['480p', '720p', '1080p']
|
||||
|
||||
export const autoArchiveMethodSchema = z.enum(['not_updated', 'after_created'])
|
||||
export type AutoArchiveMethod = z.infer<typeof autoArchiveMethodSchema>
|
||||
|
||||
export const autoArchiveSettingsSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
method: autoArchiveMethodSchema,
|
||||
days: z.number().int().min(1).max(3650),
|
||||
postRestoreGraceDays: z.number().int().min(1).max(3650).default(30),
|
||||
})
|
||||
export type AutoArchiveSettings = z.infer<typeof autoArchiveSettingsSchema>
|
||||
|
||||
export const DEFAULT_AUTO_ARCHIVE_SETTINGS: AutoArchiveSettings = {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
}
|
||||
|
||||
export interface ArchiveStorageInfo {
|
||||
enabled: boolean
|
||||
backend?: 'local' | 's3'
|
||||
endpoint?: string
|
||||
bucket?: string
|
||||
localRoot?: string
|
||||
}
|
||||
|
||||
export const updateTeamSettingsRequestSchema = z.union([
|
||||
z.object({
|
||||
key: z.literal('transcode.videoStrategy'),
|
||||
@@ -139,6 +165,26 @@ export const updateTeamSettingsRequestSchema = z.union([
|
||||
key: z.literal('appearance.hideAgent'),
|
||||
value: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('autoArchive'),
|
||||
value: autoArchiveSettingsSchema,
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('autoArchive.enabled'),
|
||||
value: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('autoArchive.method'),
|
||||
value: autoArchiveMethodSchema,
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('autoArchive.days'),
|
||||
value: z.number().int().min(1).max(3650),
|
||||
}),
|
||||
z.object({
|
||||
key: z.literal('autoArchive.postRestoreGraceDays'),
|
||||
value: z.number().int().min(1).max(3650),
|
||||
}),
|
||||
])
|
||||
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
|
||||
|
||||
@@ -189,6 +235,8 @@ export interface TeamSettingsResponse {
|
||||
gotenberg?: GotenbergSettingsResponse
|
||||
appearance?: TeamAppearanceSettings
|
||||
semanticSearchEnabled?: boolean
|
||||
archiveStorage?: ArchiveStorageInfo
|
||||
autoArchive?: AutoArchiveSettings
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/operations",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.6.3",
|
||||
"version": "0.6.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { Readable } from 'node:stream'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AssetStatus, prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import { archiveAssetWorkflow } from '../workflows/archive-asset'
|
||||
import { restoreAssetWorkflow } from '../workflows/restore-asset'
|
||||
import { copyOriginalToArchiveStorageActivity } from './archive'
|
||||
|
||||
describe('Archive & Restore Workflows and Activities', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -198,4 +200,59 @@ describe('Archive & Restore Workflows and Activities', () => {
|
||||
const updatedTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: task.id } })
|
||||
expect(updatedTask.status).toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
|
||||
it('freshly overwrites destination even if a file of matching size already exists in archive storage', async () => {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = 'files/wf-test/overwrite-test.mp4'
|
||||
const originalContent = 'fresh-content-12345'
|
||||
const staleContent = 'stale-content-99999'
|
||||
expect(originalContent.length).toBe(staleContent.length)
|
||||
|
||||
// Put stale content into archive storage directly
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
await archiveStorage.uploadStream(
|
||||
key,
|
||||
Readable.toWeb(
|
||||
Readable.from(Buffer.from(staleContent)),
|
||||
) as unknown as ReadableStream<Uint8Array>,
|
||||
staleContent.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
// Put fresh content into main storage
|
||||
await s3Service.uploadStream({
|
||||
bucket,
|
||||
key,
|
||||
stream: Readable.toWeb(
|
||||
Readable.from(Buffer.from(originalContent)),
|
||||
) as unknown as ReadableStream<Uint8Array>,
|
||||
contentLength: originalContent.length,
|
||||
contentType: 'video/mp4',
|
||||
})
|
||||
|
||||
const sk = await prisma.storageKey.create({
|
||||
data: { key, isArchived: false },
|
||||
})
|
||||
|
||||
await copyOriginalToArchiveStorageActivity({
|
||||
storageKeyId: sk.id,
|
||||
key,
|
||||
expectedSize: originalContent.length,
|
||||
contentType: 'video/mp4',
|
||||
})
|
||||
|
||||
const { stream } = await archiveStorage.getObjectStream(key)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const readStream = Readable.fromWeb(stream as any)
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of readStream) {
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
const finalArchivedContent = Buffer.concat(chunks).toString('utf-8')
|
||||
expect(finalArchivedContent).toBe(originalContent)
|
||||
|
||||
// Clean up
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
await archiveStorage.deleteObject(key)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { AssetStatus, prisma, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { revertArchiveStateForStorageKey } from '@shumai/core/src/asset/asset-archive'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
getArchiveStorageService,
|
||||
@@ -258,17 +259,7 @@ export const copyOriginalToArchiveStorageActivity = defineStep(
|
||||
return { copiedSize: verifyHead.size ?? objectSize }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage: check if already uploaded in a prior attempt
|
||||
const existingArchiveHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (
|
||||
existingArchiveHead.exists &&
|
||||
existingArchiveHead.size !== undefined &&
|
||||
((params.expectedSize > 0 && existingArchiveHead.size === params.expectedSize) ||
|
||||
(params.expectedSize === 0 && existingArchiveHead.size > 0))
|
||||
) {
|
||||
return { copiedSize: existingArchiveHead.size }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage:
|
||||
const mainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (!mainHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -327,7 +318,7 @@ export const commitArchiveDbStateActivity = defineStep(
|
||||
storageKeyId: params.storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
status: AssetStatus.archiving,
|
||||
},
|
||||
data: { status: AssetStatus.archived },
|
||||
}),
|
||||
@@ -338,7 +329,7 @@ export const commitArchiveDbStateActivity = defineStep(
|
||||
export const deleteMainOriginalAfterArchiveActivity = defineStep(
|
||||
async function deleteMainOriginalAfterArchiveActivity(params: { key: string }): Promise<void> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (archiveStorage?.isSameS3Target) {
|
||||
if (archiveStorage.isSameS3Target) {
|
||||
return
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -425,17 +416,7 @@ export const copyOriginalFromArchiveToMainActivity = defineStep(
|
||||
return { status: 'copied', copiedSize: verifyHead.size ?? objectSize }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage: check if already restored to main storage
|
||||
const existingMainHead = await tryHeadMainObject(bucket, params.key)
|
||||
if (
|
||||
existingMainHead.exists &&
|
||||
existingMainHead.size !== undefined &&
|
||||
((params.expectedSize > 0 && existingMainHead.size === params.expectedSize) ||
|
||||
(params.expectedSize === 0 && existingMainHead.size > 0))
|
||||
) {
|
||||
return { status: 'copied', copiedSize: existingMainHead.size }
|
||||
}
|
||||
|
||||
// Separate bucket or local archive storage:
|
||||
const archiveHead = await tryHeadArchiveObject(archiveStorage, params.key)
|
||||
if (!archiveHead.exists) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -506,9 +487,9 @@ export const commitRestoreDbStateActivity = defineStep(
|
||||
storageKeyId: params.storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { notIn: [AssetStatus.trashed, AssetStatus.pending_purge] },
|
||||
status: AssetStatus.restoring,
|
||||
},
|
||||
data: { status: AssetStatus.processed },
|
||||
data: { status: AssetStatus.processed, updatedAt: new Date() },
|
||||
}),
|
||||
])
|
||||
},
|
||||
@@ -517,7 +498,7 @@ export const commitRestoreDbStateActivity = defineStep(
|
||||
export const deleteArchiveOriginalAfterRestoreActivity = defineStep(
|
||||
async function deleteArchiveOriginalAfterRestoreActivity(params: { key: string }): Promise<void> {
|
||||
const archiveStorage = getArchiveStorageService()
|
||||
if (!archiveStorage || archiveStorage.isSameS3Target) {
|
||||
if (archiveStorage.isSameS3Target) {
|
||||
return
|
||||
}
|
||||
await archiveStorage.deleteObject(params.key)
|
||||
@@ -541,23 +522,7 @@ export const revertArchiveOrRestoreStatusOnFailureActivity = defineStep(
|
||||
}
|
||||
|
||||
if (storageKeyId) {
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { id: storageKeyId },
|
||||
select: { isArchived: true },
|
||||
})
|
||||
if (sk) {
|
||||
await prisma.asset.updateMany({
|
||||
where: {
|
||||
storageKeyId,
|
||||
deletedAt: null,
|
||||
type: 'file',
|
||||
status: { in: [AssetStatus.archiving, AssetStatus.restoring] },
|
||||
},
|
||||
data: {
|
||||
status: sk.isArchived ? AssetStatus.archived : AssetStatus.processed,
|
||||
},
|
||||
})
|
||||
}
|
||||
await revertArchiveStateForStorageKey(storageKeyId)
|
||||
}
|
||||
|
||||
await prisma.workflowTask.update({
|
||||
|
||||
@@ -80,4 +80,19 @@ describe('FileBrowserContextMenu', () => {
|
||||
|
||||
expect(screen.queryByText(/Manage versions|管理版本/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('renders Copy submenu trigger for regular file item with aligned gap-2 and w-52 menu width', () => {
|
||||
renderWithMenu(fileItem)
|
||||
|
||||
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
|
||||
|
||||
const copyOption = screen.getByText(/^Copy$|^复制$/i)
|
||||
expect(copyOption).toBeTruthy()
|
||||
|
||||
const trigger = copyOption.closest('[data-slot="context-menu-sub-trigger"]')
|
||||
expect(trigger?.className).toContain('gap-2')
|
||||
|
||||
const menuContent = copyOption.closest('[data-slot="context-menu-content"]')
|
||||
expect(menuContent?.className).toContain('w-52')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
Copy,
|
||||
Layers,
|
||||
} from 'lucide-react'
|
||||
import { CopyContextMenuSub } from './copy-submenu'
|
||||
import type { CopyKind } from './copy-options'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
item: AssetInfo | null
|
||||
@@ -33,11 +35,13 @@ interface FileBrowserContextMenuProps {
|
||||
onRename: (item: AssetInfo) => void
|
||||
onDelete: (items: AssetInfo[]) => void
|
||||
onDownload: (items: AssetInfo[]) => void
|
||||
onCopyNameAndDownloadLink?: (items: AssetInfo[]) => void
|
||||
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
onRestore: (items: AssetInfo[]) => void
|
||||
onArchive?: (items: AssetInfo[]) => void
|
||||
onRestoreArchive?: (items: AssetInfo[]) => void
|
||||
archiveStorageEnabled?: boolean
|
||||
isTeamOwner?: boolean
|
||||
allowDownload?: boolean
|
||||
onNewFolder: (name: string) => void
|
||||
onUploadFile: () => void
|
||||
onUploadFolder: () => void
|
||||
@@ -64,11 +68,13 @@ export function FileBrowserContextMenu({
|
||||
onRename,
|
||||
onDelete,
|
||||
onDownload,
|
||||
onCopyNameAndDownloadLink,
|
||||
onCopy,
|
||||
onRestore,
|
||||
onArchive,
|
||||
onRestoreArchive,
|
||||
archiveStorageEnabled = false,
|
||||
isTeamOwner = false,
|
||||
allowDownload = true,
|
||||
onNewFolder,
|
||||
onUploadFile,
|
||||
onUploadFolder,
|
||||
@@ -113,14 +119,6 @@ export function FileBrowserContextMenu({
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyNameAndDownloadLink = () => {
|
||||
if (isItemSelected) {
|
||||
onCopyNameAndDownloadLink?.(selectedItems)
|
||||
} else if (item) {
|
||||
onCopyNameAndDownloadLink?.([item])
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = () => {
|
||||
onRestore(itemsToRestore)
|
||||
}
|
||||
@@ -162,15 +160,11 @@ export function FileBrowserContextMenu({
|
||||
if (isShareView) {
|
||||
if (!item) return null
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuContent className="w-52">
|
||||
<ContextMenuItem onSelect={handleDownload}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>{m.copy_name_and_download_link()}</span>
|
||||
</ContextMenuItem>
|
||||
{canEdit && (
|
||||
<ContextMenuItem
|
||||
onSelect={() => onRemoveFromShare?.(itemsToModify)}
|
||||
@@ -189,7 +183,7 @@ export function FileBrowserContextMenu({
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuContent className="w-52">
|
||||
<ContextMenuItem onSelect={handleRestore}>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
<span>{m.restore()}</span>
|
||||
@@ -203,6 +197,7 @@ export function FileBrowserContextMenu({
|
||||
// Right-click on empty area
|
||||
return (
|
||||
<ContextMenuContent
|
||||
className="w-52"
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
@@ -230,6 +225,7 @@ export function FileBrowserContextMenu({
|
||||
const contextMenuContent =
|
||||
isItemSelected && selectedIds.size > 1 ? (
|
||||
<ContextMenuContent
|
||||
className="w-52"
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
@@ -238,10 +234,14 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>{m.copy_name_and_download_link()}</span>
|
||||
</ContextMenuItem>
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
isTeamOwner,
|
||||
allowDownload,
|
||||
}}
|
||||
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
|
||||
/>
|
||||
{canEdit && (
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
@@ -294,7 +294,7 @@ export function FileBrowserContextMenu({
|
||||
<span>{m.add_to_share_links()}</span>
|
||||
</ContextMenuSubTrigger>
|
||||
<ContextMenuPortal>
|
||||
<ContextMenuSubContent className="w-48">
|
||||
<ContextMenuSubContent className="w-52">
|
||||
{shareLinks.map((share) => (
|
||||
<ContextMenuItem
|
||||
key={share.id}
|
||||
@@ -312,6 +312,7 @@ export function FileBrowserContextMenu({
|
||||
</ContextMenuContent>
|
||||
) : (
|
||||
<ContextMenuContent
|
||||
className="w-52"
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
@@ -330,10 +331,14 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>{m.copy_name_and_download_link()}</span>
|
||||
</ContextMenuItem>
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
isTeamOwner,
|
||||
allowDownload,
|
||||
}}
|
||||
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
|
||||
/>
|
||||
|
||||
{canEdit && (
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
@@ -409,7 +414,7 @@ export function FileBrowserContextMenu({
|
||||
<span>{m.add_to_share_links()}</span>
|
||||
</ContextMenuSubTrigger>
|
||||
<ContextMenuPortal>
|
||||
<ContextMenuSubContent className="w-48">
|
||||
<ContextMenuSubContent className="w-52">
|
||||
{shareLinks.map((share) => (
|
||||
<ContextMenuItem
|
||||
key={share.id}
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import {
|
||||
isImageItem,
|
||||
pickClipboardTranscode,
|
||||
getCopyOptions,
|
||||
formatCopyText,
|
||||
getItemInAppUrl,
|
||||
} from './copy-options'
|
||||
|
||||
describe('copy-options', () => {
|
||||
const dummyFile: AssetInfo = {
|
||||
id: 'file-1',
|
||||
name: 'document.pdf',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 1024 * 1024,
|
||||
fileCount: 0,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
}
|
||||
|
||||
const dummyImage: AssetInfo = {
|
||||
id: 'image-1',
|
||||
name: 'photo.jpg',
|
||||
type: 'file',
|
||||
proxyType: 'image',
|
||||
status: 'processed',
|
||||
sizeByte: 2 * 1024 * 1024,
|
||||
fileCount: 0,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
media: {
|
||||
imageTranscodes: [
|
||||
{ id: 't1', key: 'k1', url: 'https://cdn/1080.webp', width: 1920, height: 1080, size: 200 },
|
||||
{ id: 't2', key: 'k2', url: 'https://cdn/3000.webp', width: 3000, height: 2000, size: 500 },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
const dummyFolder: AssetInfo = {
|
||||
id: 'folder-1',
|
||||
name: 'Assets',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
sizeByte: 0,
|
||||
fileCount: 5,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
}
|
||||
|
||||
const dummyVersionStack: AssetInfo = {
|
||||
id: 'stack-1',
|
||||
name: 'render.png',
|
||||
type: 'version_stack',
|
||||
proxyType: 'image',
|
||||
status: 'processed',
|
||||
sizeByte: 5 * 1024 * 1024,
|
||||
fileCount: 0,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
versionStack: {
|
||||
id: 'stack-1',
|
||||
versions: [
|
||||
{ version: 2, current: true, id: 'child-2' },
|
||||
{ version: 1, current: false, id: 'child-1' },
|
||||
],
|
||||
},
|
||||
media: {
|
||||
imageTranscodes: [
|
||||
{
|
||||
id: 't1',
|
||||
key: 'k1',
|
||||
url: 'https://cdn/render-1080.webp',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
size: 200,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
describe('isImageItem', () => {
|
||||
it('detects images by proxyType and extension', () => {
|
||||
expect(isImageItem(dummyImage)).toBe(true)
|
||||
expect(isImageItem({ ...dummyFile, name: 'graphic.png' })).toBe(true)
|
||||
expect(isImageItem(dummyVersionStack)).toBe(true)
|
||||
expect(isImageItem(dummyFile)).toBe(false)
|
||||
expect(isImageItem(dummyFolder)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pickClipboardTranscode', () => {
|
||||
it('picks largest transcode <= 2048px on long edge', () => {
|
||||
const transcode = pickClipboardTranscode(dummyImage.media?.imageTranscodes)
|
||||
expect(transcode?.url).toBe('https://cdn/1080.webp')
|
||||
})
|
||||
|
||||
it('falls back to smallest available if all > 2048px', () => {
|
||||
const transcode = pickClipboardTranscode([
|
||||
{ url: 'https://cdn/4000.webp', width: 4000, height: 3000 },
|
||||
{ url: 'https://cdn/2500.webp', width: 2500, height: 2000 },
|
||||
])
|
||||
expect(transcode?.url).toBe('https://cdn/2500.webp')
|
||||
})
|
||||
|
||||
it('picks transcode by key even without presigned url', () => {
|
||||
const transcode = pickClipboardTranscode([
|
||||
{ key: 'files/asset-768p.webp', width: 768, height: 1376 },
|
||||
])
|
||||
expect(transcode?.key).toBe('files/asset-768p.webp')
|
||||
})
|
||||
|
||||
it('returns null if empty or missing', () => {
|
||||
expect(pickClipboardTranscode([])).toBeNull()
|
||||
expect(pickClipboardTranscode(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCopyOptions', () => {
|
||||
it('returns options for single image file with team owner', () => {
|
||||
const options = getCopyOptions([dummyImage], { isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).toEqual([
|
||||
'image',
|
||||
'name',
|
||||
'link',
|
||||
'download-link',
|
||||
'id',
|
||||
'markdown',
|
||||
'storage-path',
|
||||
])
|
||||
expect(options.find((o) => o.kind === 'image')?.disabled).toBe(false)
|
||||
expect(options.find((o) => o.kind === 'download-link')?.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('enables image option for processed image file with only transcode key and no url', () => {
|
||||
const imageWithoutUrls: AssetInfo = {
|
||||
...dummyImage,
|
||||
media: {
|
||||
imageTranscodes: [
|
||||
{
|
||||
id: 't1',
|
||||
key: 'files/asset-768p.webp',
|
||||
url: '',
|
||||
width: 768,
|
||||
height: 1376,
|
||||
size: 200,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
const options = getCopyOptions([imageWithoutUrls])
|
||||
expect(options.find((o) => o.kind === 'image')?.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('hides image option for non-image files', () => {
|
||||
const options = getCopyOptions([dummyFile], { isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).not.toContain('image')
|
||||
expect(kinds).toContain('download-link')
|
||||
expect(kinds).toContain('storage-path')
|
||||
})
|
||||
|
||||
it('hides download-link and storage-path for single folder', () => {
|
||||
const options = getCopyOptions([dummyFolder], { isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).toEqual(['name', 'link', 'id', 'markdown'])
|
||||
expect(kinds).not.toContain('download-link')
|
||||
expect(kinds).not.toContain('storage-path')
|
||||
})
|
||||
|
||||
it('handles multi-select with only files', () => {
|
||||
const options = getCopyOptions([dummyFile, dummyImage], { isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).toEqual([
|
||||
'name',
|
||||
'link',
|
||||
'download-link',
|
||||
'id',
|
||||
'markdown',
|
||||
'tsv',
|
||||
'storage-path',
|
||||
])
|
||||
expect(kinds).not.toContain('image')
|
||||
})
|
||||
|
||||
it('hides download-link and storage-path when all items in multi-select are folders', () => {
|
||||
const folder2 = { ...dummyFolder, id: 'folder-2', name: 'Folder 2' }
|
||||
const options = getCopyOptions([dummyFolder, folder2], { isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).toEqual(['name', 'link', 'id', 'markdown', 'tsv'])
|
||||
expect(kinds).not.toContain('download-link')
|
||||
expect(kinds).not.toContain('storage-path')
|
||||
})
|
||||
|
||||
it('disables download-link if all files in selection are archived', () => {
|
||||
const archivedFile: AssetInfo = { ...dummyFile, status: 'archived' }
|
||||
const options = getCopyOptions([archivedFile])
|
||||
expect(options.find((o) => o.kind === 'download-link')?.disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('hides id and storage-path in public share mode', () => {
|
||||
const options = getCopyOptions([dummyFile], { isPublicShare: true, isTeamOwner: true })
|
||||
const kinds = options.map((o) => o.kind)
|
||||
expect(kinds).not.toContain('id')
|
||||
expect(kinds).not.toContain('storage-path')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getItemInAppUrl', () => {
|
||||
it('formats URL for file and folder', () => {
|
||||
expect(getItemInAppUrl(dummyFile, 'https://shumai.app', 'proj-1')).toBe(
|
||||
'https://shumai.app/projects/proj-1/files/file-1',
|
||||
)
|
||||
expect(getItemInAppUrl(dummyFolder, 'https://shumai.app', 'proj-1')).toBe(
|
||||
'https://shumai.app/projects/proj-1/folders/folder-1',
|
||||
)
|
||||
expect(getItemInAppUrl(dummyVersionStack, 'https://shumai.app', 'proj-1')).toBe(
|
||||
'https://shumai.app/projects/proj-1/files/stack-1',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatCopyText', () => {
|
||||
const ctx = { origin: 'https://shumai.app', projectId: 'proj-1' }
|
||||
|
||||
it('formats name for single and multi-select', () => {
|
||||
expect(formatCopyText('name', [dummyFile], ctx)).toBe('document.pdf')
|
||||
expect(formatCopyText('name', [dummyFile, dummyFolder], ctx)).toBe('document.pdf\nAssets')
|
||||
})
|
||||
|
||||
it('formats link for single and multi-select', () => {
|
||||
expect(formatCopyText('link', [dummyFile], ctx)).toBe(
|
||||
'https://shumai.app/projects/proj-1/files/file-1',
|
||||
)
|
||||
expect(formatCopyText('link', [dummyFile, dummyFolder], ctx)).toBe(
|
||||
'https://shumai.app/projects/proj-1/files/file-1\nhttps://shumai.app/projects/proj-1/folders/folder-1',
|
||||
)
|
||||
})
|
||||
|
||||
it('formats id for single and multi-select', () => {
|
||||
expect(formatCopyText('id', [dummyFile], ctx)).toBe('file-1')
|
||||
expect(formatCopyText('id', [dummyVersionStack], ctx)).toBe('stack-1')
|
||||
expect(formatCopyText('id', [dummyFile, dummyFolder], ctx)).toBe('file-1\nfolder-1')
|
||||
})
|
||||
|
||||
it('formats markdown link for single and bullet list for multi-select', () => {
|
||||
expect(formatCopyText('markdown', [dummyFile], ctx)).toBe(
|
||||
'[document.pdf](https://shumai.app/projects/proj-1/files/file-1)',
|
||||
)
|
||||
expect(formatCopyText('markdown', [dummyFile, dummyFolder], ctx)).toBe(
|
||||
'- [document.pdf](https://shumai.app/projects/proj-1/files/file-1)\n- [Assets](https://shumai.app/projects/proj-1/folders/folder-1)',
|
||||
)
|
||||
})
|
||||
|
||||
it('formats TSV table with header and sizes for multi-select', () => {
|
||||
const tsv = formatCopyText('tsv', [dummyFile, dummyFolder], ctx)
|
||||
const lines = tsv.split('\n')
|
||||
expect(lines[0]).toBe('Name\tType\tSize\tLink\tID')
|
||||
expect(lines[1]).toContain(
|
||||
'document.pdf\tfile\t1.05 MB\thttps://shumai.app/projects/proj-1/files/file-1\tfile-1',
|
||||
)
|
||||
expect(lines[2]).toContain(
|
||||
'Assets\tfolder\t—\thttps://shumai.app/projects/proj-1/folders/folder-1\tfolder-1',
|
||||
)
|
||||
})
|
||||
|
||||
it('escapes brackets in markdown links', () => {
|
||||
const fileWithBrackets = { ...dummyFile, name: 'Report [Final] (v1).pdf' }
|
||||
expect(formatCopyText('markdown', [fileWithBrackets], ctx)).toBe(
|
||||
'[Report \\[Final\\] (v1).pdf](https://shumai.app/projects/proj-1/files/file-1)',
|
||||
)
|
||||
})
|
||||
|
||||
it('sanitizes tabs and newlines in TSV file names', () => {
|
||||
const fileWithTabs = { ...dummyFile, name: 'test\tfile\nname.pdf' }
|
||||
const tsv = formatCopyText('tsv', [fileWithTabs], ctx)
|
||||
expect(tsv).toContain('test file name.pdf\tfile\t1.05 MB')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
|
||||
export type CopyKind =
|
||||
'image' | 'name' | 'link' | 'download-link' | 'id' | 'markdown' | 'tsv' | 'storage-path'
|
||||
|
||||
export interface CopyOption {
|
||||
kind: CopyKind
|
||||
disabled: boolean
|
||||
hint?: string
|
||||
}
|
||||
|
||||
export interface CopyOptionsContext {
|
||||
isPublicShare?: boolean
|
||||
isTeamOwner?: boolean
|
||||
allowDownload?: boolean
|
||||
}
|
||||
|
||||
export interface CopyFormatContext {
|
||||
origin: string
|
||||
projectId?: string
|
||||
}
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set([
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'png',
|
||||
'webp',
|
||||
'gif',
|
||||
'svg',
|
||||
'bmp',
|
||||
'tiff',
|
||||
'avif',
|
||||
'heic',
|
||||
])
|
||||
|
||||
export function isImageItem(item: AssetInfo): boolean {
|
||||
if (item.type === 'folder' || item.type === 'root' || item.type === 'share_root') return false
|
||||
if (item.proxyType === 'image') return true
|
||||
const ext = item.name?.split('.').pop()?.toLowerCase()
|
||||
return IMAGE_EXTENSIONS.has(ext || '')
|
||||
}
|
||||
|
||||
export function isArchivedStatus(status?: string | null): boolean {
|
||||
return status === 'archived' || status === 'archiving' || status === 'restoring'
|
||||
}
|
||||
|
||||
export interface TranscodeCandidate {
|
||||
url?: string
|
||||
key?: string
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
export function pickClipboardTranscode(
|
||||
transcodes?: TranscodeCandidate[],
|
||||
): TranscodeCandidate | null {
|
||||
if (!transcodes || transcodes.length === 0) return null
|
||||
const valid = transcodes.filter((t) => !!t.url || !!t.key)
|
||||
if (valid.length === 0) return null
|
||||
|
||||
// Prefer largest transcode <= 2048px on long edge
|
||||
const suitable = valid.filter((t) => {
|
||||
const maxDim = Math.max(t.width || 0, t.height || 0)
|
||||
return maxDim <= 2048
|
||||
})
|
||||
|
||||
if (suitable.length > 0) {
|
||||
suitable.sort((a, b) => {
|
||||
const dimA = Math.max(a.width || 0, a.height || 0)
|
||||
const dimB = Math.max(b.width || 0, b.height || 0)
|
||||
return dimB - dimA
|
||||
})
|
||||
return suitable[0]
|
||||
}
|
||||
|
||||
// Fallback to smallest available if all > 2048px
|
||||
valid.sort((a, b) => {
|
||||
const dimA = Math.max(a.width || 0, a.height || 0)
|
||||
const dimB = Math.max(b.width || 0, b.height || 0)
|
||||
return dimA - dimB
|
||||
})
|
||||
return valid[0]
|
||||
}
|
||||
|
||||
export function getItemInAppUrl(item: AssetInfo, origin: string, projectId?: string): string {
|
||||
const base = origin.replace(/\/$/, '')
|
||||
if (item.type === 'folder') {
|
||||
return projectId
|
||||
? `${base}/projects/${projectId}/folders/${item.id}`
|
||||
: `${base}/folders/${item.id}`
|
||||
}
|
||||
const targetId = item.versionStack ? item.versionStack.id : item.id
|
||||
return projectId ? `${base}/projects/${projectId}/files/${targetId}` : `${base}/files/${targetId}`
|
||||
}
|
||||
|
||||
export function getCopyOptions(items: AssetInfo[], context: CopyOptionsContext = {}): CopyOption[] {
|
||||
if (items.length === 0) return []
|
||||
|
||||
const { isPublicShare = false, isTeamOwner = false, allowDownload = true } = context
|
||||
|
||||
const options: CopyOption[] = []
|
||||
|
||||
if (items.length === 1) {
|
||||
const item = items[0]
|
||||
const isImage = isImageItem(item)
|
||||
|
||||
if (isImage) {
|
||||
const isArchived = isArchivedStatus(item.status)
|
||||
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
|
||||
const hasTranscode =
|
||||
!!transcode || item.status === 'processed' || !!item.preview?.thumbnailUrl
|
||||
const disabled = isArchived || !hasTranscode || (isPublicShare && !allowDownload)
|
||||
options.push({ kind: 'image', disabled })
|
||||
}
|
||||
|
||||
options.push({ kind: 'name', disabled: false })
|
||||
options.push({ kind: 'link', disabled: false })
|
||||
|
||||
if (item.type !== 'folder') {
|
||||
const isArchived = isArchivedStatus(item.status)
|
||||
const disabled = isArchived || (isPublicShare && !allowDownload)
|
||||
options.push({ kind: 'download-link', disabled })
|
||||
}
|
||||
|
||||
if (!isPublicShare) {
|
||||
options.push({ kind: 'id', disabled: false })
|
||||
}
|
||||
|
||||
options.push({ kind: 'markdown', disabled: false })
|
||||
|
||||
if (isTeamOwner && !isPublicShare && item.type !== 'folder') {
|
||||
options.push({ kind: 'storage-path', disabled: false })
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// Multi-selection
|
||||
options.push({ kind: 'name', disabled: false })
|
||||
options.push({ kind: 'link', disabled: false })
|
||||
|
||||
const files = items.filter((i) => i.type !== 'folder')
|
||||
if (files.length > 0) {
|
||||
const allArchived = files.every((f) => isArchivedStatus(f.status))
|
||||
const disabled = allArchived || (isPublicShare && !allowDownload)
|
||||
options.push({ kind: 'download-link', disabled })
|
||||
}
|
||||
|
||||
if (!isPublicShare) {
|
||||
options.push({ kind: 'id', disabled: false })
|
||||
}
|
||||
|
||||
options.push({ kind: 'markdown', disabled: false })
|
||||
options.push({ kind: 'tsv', disabled: false })
|
||||
|
||||
if (isTeamOwner && !isPublicShare && files.length > 0) {
|
||||
options.push({ kind: 'storage-path', disabled: false })
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function formatCopyText(
|
||||
kind: CopyKind,
|
||||
items: AssetInfo[],
|
||||
context: CopyFormatContext,
|
||||
): string {
|
||||
if (items.length === 0) return ''
|
||||
|
||||
switch (kind) {
|
||||
case 'name':
|
||||
return items.map((i) => i.name).join('\n')
|
||||
|
||||
case 'link':
|
||||
return items.map((i) => getItemInAppUrl(i, context.origin, context.projectId)).join('\n')
|
||||
|
||||
case 'id':
|
||||
return items.map((i) => (i.versionStack ? i.versionStack.id : i.id)).join('\n')
|
||||
|
||||
case 'markdown':
|
||||
if (items.length === 1) {
|
||||
const item = items[0]
|
||||
const safeName = item.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
|
||||
const url = getItemInAppUrl(item, context.origin, context.projectId)
|
||||
return `[${safeName}](${url})`
|
||||
}
|
||||
return items
|
||||
.map((i) => {
|
||||
const safeName = i.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
|
||||
const url = getItemInAppUrl(i, context.origin, context.projectId)
|
||||
return `- [${safeName}](${url})`
|
||||
})
|
||||
.join('\n')
|
||||
|
||||
case 'tsv': {
|
||||
const header = 'Name\tType\tSize\tLink\tID'
|
||||
const rows = items.map((i) => {
|
||||
const type = i.type === 'folder' ? 'folder' : 'file'
|
||||
const size = i.type === 'folder' ? '—' : formatSize(i.sizeByte || 0)
|
||||
const link = getItemInAppUrl(i, context.origin, context.projectId)
|
||||
const id = i.versionStack ? i.versionStack.id : i.id
|
||||
const safeName = i.name.replace(/[\t\r\n]+/g, ' ')
|
||||
return `${safeName}\t${type}\t${size}\t${link}\t${id}`
|
||||
})
|
||||
return [header, ...rows].join('\n')
|
||||
}
|
||||
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuPortal,
|
||||
} from '@/ui/components/ui/context-menu'
|
||||
import {
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
Copy,
|
||||
Image as ImageIcon,
|
||||
FileText,
|
||||
Link,
|
||||
Download,
|
||||
Hash,
|
||||
Code,
|
||||
Table,
|
||||
HardDrive,
|
||||
} from 'lucide-react'
|
||||
import { type CopyKind, type CopyOptionsContext, getCopyOptions } from './copy-options'
|
||||
|
||||
interface CopyMenuProps {
|
||||
items: AssetInfo[]
|
||||
context: CopyOptionsContext
|
||||
onCopy: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
}
|
||||
|
||||
function renderCopyIcon(kind: CopyKind) {
|
||||
switch (kind) {
|
||||
case 'image':
|
||||
return <ImageIcon className="mr-2 h-4 w-4" />
|
||||
case 'name':
|
||||
return <FileText className="mr-2 h-4 w-4" />
|
||||
case 'link':
|
||||
return <Link className="mr-2 h-4 w-4" />
|
||||
case 'download-link':
|
||||
return <Download className="mr-2 h-4 w-4" />
|
||||
case 'id':
|
||||
return <Hash className="mr-2 h-4 w-4" />
|
||||
case 'markdown':
|
||||
return <Code className="mr-2 h-4 w-4" />
|
||||
case 'tsv':
|
||||
return <Table className="mr-2 h-4 w-4" />
|
||||
case 'storage-path':
|
||||
return <HardDrive className="mr-2 h-4 w-4" />
|
||||
}
|
||||
}
|
||||
|
||||
function renderCopyLabel(kind: CopyKind) {
|
||||
switch (kind) {
|
||||
case 'image':
|
||||
return m.copy_image()
|
||||
case 'name':
|
||||
return m.copy_name()
|
||||
case 'link':
|
||||
return m.copy_app_link()
|
||||
case 'download-link':
|
||||
return m.copy_download_link()
|
||||
case 'id':
|
||||
return m.copy_id()
|
||||
case 'markdown':
|
||||
return m.copy_markdown_link()
|
||||
case 'tsv':
|
||||
return m.copy_as_table()
|
||||
case 'storage-path':
|
||||
return m.copy_storage_path()
|
||||
}
|
||||
}
|
||||
|
||||
export function CopyContextMenuSub({ items, context, onCopy }: CopyMenuProps) {
|
||||
const options = getCopyOptions(items, context)
|
||||
if (options.length === 0) return null
|
||||
|
||||
const imageOpt = options.find((o) => o.kind === 'image')
|
||||
const coreOpts = options.filter((o) => ['name', 'link', 'download-link', 'id'].includes(o.kind))
|
||||
const docOpts = options.filter((o) => ['markdown', 'tsv'].includes(o.kind))
|
||||
const storageOpt = options.find((o) => o.kind === 'storage-path')
|
||||
|
||||
return (
|
||||
<ContextMenuSub>
|
||||
<ContextMenuSubTrigger>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>{m.copy()}</span>
|
||||
</ContextMenuSubTrigger>
|
||||
<ContextMenuPortal>
|
||||
<ContextMenuSubContent className="w-52">
|
||||
{imageOpt && (
|
||||
<>
|
||||
<ContextMenuItem disabled={imageOpt.disabled} onSelect={() => onCopy('image', items)}>
|
||||
{renderCopyIcon('image')}
|
||||
<span>{renderCopyLabel('image')}</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{coreOpts.map((opt) => (
|
||||
<ContextMenuItem
|
||||
key={opt.kind}
|
||||
disabled={opt.disabled}
|
||||
onSelect={() => onCopy(opt.kind, items)}
|
||||
>
|
||||
{renderCopyIcon(opt.kind)}
|
||||
<span>{renderCopyLabel(opt.kind)}</span>
|
||||
</ContextMenuItem>
|
||||
))}
|
||||
|
||||
{docOpts.length > 0 && (
|
||||
<>
|
||||
<ContextMenuSeparator />
|
||||
{docOpts.map((opt) => (
|
||||
<ContextMenuItem
|
||||
key={opt.kind}
|
||||
disabled={opt.disabled}
|
||||
onSelect={() => onCopy(opt.kind, items)}
|
||||
>
|
||||
{renderCopyIcon(opt.kind)}
|
||||
<span>{renderCopyLabel(opt.kind)}</span>
|
||||
</ContextMenuItem>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{storageOpt && (
|
||||
<>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem
|
||||
disabled={storageOpt.disabled}
|
||||
onSelect={() => onCopy('storage-path', items)}
|
||||
>
|
||||
{renderCopyIcon('storage-path')}
|
||||
<span>{renderCopyLabel('storage-path')}</span>
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
)}
|
||||
</ContextMenuSubContent>
|
||||
</ContextMenuPortal>
|
||||
</ContextMenuSub>
|
||||
)
|
||||
}
|
||||
|
||||
export function CopyDropdownMenuSub({ items, context, onCopy }: CopyMenuProps) {
|
||||
const options = getCopyOptions(items, context)
|
||||
if (options.length === 0) return null
|
||||
|
||||
const imageOpt = options.find((o) => o.kind === 'image')
|
||||
const coreOpts = options.filter((o) => ['name', 'link', 'download-link', 'id'].includes(o.kind))
|
||||
const docOpts = options.filter((o) => ['markdown', 'tsv'].includes(o.kind))
|
||||
const storageOpt = options.find((o) => o.kind === 'storage-path')
|
||||
|
||||
return (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>{m.copy()}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent className="w-52">
|
||||
{imageOpt && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
disabled={imageOpt.disabled}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onCopy('image', items)
|
||||
}}
|
||||
>
|
||||
{renderCopyIcon('image')}
|
||||
<span>{renderCopyLabel('image')}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{coreOpts.map((opt) => (
|
||||
<DropdownMenuItem
|
||||
key={opt.kind}
|
||||
disabled={opt.disabled}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onCopy(opt.kind, items)
|
||||
}}
|
||||
>
|
||||
{renderCopyIcon(opt.kind)}
|
||||
<span>{renderCopyLabel(opt.kind)}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
|
||||
{docOpts.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{docOpts.map((opt) => (
|
||||
<DropdownMenuItem
|
||||
key={opt.kind}
|
||||
disabled={opt.disabled}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onCopy(opt.kind, items)
|
||||
}}
|
||||
>
|
||||
{renderCopyIcon(opt.kind)}
|
||||
<span>{renderCopyLabel(opt.kind)}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{storageOpt && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
disabled={storageOpt.disabled}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onCopy('storage-path', items)
|
||||
}}
|
||||
>
|
||||
{renderCopyIcon('storage-path')}
|
||||
<span>{renderCopyLabel('storage-path')}</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
)
|
||||
}
|
||||
@@ -485,7 +485,7 @@ export function FileBrowser({
|
||||
handleRename,
|
||||
handleRestore,
|
||||
handleDownload,
|
||||
handleCopyNameAndDownloadLink,
|
||||
handleCopy,
|
||||
handleArchive,
|
||||
handleRestoreArchive,
|
||||
handleAction,
|
||||
@@ -781,6 +781,8 @@ export function FileBrowser({
|
||||
allowDownload,
|
||||
fields: displayedFields,
|
||||
canEdit,
|
||||
isTeamOwner: canAdmin,
|
||||
onCopy: handleCopy,
|
||||
archiveStorageEnabled,
|
||||
isExternalDragging,
|
||||
externalOverFolderId,
|
||||
@@ -1172,7 +1174,7 @@ export function FileBrowser({
|
||||
onRename={handleRename}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
onCopyNameAndDownloadLink={handleCopyNameAndDownloadLink}
|
||||
onCopy={handleCopy}
|
||||
onNewFolder={handleNewFolder}
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
@@ -1190,6 +1192,8 @@ export function FileBrowser({
|
||||
onArchive={handleArchive}
|
||||
onRestoreArchive={handleRestoreArchive}
|
||||
archiveStorageEnabled={archiveStorageEnabled}
|
||||
isTeamOwner={canAdmin}
|
||||
allowDownload={allowDownload}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
isRecents={isRecents}
|
||||
shareLinks={shareLinksData?.data ?? []}
|
||||
|
||||
@@ -772,4 +772,34 @@ describe('FileCard', () => {
|
||||
)
|
||||
expect(screen.getByTestId('file-card-restoring-badge')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('renders Copy submenu in dropdown menu', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileCard
|
||||
item={fileItem}
|
||||
isSelected={false}
|
||||
isChecked={false}
|
||||
isEditing={false}
|
||||
onSelect={vi.fn()}
|
||||
onDoubleClick={vi.fn()}
|
||||
onContextMenu={vi.fn()}
|
||||
onDragStart={vi.fn()}
|
||||
onDrop={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
onFinishEditing={vi.fn()}
|
||||
onSaveField={vi.fn()}
|
||||
onAction={vi.fn()}
|
||||
fields={[]}
|
||||
canEdit={true}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const moreBtn = screen.getByRole('button', { name: '' })
|
||||
fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' })
|
||||
|
||||
const copyOption = screen.getByText(/^Copy$|^复制$/i)
|
||||
expect(copyOption).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { CopyDropdownMenuSub } from './copy-submenu'
|
||||
import type { CopyKind } from './copy-options'
|
||||
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
@@ -89,6 +91,8 @@ interface FileCardProps {
|
||||
allowDownload?: boolean
|
||||
hideCheckbox?: boolean
|
||||
hideActions?: boolean
|
||||
isTeamOwner?: boolean
|
||||
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
}
|
||||
|
||||
export function FileCard({
|
||||
@@ -110,6 +114,8 @@ export function FileCard({
|
||||
dragState,
|
||||
disabled,
|
||||
onAction,
|
||||
onCopy,
|
||||
isTeamOwner = false,
|
||||
isRecentlyDeleted,
|
||||
isRecents,
|
||||
selectedCount,
|
||||
@@ -693,6 +699,16 @@ export function FileCard({
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{!isRecentlyDeleted && !isShareView && (
|
||||
<CopyDropdownMenuSub
|
||||
items={[item]}
|
||||
context={{
|
||||
isTeamOwner,
|
||||
allowDownload,
|
||||
}}
|
||||
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
|
||||
/>
|
||||
)}
|
||||
{canEdit && archiveStorageEnabled && canArchiveItem && (
|
||||
<DropdownMenuItem
|
||||
data-testid="file-card-archive-action"
|
||||
|
||||
@@ -12,6 +12,8 @@ import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { getTrashDaysLeft } from '@/ui/lib/time'
|
||||
import { CopyDropdownMenuSub } from './copy-submenu'
|
||||
import type { CopyKind } from './copy-options'
|
||||
import {
|
||||
Archive,
|
||||
ArchiveRestore,
|
||||
@@ -68,6 +70,8 @@ interface FolderCardProps {
|
||||
allowDownload?: boolean
|
||||
hideCheckbox?: boolean
|
||||
hideActions?: boolean
|
||||
isTeamOwner?: boolean
|
||||
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
}
|
||||
|
||||
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
|
||||
@@ -140,6 +144,8 @@ export function FolderCard({
|
||||
dragState,
|
||||
disabled,
|
||||
onAction,
|
||||
onCopy,
|
||||
isTeamOwner = false,
|
||||
isRecentlyDeleted,
|
||||
isRecents,
|
||||
selectedCount,
|
||||
@@ -473,6 +479,16 @@ export function FolderCard({
|
||||
<span>{m.download()}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{!isRecentlyDeleted && !isShareView && (
|
||||
<CopyDropdownMenuSub
|
||||
items={[item]}
|
||||
context={{
|
||||
isTeamOwner,
|
||||
allowDownload,
|
||||
}}
|
||||
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
|
||||
/>
|
||||
)}
|
||||
{canEdit && archiveStorageEnabled && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
|
||||
@@ -424,4 +424,17 @@ describe('MobileFileBrowser', () => {
|
||||
|
||||
expect(screen.queryByRole('button', { name: /actions/i })).toBeNull()
|
||||
})
|
||||
|
||||
it('renders Copy submenu in file card dropdown menu on mobile', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
const dropdownTrigger = container.querySelector(
|
||||
'[data-slot="dropdown-menu-trigger"]',
|
||||
) as HTMLElement
|
||||
expect(dropdownTrigger).toBeTruthy()
|
||||
fireEvent.keyDown(dropdownTrigger, { key: 'ArrowDown', code: 'ArrowDown' })
|
||||
|
||||
const copyOption = await screen.findByText(/^Copy$|^复制$/i)
|
||||
expect(copyOption).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -176,6 +176,7 @@ export function MobileFileBrowser({
|
||||
confirmArchiveOrRestore,
|
||||
isArchiving,
|
||||
isRestoringArchive,
|
||||
handleCopy,
|
||||
} = useFileActions({
|
||||
teamId,
|
||||
projectId,
|
||||
@@ -537,6 +538,8 @@ export function MobileFileBrowser({
|
||||
archiveStorageEnabled={archiveStorageEnabled}
|
||||
isShareView={isShareView}
|
||||
allowDownload={allowDownload}
|
||||
onCopy={handleCopy}
|
||||
isTeamOwner={canAdmin}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -600,6 +603,8 @@ export function MobileFileBrowser({
|
||||
archiveStorageEnabled={archiveStorageEnabled}
|
||||
isShareView={isShareView}
|
||||
allowDownload={allowDownload}
|
||||
onCopy={handleCopy}
|
||||
isTeamOwner={canAdmin}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useCopyActions } from './use-copy-actions'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { toast } from 'sonner'
|
||||
import * as clipboardModule from '@/ui/lib/clipboard'
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockDownloadUrlPost = vi.fn()
|
||||
const mockStoragePathsPost = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
'download-url': {
|
||||
$post: (...args: unknown[]) => mockDownloadUrlPost(...args),
|
||||
},
|
||||
'storage-paths': {
|
||||
$post: (...args: unknown[]) => mockStoragePathsPost(...args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('useCopyActions', () => {
|
||||
const dummyFile: AssetInfo = {
|
||||
id: 'f1',
|
||||
name: 'document.pdf',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 1024,
|
||||
fileCount: 0,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
}
|
||||
|
||||
const dummyFolder: AssetInfo = {
|
||||
id: 'd1',
|
||||
name: 'Folder1',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
sizeByte: 0,
|
||||
fileCount: 2,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
}
|
||||
|
||||
const dummyImage: AssetInfo = {
|
||||
id: 'img1',
|
||||
name: 'photo.jpg',
|
||||
type: 'file',
|
||||
proxyType: 'image',
|
||||
status: 'processed',
|
||||
sizeByte: 2048,
|
||||
fileCount: 0,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
media: {
|
||||
imageTranscodes: [
|
||||
{
|
||||
id: 't1',
|
||||
url: '',
|
||||
key: 'files/img1/proxy-768p.webp',
|
||||
width: 768,
|
||||
height: 1024,
|
||||
size: 500,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('R2 Regression: Empty download links or storage paths', () => {
|
||||
it('does not touch clipboard and does not toast success when all files are archived', async () => {
|
||||
const getDownloadLinks = vi.fn().mockResolvedValue({
|
||||
files: [],
|
||||
skippedArchivedCount: 2,
|
||||
})
|
||||
|
||||
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
|
||||
const copyTextSpy = vi.spyOn(clipboardModule, 'copyToClipboard')
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks,
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('download-link', [dummyFile, { ...dummyFile, id: 'f2' }])
|
||||
})
|
||||
|
||||
// Must show error toast
|
||||
expect(toast.error).toHaveBeenCalled()
|
||||
// Must NOT show success toast
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
// Must NOT have copied empty string with copyToClipboard
|
||||
expect(copyTextSpy).not.toHaveBeenCalled()
|
||||
// If deferred was called, it should have returned false and avoided success
|
||||
if (copyDeferredSpy.mock.results.length > 0) {
|
||||
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not toast success and shows error toast when storage paths return empty array', async () => {
|
||||
mockStoragePathsPost.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ paths: [] }),
|
||||
})
|
||||
|
||||
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('storage-path', [dummyFile])
|
||||
})
|
||||
|
||||
expect(toast.error).toHaveBeenCalled()
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
if (copyDeferredSpy.mock.results.length > 0) {
|
||||
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('image copying', () => {
|
||||
it('resolves download URL on demand for transcode key and copies image to clipboard', async () => {
|
||||
mockDownloadUrlPost.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
|
||||
})
|
||||
|
||||
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('image', [dummyImage])
|
||||
})
|
||||
|
||||
expect(mockDownloadUrlPost).toHaveBeenCalledWith({
|
||||
json: { key: 'files/img1/proxy-768p.webp', assetId: 'img1' },
|
||||
})
|
||||
expect(copyImageSpy).toHaveBeenCalled()
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to thumbnail URL if no transcodes are present', async () => {
|
||||
const imageWithThumb: AssetInfo = {
|
||||
...dummyImage,
|
||||
media: undefined,
|
||||
preview: {
|
||||
thumbnailUrl: 'https://cdn/thumb.webp',
|
||||
},
|
||||
}
|
||||
|
||||
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('image', [imageWithThumb])
|
||||
})
|
||||
|
||||
expect(copyImageSpy).toHaveBeenCalled()
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('toasts error if copying image fails or is unsupported', async () => {
|
||||
vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(false)
|
||||
mockDownloadUrlPost.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
|
||||
})
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('image', [dummyImage])
|
||||
})
|
||||
|
||||
expect(toast.error).toHaveBeenCalled()
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('download links copying', () => {
|
||||
it('copies download links and shows skipped folders suffix when folders are included', async () => {
|
||||
const getDownloadLinks = vi.fn().mockResolvedValue({
|
||||
files: [{ id: 'f1', name: 'document.pdf', url: 'https://cdn/download-1' }],
|
||||
})
|
||||
|
||||
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks,
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('download-link', [dummyFile, dummyFolder])
|
||||
})
|
||||
|
||||
expect(getDownloadLinks).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('storage paths copying', () => {
|
||||
it('fetches storage paths and copies via deferred clipboard', async () => {
|
||||
mockStoragePathsPost.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
paths: [
|
||||
{
|
||||
id: 'f1',
|
||||
name: 'document.pdf',
|
||||
path: '/data/shumai/files/1',
|
||||
backend: 'local',
|
||||
isArchived: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
})
|
||||
|
||||
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCopy('storage-path', [dummyFile])
|
||||
})
|
||||
|
||||
expect(mockStoragePathsPost).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('text copying formats', () => {
|
||||
it('copies name, link, id, markdown, and tsv with success toasts', async () => {
|
||||
vi.spyOn(clipboardModule, 'copyToClipboard').mockResolvedValue(true)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCopyActions({
|
||||
projectId: 'p1',
|
||||
getDownloadLinks: vi.fn(),
|
||||
}),
|
||||
)
|
||||
|
||||
for (const kind of ['name', 'link', 'id', 'markdown', 'tsv'] as const) {
|
||||
vi.clearAllMocks()
|
||||
await act(async () => {
|
||||
await result.current.handleCopy(kind, [dummyFile, dummyFolder])
|
||||
})
|
||||
expect(clipboardModule.copyToClipboard).toHaveBeenCalled()
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { toast } from 'sonner'
|
||||
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
|
||||
import { type CopyKind, formatCopyText, pickClipboardTranscode } from './copy-options'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export interface UseCopyActionsProps {
|
||||
projectId?: string
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
getDownloadLinks: (args: { json: { ids: string[] } }) => Promise<{
|
||||
files: Array<{ id: string; name: string; url: string }>
|
||||
skippedArchivedCount?: number
|
||||
}>
|
||||
}
|
||||
|
||||
export function useCopyActions({
|
||||
projectId,
|
||||
isPublic,
|
||||
shareId,
|
||||
getDownloadLinks,
|
||||
}: UseCopyActionsProps) {
|
||||
const handleCopy = async (kind: CopyKind, items: AssetInfo[]) => {
|
||||
if (items.length === 0) return
|
||||
|
||||
if (kind === 'image') {
|
||||
const item = items[0]
|
||||
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
|
||||
|
||||
if (!transcode && !item.preview?.thumbnailUrl && item.status !== 'processed') {
|
||||
toast.error(m.copy_image_failed())
|
||||
return
|
||||
}
|
||||
|
||||
const fetchImageUrl = async (): Promise<string> => {
|
||||
if (transcode?.url) return transcode.url
|
||||
if (transcode?.key && item.id) {
|
||||
if (isPublic && shareId) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
|
||||
{
|
||||
param: { shareId, fileId: item.id },
|
||||
json: { key: transcode.key },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
},
|
||||
},
|
||||
)
|
||||
if (res.ok) {
|
||||
const { url } = await res.json()
|
||||
return url
|
||||
}
|
||||
} else {
|
||||
const res = await client.api.files['download-url'].$post({
|
||||
json: { key: transcode.key, assetId: item.id },
|
||||
})
|
||||
if (res.ok) {
|
||||
const { url } = await res.json()
|
||||
return url
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.preview?.thumbnailUrl) {
|
||||
return item.preview.thumbnailUrl
|
||||
}
|
||||
throw new Error('No image URL available')
|
||||
}
|
||||
|
||||
try {
|
||||
const ok = await copyImageToClipboard(fetchImageUrl())
|
||||
if (ok) {
|
||||
toast.success(m.copied_image_toast())
|
||||
} else {
|
||||
toast.error(m.copy_image_failed())
|
||||
}
|
||||
} catch {
|
||||
toast.error(m.copy_image_failed())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (kind === 'download-link') {
|
||||
const targetFiles = items.filter((i) => i.type !== 'folder')
|
||||
if (targetFiles.length === 0) return
|
||||
|
||||
let hasShownEmptyError = false
|
||||
try {
|
||||
const fetchDownloadLinksPromise = (async () => {
|
||||
const res = await getDownloadLinks({
|
||||
json: { ids: targetFiles.map((i) => i.id!) },
|
||||
})
|
||||
const files = res.files
|
||||
if (files.length === 0) {
|
||||
hasShownEmptyError = true
|
||||
if ((res.skippedArchivedCount ?? 0) > 0) {
|
||||
toast.error(m.download_all_archived_error())
|
||||
} else {
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
throw new Error('NO_FILES_TO_COPY')
|
||||
}
|
||||
return files.map((f) => f.url).join('\n')
|
||||
})()
|
||||
|
||||
const ok = await copyToClipboardDeferred(fetchDownloadLinksPromise)
|
||||
if (ok) {
|
||||
const skippedFolders = items.length - targetFiles.length
|
||||
if (targetFiles.length === 1 && skippedFolders === 0) {
|
||||
toast.success(m.copied_download_link_toast())
|
||||
} else {
|
||||
const baseToast = m.copied_download_links_toast({ count: targetFiles.length })
|
||||
const msg =
|
||||
skippedFolders > 0
|
||||
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
|
||||
: baseToast
|
||||
toast.success(msg)
|
||||
}
|
||||
} else if (!hasShownEmptyError) {
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
} catch (err) {
|
||||
if (!hasShownEmptyError) {
|
||||
console.error('Failed to copy download links:', err)
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (kind === 'storage-path') {
|
||||
const targetFiles = items.filter((i) => i.type !== 'folder')
|
||||
if (targetFiles.length === 0) return
|
||||
|
||||
let hasShownEmptyError = false
|
||||
try {
|
||||
const fetchStoragePathsPromise = (async () => {
|
||||
const res = await client.api.files['storage-paths'].$post({
|
||||
json: { ids: targetFiles.map((i) => i.id!) },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch storage paths')
|
||||
const data = await res.json()
|
||||
if (!data.paths || data.paths.length === 0) {
|
||||
hasShownEmptyError = true
|
||||
toast.error(m.copy_failed())
|
||||
throw new Error('NO_PATHS_TO_COPY')
|
||||
}
|
||||
return data.paths.map((p) => p.path).join('\n')
|
||||
})()
|
||||
|
||||
const ok = await copyToClipboardDeferred(fetchStoragePathsPromise)
|
||||
if (ok) {
|
||||
const skippedFolders = items.length - targetFiles.length
|
||||
if (targetFiles.length === 1 && skippedFolders === 0) {
|
||||
toast.success(m.copied_storage_path_toast())
|
||||
} else {
|
||||
const baseToast = m.copied_storage_paths_toast({ count: targetFiles.length })
|
||||
const msg =
|
||||
skippedFolders > 0
|
||||
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
|
||||
: baseToast
|
||||
toast.success(msg)
|
||||
}
|
||||
} else if (!hasShownEmptyError) {
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
} catch (err) {
|
||||
if (!hasShownEmptyError) {
|
||||
console.error('Failed to copy storage paths:', err)
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Synchronous text copy
|
||||
const origin = typeof window !== 'undefined' ? window.location.origin : ''
|
||||
const text = formatCopyText(kind, items, { origin, projectId })
|
||||
const ok = await copyToClipboard(text)
|
||||
|
||||
if (ok) {
|
||||
switch (kind) {
|
||||
case 'name':
|
||||
toast.success(
|
||||
items.length === 1
|
||||
? m.copied_name_toast()
|
||||
: m.copied_names_toast({ count: items.length }),
|
||||
)
|
||||
break
|
||||
case 'link':
|
||||
toast.success(
|
||||
items.length === 1
|
||||
? m.copied_link_toast()
|
||||
: m.copied_links_toast({ count: items.length }),
|
||||
)
|
||||
break
|
||||
case 'id':
|
||||
toast.success(
|
||||
items.length === 1 ? m.copied_id_toast() : m.copied_ids_toast({ count: items.length }),
|
||||
)
|
||||
break
|
||||
case 'markdown':
|
||||
toast.success(
|
||||
items.length === 1
|
||||
? m.copied_markdown_link_toast()
|
||||
: m.copied_markdown_links_toast({ count: items.length }),
|
||||
)
|
||||
break
|
||||
case 'tsv':
|
||||
toast.success(m.copied_table_toast({ count: items.length }))
|
||||
break
|
||||
}
|
||||
} else {
|
||||
toast.error(m.copy_failed())
|
||||
}
|
||||
}
|
||||
|
||||
return { handleCopy }
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { copyToClipboard } from '@/ui/lib/clipboard'
|
||||
import { useCopyActions } from './use-copy-actions'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface UseFileActionsProps {
|
||||
@@ -316,36 +316,12 @@ export function useFileActions({
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyNameAndDownloadLink = async (items: AssetInfo[]) => {
|
||||
if (items.length === 0) return
|
||||
try {
|
||||
const res = await getDownloadLinks({
|
||||
json: { ids: items.map((i) => i.id!) },
|
||||
})
|
||||
const files = res.files
|
||||
if (files.length === 0) {
|
||||
if ((res.skippedArchivedCount ?? 0) > 0) {
|
||||
toast.error(m.download_all_archived_error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let text = ''
|
||||
if (files.length === 1) {
|
||||
text = `Name: ${files[0].name}\nPath: ${files[0].url}`
|
||||
} else {
|
||||
text = files.map((f) => `${f.name}\t${f.url}`).join('\n')
|
||||
}
|
||||
|
||||
const ok = await copyToClipboard(text)
|
||||
if (ok) {
|
||||
toast.success(m.copied_name_and_download_link_to_clipboard())
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Failed to copy name and download link')
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
const { handleCopy } = useCopyActions({
|
||||
projectId,
|
||||
isPublic,
|
||||
shareId,
|
||||
getDownloadLinks: (args) => getDownloadLinks(args),
|
||||
})
|
||||
|
||||
const handleArchive = (items: AssetInfo[]) => {
|
||||
if (items.length === 0) return
|
||||
@@ -543,7 +519,7 @@ export function useFileActions({
|
||||
handleRestore(targetItems)
|
||||
break
|
||||
case 'copy-name-and-download-link':
|
||||
handleCopyNameAndDownloadLink(targetItems)
|
||||
handleCopy('download-link', targetItems)
|
||||
break
|
||||
case 'archive':
|
||||
handleArchive(targetItems)
|
||||
@@ -561,7 +537,7 @@ export function useFileActions({
|
||||
handleDelete,
|
||||
handleRestore,
|
||||
handleDownload,
|
||||
handleCopyNameAndDownloadLink,
|
||||
handleCopy,
|
||||
handleArchive,
|
||||
handleRestoreArchive,
|
||||
handleNewFolder,
|
||||
|
||||
@@ -199,14 +199,12 @@ export function FileViewerRightSidebar({
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
}: {
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
guestUserId?: string
|
||||
second?: number | null
|
||||
}) => {
|
||||
if (isPublic) {
|
||||
@@ -225,7 +223,6 @@ export function FileViewerRightSidebar({
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -310,7 +307,7 @@ export function FileViewerRightSidebar({
|
||||
setIsGuestPopupOpen(true)
|
||||
return
|
||||
}
|
||||
createComment({ text, attachmentIds, annotations, replyToId, guestUserId, second })
|
||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
||||
}
|
||||
@@ -320,10 +317,9 @@ export function FileViewerRightSidebar({
|
||||
setReplyingTo(null)
|
||||
}
|
||||
|
||||
const handleGuestSuccess = (guestUserId: string) => {
|
||||
console.log('[handleGuestSuccess] guestUserId:', guestUserId)
|
||||
const handleGuestSuccess = () => {
|
||||
if (pendingComment) {
|
||||
createComment({ ...pendingComment, guestUserId })
|
||||
createComment({ ...pendingComment })
|
||||
setPendingComment(null)
|
||||
setReplyingTo(null)
|
||||
}
|
||||
@@ -473,6 +469,7 @@ export function FileViewerRightSidebar({
|
||||
isOpen={isGuestPopupOpen}
|
||||
onClose={() => setIsGuestPopupOpen(false)}
|
||||
onSuccess={handleGuestSuccess}
|
||||
shareId={shareId || undefined}
|
||||
>
|
||||
<ChatInput
|
||||
projectId={projectId}
|
||||
|
||||
@@ -170,14 +170,12 @@ export function MobileFileBottomSheet({
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
}: {
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
guestUserId?: string
|
||||
second?: number | null
|
||||
}) => {
|
||||
if (isPublic) {
|
||||
@@ -196,7 +194,6 @@ export function MobileFileBottomSheet({
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -285,7 +282,6 @@ export function MobileFileBottomSheet({
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId: actualReplyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
})
|
||||
}
|
||||
@@ -295,9 +291,9 @@ export function MobileFileBottomSheet({
|
||||
setReplyingTo(null)
|
||||
}
|
||||
|
||||
const handleGuestSuccess = (guestUserId: string) => {
|
||||
const handleGuestSuccess = () => {
|
||||
if (pendingComment) {
|
||||
createComment({ ...pendingComment, guestUserId })
|
||||
createComment({ ...pendingComment })
|
||||
setPendingComment(null)
|
||||
setReplyingTo(null)
|
||||
}
|
||||
@@ -442,6 +438,7 @@ export function MobileFileBottomSheet({
|
||||
isOpen={isGuestPopupOpen}
|
||||
onClose={() => setIsGuestPopupOpen(false)}
|
||||
onSuccess={handleGuestSuccess}
|
||||
shareId={shareId || undefined}
|
||||
>
|
||||
<ChatInput
|
||||
projectId={projectId}
|
||||
|
||||
@@ -13,6 +13,7 @@ interface GuestIdentityPopupProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSuccess: (guestUserId: string) => void
|
||||
shareId?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
@@ -20,6 +21,7 @@ export function GuestIdentityPopup({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
shareId,
|
||||
children,
|
||||
}: GuestIdentityPopupProps) {
|
||||
const [name, setName] = useState('')
|
||||
@@ -34,7 +36,7 @@ export function GuestIdentityPopup({
|
||||
|
||||
try {
|
||||
const res = await client.api.identify.$post({
|
||||
json: { username: name, email: email },
|
||||
json: { username: name, email: email, shareId: shareId || undefined },
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -43,6 +45,9 @@ export function GuestIdentityPopup({
|
||||
}
|
||||
|
||||
const { id } = await res.json()
|
||||
if (shareId) {
|
||||
localStorage.setItem(`guest_user_id_${shareId}`, id)
|
||||
}
|
||||
localStorage.setItem('guest_user_id', id)
|
||||
onSuccess(id)
|
||||
onClose()
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { StorageSettings } from './StorageSettings'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const mockGetSettings = vi.fn()
|
||||
const mockPatchSettings = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
settings: {
|
||||
$get: () => mockGetSettings(),
|
||||
$patch: (args: unknown) => mockPatchSettings(args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('StorageSettings', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
mockGetSettings.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
archiveStorage: {
|
||||
enabled: true,
|
||||
backend: 's3',
|
||||
bucket: 'my-archive-bucket',
|
||||
endpoint: 'https://s3.custom.com',
|
||||
},
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
}),
|
||||
})
|
||||
mockPatchSettings.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
autoArchive: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const renderComponent = () =>
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StorageSettings teamId="team-storage-123" />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
it('renders archive storage details for S3 backend when configured', async () => {
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('my-archive-bucket')).toBeDefined()
|
||||
expect(screen.getByText('https://s3.custom.com')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('renders archive storage details for local backend', async () => {
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
archiveStorage: {
|
||||
enabled: true,
|
||||
backend: 'local',
|
||||
localRoot: '/var/data/archive',
|
||||
},
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('/var/data/archive')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('renders warning alert and disables auto-archive form when archive storage is not configured', async () => {
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
archiveStorage: {
|
||||
enabled: false,
|
||||
},
|
||||
autoArchive: {
|
||||
enabled: false,
|
||||
method: 'not_updated',
|
||||
days: 30,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
const switchElement = screen.getByRole('switch')
|
||||
expect(switchElement.hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('submits updated auto-archive configuration when Save is clicked', async () => {
|
||||
renderComponent()
|
||||
|
||||
const switchElement = await screen.findByRole('switch')
|
||||
expect(switchElement.getAttribute('data-state')).toBe('unchecked')
|
||||
fireEvent.click(switchElement)
|
||||
|
||||
const daysInput = await screen.findByLabelText(/Age Threshold/i)
|
||||
fireEvent.change(daysInput, { target: { value: '60' } })
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /Save/i })
|
||||
fireEvent.click(saveButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPatchSettings).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-storage-123' },
|
||||
json: {
|
||||
key: 'autoArchive',
|
||||
value: {
|
||||
enabled: true,
|
||||
method: 'not_updated',
|
||||
days: 60,
|
||||
postRestoreGraceDays: 30,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('handles error when saving auto-archive configuration fails', async () => {
|
||||
mockPatchSettings.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({ message: 'Cannot save settings' }),
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
const saveButton = await screen.findByRole('button', { name: /Save/i })
|
||||
fireEvent.click(saveButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('Cannot save settings')
|
||||
})
|
||||
})
|
||||
|
||||
it('allows clearing the days input and clamps value on blur', async () => {
|
||||
renderComponent()
|
||||
|
||||
const daysInput = (await screen.findByLabelText(/Age Threshold/i)) as HTMLInputElement
|
||||
expect(daysInput.value).toBe('30')
|
||||
|
||||
// User clears the field
|
||||
fireEvent.change(daysInput, { target: { value: '' } })
|
||||
expect(daysInput.value).toBe('')
|
||||
|
||||
// User types new value
|
||||
fireEvent.change(daysInput, { target: { value: '45' } })
|
||||
expect(daysInput.value).toBe('45')
|
||||
|
||||
// Blur clamps if out of range
|
||||
fireEvent.change(daysInput, { target: { value: '99999' } })
|
||||
fireEvent.blur(daysInput)
|
||||
expect(daysInput.value).toBe('3650')
|
||||
})
|
||||
|
||||
it('renders error state and retries on button click', async () => {
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /Retry/i })).toBeDefined()
|
||||
})
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
archiveStorage: { enabled: true, backend: 'local', localRoot: '/tmp/retry-path' },
|
||||
autoArchive: { enabled: false, method: 'not_updated', days: 30, postRestoreGraceDays: 30 },
|
||||
}),
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Retry/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('/tmp/retry-path')).toBeDefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,358 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
} from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Loader2, HardDrive, CheckCircle2, AlertTriangle, Info, AlertCircle } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { TeamSettingsResponse, AutoArchiveMethod } from '@shumai/dtos'
|
||||
|
||||
interface StorageSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
function clampDays(val: string | number, defaultVal = 30): number {
|
||||
const parsed = typeof val === 'number' ? val : parseInt(val, 10)
|
||||
if (isNaN(parsed)) return defaultVal
|
||||
return Math.min(3650, Math.max(1, parsed))
|
||||
}
|
||||
|
||||
export const StorageSettings: React.FC<StorageSettingsProps> = ({ teamId }) => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const {
|
||||
data: settings,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery<TeamSettingsResponse>({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return (await res.json()) as TeamSettingsResponse
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
const [enabled, setEnabled] = useState(false)
|
||||
const [method, setMethod] = useState<AutoArchiveMethod>('not_updated')
|
||||
const [daysInput, setDaysInput] = useState('30')
|
||||
const [postRestoreGraceDaysInput, setPostRestoreGraceDaysInput] = useState('30')
|
||||
const [isDirty, setIsDirty] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (settings?.autoArchive && !isDirty) {
|
||||
setEnabled(settings.autoArchive.enabled ?? false)
|
||||
setMethod(settings.autoArchive.method ?? 'not_updated')
|
||||
setDaysInput(String(settings.autoArchive.days ?? 30))
|
||||
setPostRestoreGraceDaysInput(String(settings.autoArchive.postRestoreGraceDays ?? 30))
|
||||
}
|
||||
}, [settings?.autoArchive, isDirty])
|
||||
|
||||
const archiveStorage = settings?.archiveStorage
|
||||
const isArchiveConfigured = Boolean(archiveStorage?.enabled)
|
||||
|
||||
const { mutate: saveAutoArchiveSettings, isPending: isSaving } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const days = clampDays(daysInput, 30)
|
||||
const postRestoreGraceDays = clampDays(postRestoreGraceDaysInput, 30)
|
||||
|
||||
const res = await client.api.teams[':teamId'].settings.$patch({
|
||||
param: { teamId },
|
||||
json: {
|
||||
key: 'autoArchive',
|
||||
value: {
|
||||
enabled,
|
||||
method,
|
||||
days,
|
||||
postRestoreGraceDays,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => null)) as { message?: string } | null
|
||||
throw new Error(err?.message || m.auto_archive_settings_save_failed())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
setIsDirty(false)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
})
|
||||
toast.success(m.auto_archive_settings_saved())
|
||||
},
|
||||
onError: (err: unknown) => {
|
||||
toast.error(err instanceof Error ? err.message : m.auto_archive_settings_save_failed())
|
||||
},
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="h-full overflow-y-auto space-y-6 pr-1">
|
||||
<Card className="border-destructive/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive flex items-center gap-2">
|
||||
<AlertCircle className="w-5 h-5" />
|
||||
{m.failed_to_load_storage_settings()}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{error instanceof Error ? error.message : m.failed_load_settings()}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardFooter>
|
||||
<Button variant="outline" onClick={() => refetch()}>
|
||||
{m.retry()}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto space-y-6 pr-1">
|
||||
{/* Read-only Archive Storage Config Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<HardDrive className="h-5 w-5 text-primary" />
|
||||
{m.archive_storage_config_card()}
|
||||
</CardTitle>
|
||||
<CardDescription>{m.archive_storage_config_card_description()}</CardDescription>
|
||||
</div>
|
||||
{isArchiveConfigured ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-emerald-600 border-emerald-300 bg-emerald-50 dark:bg-emerald-950/40 dark:border-emerald-800 dark:text-emerald-400 flex items-center gap-1.5"
|
||||
>
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
{m.archive_storage_configured()}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-amber-600 border-amber-300 bg-amber-50 dark:bg-amber-950/40 dark:border-amber-800 dark:text-amber-400 flex items-center gap-1.5"
|
||||
>
|
||||
<AlertTriangle className="w-3.5 h-3.5" />
|
||||
{m.archive_storage_not_configured()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{!isArchiveConfigured ? (
|
||||
<div className="rounded-lg border border-amber-200 bg-amber-50/50 p-4 dark:border-amber-900/50 dark:bg-amber-950/20 text-sm text-amber-800 dark:text-amber-300 flex items-start gap-3">
|
||||
<AlertTriangle className="w-5 h-5 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium">{m.archive_storage_not_configured()}</p>
|
||||
<p className="text-xs text-amber-700 dark:text-amber-400 mt-1">
|
||||
{m.archive_storage_not_configured_alert()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-1 rounded-lg border border-border p-3">
|
||||
<label className="text-xs text-muted-foreground uppercase tracking-wider font-semibold">
|
||||
{m.archive_storage_backend()}
|
||||
</label>
|
||||
<p className="text-sm font-medium">
|
||||
{archiveStorage?.backend === 's3'
|
||||
? m.archive_storage_backend_s3()
|
||||
: m.archive_storage_backend_local()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{archiveStorage?.backend === 's3' ? (
|
||||
<>
|
||||
<div className="space-y-1 rounded-lg border border-border p-3">
|
||||
<label className="text-xs text-muted-foreground uppercase tracking-wider font-semibold">
|
||||
{m.archive_storage_bucket()}
|
||||
</label>
|
||||
<p className="text-sm font-medium font-mono">{archiveStorage?.bucket || '-'}</p>
|
||||
</div>
|
||||
<div className="space-y-1 rounded-lg border border-border p-3 md:col-span-2">
|
||||
<label className="text-xs text-muted-foreground uppercase tracking-wider font-semibold">
|
||||
{m.archive_storage_endpoint()}
|
||||
</label>
|
||||
<p className="text-sm font-medium font-mono">
|
||||
{archiveStorage?.endpoint || m.archive_storage_default_endpoint()}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="space-y-1 rounded-lg border border-border p-3 md:col-span-2">
|
||||
<label className="text-xs text-muted-foreground uppercase tracking-wider font-semibold">
|
||||
{m.archive_storage_local_root()}
|
||||
</label>
|
||||
<p className="text-sm font-medium font-mono">
|
||||
{archiveStorage?.localRoot || '-'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Auto Archive Config Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.auto_archive_card()}</CardTitle>
|
||||
<CardDescription>{m.auto_archive_card_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{!isArchiveConfigured && (
|
||||
<div className="rounded-lg border border-border bg-muted/40 p-3 text-xs text-muted-foreground flex items-center gap-2">
|
||||
<Info className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||
<span>{m.auto_archive_disabled_hint()}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Toggle Auto Archive */}
|
||||
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="enable-auto-archive-switch"
|
||||
className="text-sm font-medium leading-none cursor-pointer"
|
||||
>
|
||||
{m.enable_auto_archive()}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">{m.enable_auto_archive_description()}</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="enable-auto-archive-switch"
|
||||
checked={enabled}
|
||||
onCheckedChange={(val) => {
|
||||
setIsDirty(true)
|
||||
setEnabled(val)
|
||||
}}
|
||||
disabled={!isArchiveConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Method and Days Configuration */}
|
||||
<div className="space-y-4 rounded-lg border border-border p-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">{m.auto_archive_method()}</label>
|
||||
<Select
|
||||
value={method}
|
||||
onValueChange={(val) => {
|
||||
setIsDirty(true)
|
||||
setMethod(val as AutoArchiveMethod)
|
||||
}}
|
||||
disabled={!isArchiveConfigured || isSaving}
|
||||
>
|
||||
<SelectTrigger id="auto-archive-method-trigger">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="not_updated">{m.auto_archive_method_not_updated()}</SelectItem>
|
||||
<SelectItem value="after_created">
|
||||
{m.auto_archive_method_after_created()}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">{m.auto_archive_method_description()}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="auto-archive-days-input" className="text-sm font-medium">
|
||||
{m.auto_archive_days()}
|
||||
</label>
|
||||
<Input
|
||||
id="auto-archive-days-input"
|
||||
type="number"
|
||||
min={1}
|
||||
max={3650}
|
||||
value={daysInput}
|
||||
onChange={(e) => {
|
||||
setIsDirty(true)
|
||||
setDaysInput(e.target.value)
|
||||
}}
|
||||
onBlur={() => {
|
||||
setDaysInput(String(clampDays(daysInput, 30)))
|
||||
}}
|
||||
disabled={!isArchiveConfigured || isSaving}
|
||||
className="w-full md:w-64"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{m.auto_archive_days_description()}</p>
|
||||
</div>
|
||||
|
||||
{method === 'after_created' && (
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="auto-archive-post-restore-grace-days-input"
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{m.auto_archive_post_restore_grace_days()}
|
||||
</label>
|
||||
<Input
|
||||
id="auto-archive-post-restore-grace-days-input"
|
||||
type="number"
|
||||
min={1}
|
||||
max={3650}
|
||||
value={postRestoreGraceDaysInput}
|
||||
onChange={(e) => {
|
||||
setIsDirty(true)
|
||||
setPostRestoreGraceDaysInput(e.target.value)
|
||||
}}
|
||||
onBlur={() => {
|
||||
setPostRestoreGraceDaysInput(String(clampDays(postRestoreGraceDaysInput, 30)))
|
||||
}}
|
||||
disabled={!isArchiveConfigured || isSaving}
|
||||
className="w-full md:w-64"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.auto_archive_post_restore_grace_days_description()}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-end border-t border-border pt-4">
|
||||
<Button
|
||||
onClick={() => saveAutoArchiveSettings()}
|
||||
disabled={!isArchiveConfigured || isSaving}
|
||||
>
|
||||
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{m.save()}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ function ContextMenuSubTrigger({
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import { copyImageToClipboard } from '@/ui/lib/clipboard'
|
||||
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { ImageControlBar } from './image-control-bar'
|
||||
@@ -128,49 +129,10 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
const handleCopy = async () => {
|
||||
const webpUrl = bestUrl
|
||||
if (!webpUrl) return
|
||||
try {
|
||||
const copyPromise = (async () => {
|
||||
const response = await fetch(webpUrl)
|
||||
const blob = await response.blob()
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
img.src = objectUrl
|
||||
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve
|
||||
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
|
||||
})
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = img.width
|
||||
canvas.height = img.height
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Could not get canvas context')
|
||||
ctx.drawImage(img, 0, 0)
|
||||
|
||||
const pngBlob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/png')
|
||||
})
|
||||
|
||||
if (!pngBlob) throw new Error('Failed to convert image to PNG')
|
||||
return pngBlob
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
})()
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': copyPromise,
|
||||
}),
|
||||
])
|
||||
const ok = await copyImageToClipboard(webpUrl)
|
||||
if (ok) {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to copy image to clipboard:', err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { copyToClipboard } from './clipboard'
|
||||
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from './clipboard'
|
||||
|
||||
describe('copyToClipboard', () => {
|
||||
const originalClipboard = navigator.clipboard
|
||||
@@ -49,3 +49,93 @@ describe('copyToClipboard', () => {
|
||||
expect(execCommandFn).toHaveBeenCalledWith('copy')
|
||||
})
|
||||
})
|
||||
|
||||
describe('copyToClipboardDeferred', () => {
|
||||
it('uses navigator.clipboard.write with ClipboardItem when available', async () => {
|
||||
const mockWrite = vi.fn().mockResolvedValue(undefined)
|
||||
class MockClipboardItem {
|
||||
types: Record<string, unknown>
|
||||
constructor(types: Record<string, unknown>) {
|
||||
this.types = types
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'ClipboardItem', {
|
||||
value: MockClipboardItem,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { write: mockWrite },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
const success = await copyToClipboardDeferred(Promise.resolve('deferred text'))
|
||||
expect(success).toBe(true)
|
||||
expect(mockWrite).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('falls back to copyToClipboard when ClipboardItem is unavailable', async () => {
|
||||
const mockWriteText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(globalThis, 'ClipboardItem', {
|
||||
value: undefined,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { writeText: mockWriteText },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
const success = await copyToClipboardDeferred(Promise.resolve('fallback deferred text'))
|
||||
expect(success).toBe(true)
|
||||
expect(mockWriteText).toHaveBeenCalledWith('fallback deferred text')
|
||||
})
|
||||
})
|
||||
|
||||
describe('copyImageToClipboard', () => {
|
||||
it('returns false when clipboard API is unavailable', async () => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: undefined,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
const success = await copyImageToClipboard('http://example.com/image.png')
|
||||
expect(success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts a Promise resolving to a URL and writes to clipboard', async () => {
|
||||
const mockWrite = vi.fn().mockResolvedValue(undefined)
|
||||
class MockClipboardItem {
|
||||
types: Record<string, unknown>
|
||||
constructor(types: Record<string, unknown>) {
|
||||
this.types = types
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'ClipboardItem', {
|
||||
value: MockClipboardItem,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { write: mockWrite },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {
|
||||
return new Response(new Blob(['fake-image-bytes'], { type: 'image/webp' }))
|
||||
})
|
||||
|
||||
const success = await copyImageToClipboard(Promise.resolve('http://example.com/image.png'))
|
||||
expect(success).toBe(true)
|
||||
expect(mockWrite).toHaveBeenCalledTimes(1)
|
||||
fetchSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user