import { describe, expect, test, vi, beforeEach } from 'vitest' import { Hono } from 'hono' import shareRoute from './share' import publicShareRoute from './public-share' import { authMiddleware } from './middleware/auth' import { shareService } from '@shumai/core/src/share/share' import { shareActivityService } from '@shumai/core/src/share/share-activity' import { HTTPException } from 'hono/http-exception' import { assetService } from '@shumai/core/src/asset/asset' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { ShareLinkPasswordInvalidError, ShareLinkExpiredError, ShareLinkNotFoundError, } 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' import { s3Service } from '@shumai/core/src/s3/s3' vi.mock('./middleware/auth', () => ({ // eslint-disable-next-line @typescript-eslint/no-explicit-any authMiddleware: async (c: any, next: any) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any c.set('user', { id: 'user1', name: 'Test User' } as any) await next() }, })) vi.mock('@shumai/core/src/authz/authz', () => ({ authzService: { hasPermission: vi.fn().mockResolvedValue(undefined), }, Permission: { Read: 'Read', Edit: 'Edit', Admin: 'Admin', }, ResourceType: { Project: 'project', Share: 'share', Asset: 'asset', }, })) vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ auditLogService: { logAction: vi.fn().mockResolvedValue({}), }, })) vi.mock('@shumai/core/src/project/project', () => ({ projectService: { getProjectTeam: vi.fn().mockResolvedValue('t1'), }, })) function watermarkMediaInfo(overrides: Partial = {}): PrismaJson.MediaInfo { return { duration: 1, filesize: 100, frames: 30, proxyType: 'video', imageTranscodes: [], videoTranscodes: [], finishedAt: new Date().toISOString(), metadata: { originalHeight: 360, originalWidth: 640, hasAudio: false, duration: 1, bitRate: 0, frameRate: 30, totalFrames: 30, startTimecode: '00:00:00:00', format: {}, }, original: { key: 'files/orig.mp4', filesizeInBytes: 100, codec: '', }, ...overrides, } } describe('Share API', () => { const app = new Hono() .route('/', publicShareRoute) .use('*', authMiddleware) .route('/', shareRoute) beforeEach(() => { vi.restoreAllMocks() vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) }) // Public Routes describe('POST /shares/:shareId/views', () => { test('attributes an authorized asset view to a verified guest', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ rootFolderId: 'folder1', } as Awaited>) vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('asset1') vi.spyOn(userService, 'getUserById').mockResolvedValue({ id: 'guest1', guestEmail: 'alice@example.com', } as Awaited>) const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined) const token = createGuestToken({ userId: 'guest1', shareId: 'share1' }) const res = await app.request('/shares/share1/views', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-share-password': 'pass', Cookie: `shumai_guest_share1=${token}`, }, body: JSON.stringify({ assetId: 'alias1', isShareEntry: true }), }) expect(res.status).toBe(204) expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'alias1', 'pass') expect(record).toHaveBeenCalledWith('share1', { assetId: 'asset1', isShareEntry: true, userId: 'guest1', }) }) test('a rejected view leaves the counter and history alone', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( new ShareLinkPasswordInvalidError('Incorrect password'), ) const record = vi.spyOn(shareActivityService, 'recordView').mockResolvedValue(undefined) const res = await app.request('/shares/share1/views', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}', }) expect(res.status).toBe(401) expect(record).not.toHaveBeenCalled() }) }) describe('GET /shares/:shareId/activities', () => { test('returns the requested page to a share reader', async () => { const list = vi.spyOn(shareActivityService, 'list').mockResolvedValue({ data: [], pageInfo: { total: 0 }, }) const res = await app.request('/shares/share1/activities?first=20') expect(res.status).toBe(200) expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } }) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ id: 'share1', permission: Permission.Read, type: ResourceType.Share, }), ) expect(list).toHaveBeenCalledWith('share1', { first: 20 }) }) test('denies access to activity without share read permission', async () => { vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403)) const list = vi.spyOn(shareActivityService, 'list') const res = await app.request('/shares/share1/activities') expect(res.status).toBe(403) expect(list).not.toHaveBeenCalled() }) }) describe('GET /shares/:shareId/info', () => { test('Success', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', name: 'Public Share', isDisabled: false, allowDownload: false, isExpired: false, views: 0, lastViewedAt: null, hasPassword: true, rootFolderId: 'folder1', projectId: 'project1', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', name: 'Public Share', rootFolderId: 'folder1', // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) const res = await app.request('/shares/share1/info', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.name).toBe('Public Share') expect(body.hasPassword).toBe(true) expect(body.allowDownload).toBe(false) expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass') }) test('Unauthorized', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', name: 'Public Share', isDisabled: false, allowDownload: false, isExpired: false, views: 0, lastViewedAt: null, hasPassword: true, rootFolderId: 'folder1', projectId: 'project1', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( new ShareLinkPasswordInvalidError('Invalid password for share link'), ) const res = await app.request('/shares/share1/info', { method: 'GET', headers: { 'x-share-password': 'wrong' }, }) expect(res.status).toBe(401) const body = await res.json() expect(body.error).toBe('Unauthorized') }) test('Expired/Disabled', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', name: 'Public Share', isDisabled: false, allowDownload: false, isExpired: false, views: 0, lastViewedAt: null, hasPassword: true, rootFolderId: 'folder1', projectId: 'project1', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( new ShareLinkExpiredError('Share link has expired'), ) const res = await app.request('/shares/share1/info', { method: 'GET', }) expect(res.status).toBe(403) const body = await res.json() expect(body.error).toBe('Share link has expired') }) }) describe('GET /shares/:shareId/folders/:folderId/children', () => { test('Success', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', name: 'My Share', isDisabled: false, allowDownload: false, rootFolderId: 'folder1', projectId: 'project1', password: null, expireAt: null, defaultSortOrder: 'name:asc', fieldVisibility: null, createdAt: new Date(), updatedAt: new Date(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'listChildren').mockResolvedValue({ data: [], pageInfo: { total: 0, cursor: undefined }, }) const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass') expect(assetService.listChildren).toHaveBeenCalledWith( expect.objectContaining({ assetId: 'folder1', assetType: 'file', sort: 'name', order: 'asc', }), { excludeInternalComments: true }, ) }) test('applies per-file watermark proxies when watermark enabled', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', name: 'My Share', isDisabled: false, allowDownload: false, rootFolderId: 'folder1', projectId: 'project1', password: null, expireAt: null, watermarkConfigId: 'cfg1', // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'listChildren').mockResolvedValue({ data: [ { id: 'video-ready', name: 'a.mp4', sizeByte: 1, fileCount: 0, type: 'file', status: 'processed', proxyType: 'video', media: { proxyType: 'video', videoTranscodes: [ { id: 'orig', url: 'u', key: 'files/orig.mp4', width: 640, height: 360, size: 1, }, ], imageTranscodes: [], original: { key: 'files/orig.mp4' }, }, }, { id: 'video-pending', name: 'b.mp4', sizeByte: 1, fileCount: 0, type: 'file', status: 'processed', proxyType: 'video', media: { proxyType: 'video', videoTranscodes: [ { id: 'orig', url: 'u', key: 'files/orig.mp4', width: 640, height: 360, size: 1, }, ], imageTranscodes: [], isHls: true, hls: { key: 'files/orig-hls/master.m3u8', url: '/api/files/video-pending/m3u8/master.m3u8', resolutions: [{ resolution: '1080p', width: 1920, height: 1080 }], }, original: { key: 'files/orig.mp4' }, }, }, { id: 'doc', name: 'c.pdf', sizeByte: 1, fileCount: 0, type: 'file', status: 'processed', proxyType: 'pdf', media: { proxyType: 'pdf', pdfTranscode: { url: 'u', key: 'files/doc.pdf' }, videoTranscodes: [], imageTranscodes: [], original: { key: 'files/doc.pdf' }, }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any ] as any, pageInfo: { total: 3, cursor: undefined }, }) vi.spyOn(assetService, 'resolveTargetAssetId').mockImplementation(async (id) => id) vi.spyOn(s3Service, 'presign').mockResolvedValue('http://s3/presigned') vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue( new Map([ [ 'video-ready', watermarkMediaInfo({ videoTranscodes: [{ key: 'files/wm-a.mp4', width: 640, height: 360 }], }), ], ]), ) const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() // Ready item → watermarked proxy expect(body.data[0].media.videoTranscodes).toEqual([ { id: 'files/wm-a.mp4', url: 'http://s3/presigned', key: 'files/wm-a.mp4', width: 640, height: 360, size: 0, }, ]) // Pending item → original transcodes emptied and HLS cleared expect(body.data[1].media.videoTranscodes).toEqual([]) expect(body.data[1].media.imageTranscodes).toEqual([]) expect(body.data[1].media.isHls).toBe(false) expect(body.data[1].media.hls).toBeUndefined() // Non-media item → untouched expect(body.data[2].media.pdfTranscode).toEqual({ url: 'u', key: 'files/doc.pdf' }) }) }) describe('public share field values', () => { const shareLinkWithFields = { id: 'share1', name: 'My Share', isDisabled: false, allowDownload: false, rootFolderId: 'folder1', projectId: 'project1', password: null, expireAt: null, watermarkConfigId: null, fieldVisibility: { status: true, internalNote: false }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const assetWithFields = { id: 'file1', name: 'a.png', sizeByte: 1, fileCount: 0, type: 'file', status: 'processed', proxyType: 'pdf', fieldValues: [ { fieldId: 'status', value: 'Approved' }, { fieldId: 'internalNote', value: 'not for guests' }, { fieldId: 'rating', value: 3 }, ], // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any test('children only include field values visible on the share', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields) vi.spyOn(assetService, 'listChildren').mockResolvedValue({ data: [assetWithFields], pageInfo: { total: 1, cursor: undefined }, }) const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') expect(res.status).toBe(200) const body = await res.json() expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) }) test('children with watermark only include field values visible on the share', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ ...shareLinkWithFields, watermarkConfigId: 'cfg1', }) vi.spyOn(assetService, 'listChildren').mockResolvedValue({ data: [assetWithFields], pageInfo: { total: 1, cursor: undefined }, }) vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementation(async (id) => id) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') expect(res.status).toBe(200) const body = await res.json() expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) }) test('children include no field values when the share shows no fields', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ ...shareLinkWithFields, fieldVisibility: null, }) vi.spyOn(assetService, 'listChildren').mockResolvedValue({ data: [assetWithFields], pageInfo: { total: 1, cursor: undefined }, }) const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') expect(res.status).toBe(200) const body = await res.json() expect(body.data[0].fieldValues).toEqual([]) }) test('file detail only includes field values visible on the share', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields) vi.spyOn(assetService, 'getAsset').mockResolvedValue(assetWithFields) const res = await app.request('/shares/share1/files/file1') expect(res.status).toBe(200) const body = await res.json() expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) }) test('file detail with watermark only includes field values visible on the share', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ ...shareLinkWithFields, watermarkConfigId: 'cfg1', }) vi.spyOn(assetService, 'getAsset').mockResolvedValue({ ...assetWithFields, proxyType: 'image', media: { proxyType: 'image', videoTranscodes: [], imageTranscodes: [] }, }) vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file1') vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) const res = await app.request('/shares/share1/files/file1') expect(res.status).toBe(200) const body = await res.json() expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) }) }) describe('GET /shares/:shareId/files/:fileId', () => { const shareLinkWithWatermark = { id: 'share1', name: 'My Share', isDisabled: false, allowDownload: false, rootFolderId: 'folder1', projectId: 'project1', password: null, expireAt: null, watermarkConfigId: 'cfg1', // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const videoAsset = { id: 'file1', name: 'video.mp4', sizeByte: 1024, fileCount: 0, type: 'file', status: 'processed', proxyType: 'video', media: { proxyType: 'video', videoTranscodes: [ { id: 'orig-360p', url: 'http://s3/original-360p', key: 'files/original-360p.mp4', width: 640, height: 360, size: 100, }, ], imageTranscodes: [], original: { key: 'files/original.mp4' }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any beforeEach(() => { vi.spyOn(assetService, 'getAsset').mockResolvedValue(videoAsset) vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1') vi.spyOn(s3Service, 'presign').mockResolvedValue('http://s3/presigned') }) test('serves watermarked transcodes when watermark enabled and completed', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue( new Map([ [ 'file1', watermarkMediaInfo({ videoTranscodes: [{ key: 'files/watermarked-360p.mp4', width: 640, height: 360 }], }), ], ]), ) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([ { id: 'files/watermarked-360p.mp4', url: 'http://s3/presigned', key: 'files/watermarked-360p.mp4', width: 640, height: 360, size: 0, }, ]) expect(body.media.imageTranscodes).toEqual([]) }) test('serves watermarked transcodes with hdr flags preserved when watermark enabled and completed', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue( new Map([ [ 'file1', watermarkMediaInfo({ videoTranscodes: [ { key: 'files/watermarked-1080p.mp4', width: 1920, height: 1080, hdr: false }, { key: 'files/watermarked-1080p-hdr.mp4', width: 1920, height: 1080, hdr: true }, ], }), ], ]), ) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([ { id: 'files/watermarked-1080p.mp4', url: 'http://s3/presigned', key: 'files/watermarked-1080p.mp4', width: 1920, height: 1080, size: 0, hdr: false, }, { id: 'files/watermarked-1080p-hdr.mp4', url: 'http://s3/presigned', key: 'files/watermarked-1080p-hdr.mp4', width: 1920, height: 1080, size: 0, hdr: true, }, ]) }) test('serves empty transcode arrays while watermark transcoding is in flight', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([]) expect(body.media.imageTranscodes).toEqual([]) }) test('clears HLS fields while watermark transcoding is in flight', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) vi.spyOn(assetService, 'getAsset').mockResolvedValue({ ...videoAsset, media: { ...videoAsset.media, isHls: true, hls: { key: 'files/hls/master.m3u8', url: '/api/files/file1/m3u8/master.m3u8', resolutions: [{ resolution: '1080p', width: 1920, height: 1080 }], }, }, }) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.isHls).toBe(false) expect(body.media.hls).toBeUndefined() }) test('serves watermarked turntable video for a 3d asset when watermark enabled and completed', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) const asset3d = { id: 'file1', name: 'model.glb', sizeByte: 1024, fileCount: 0, type: 'file', status: 'processed', proxyType: '3d', media: { proxyType: '3d', videoPreview: { url: 'http://s3/unwatermarked-turntable.mp4', key: 'files/turntable.mp4', }, videoTranscodes: [ { id: 'orig-turntable', url: 'http://s3/unwatermarked-turntable.mp4', key: 'files/turntable.mp4', width: 1080, height: 1080, }, ], original: { key: 'files/model.glb' }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue( new Map([ [ 'file1', watermarkMediaInfo({ proxyType: '3d', videoTranscodes: [ { key: 'files/watermarked-turntable.mp4', width: 1080, height: 1080, resolution: '1080p', }, ], videoPreview: { key: 'files/watermarked-turntable.mp4', width: 1080, height: 1080 }, }), ], ]), ) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([ { id: 'files/watermarked-turntable.mp4', url: 'http://s3/presigned', key: 'files/watermarked-turntable.mp4', width: 1080, height: 1080, size: 0, resolution: '1080p', }, ]) expect(body.media.videoPreview?.url).toBe('http://s3/presigned') expect(body.media.videoPreview?.key).toBe('files/watermarked-turntable.mp4') }) test('strips videoPreview url and serves empty videoTranscodes for a 3d asset while watermark is in flight', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) const asset3d = { id: 'file1', name: 'model.glb', sizeByte: 1024, fileCount: 0, type: 'file', status: 'processed', proxyType: '3d', media: { proxyType: '3d', videoPreview: { url: 'http://s3/unwatermarked-turntable.mp4', key: 'files/turntable.mp4', }, videoTranscodes: [ { id: 'orig-turntable', url: 'http://s3/unwatermarked-turntable.mp4', key: 'files/turntable.mp4', width: 1080, height: 1080, }, ], original: { key: 'files/model.glb' }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d) vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([]) expect(body.media.videoPreview?.url).toBeUndefined() }) test('leaves non-video/image media untouched when watermark enabled', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark) vi.spyOn(assetService, 'getAsset').mockResolvedValue({ id: 'file1', name: 'doc.pdf', sizeByte: 1024, fileCount: 0, type: 'file', status: 'processed', proxyType: 'pdf', media: { proxyType: 'pdf', pdfTranscode: { url: 'http://s3/doc', key: 'files/doc.pdf' }, videoTranscodes: [], imageTranscodes: [], original: { key: 'files/doc.pdf' }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) const resolveSpy = vi.spyOn(assetService, 'resolveTargetAssetId') const wfSpy = vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap') const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.pdfTranscode).toEqual({ url: 'http://s3/doc', key: 'files/doc.pdf' }) expect(resolveSpy).not.toHaveBeenCalled() expect(wfSpy).not.toHaveBeenCalled() }) test('serves original media unchanged when watermark disabled', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', name: 'My Share', isDisabled: false, allowDownload: false, rootFolderId: 'folder1', projectId: 'project1', password: null, expireAt: null, watermarkConfigId: null, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) const wfSpy = vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap') const res = await app.request('/shares/share1/files/file1', { method: 'GET', headers: { 'x-share-password': 'pass' }, }) expect(res.status).toBe(200) const body = await res.json() expect(body.media.videoTranscodes).toEqual([ { id: 'orig-360p', url: 'http://s3/original-360p', key: 'files/original-360p.mp4', width: 640, height: 360, size: 100, }, ]) expect(wfSpy).not.toHaveBeenCalled() }) }) // Protected Routes describe('POST /projects/:projectId/shares', () => { test('Success', async () => { vi.spyOn(shareService, 'createShareLink').mockResolvedValue({ id: 'share1', name: 'test-share', isDisabled: false, allowDownload: false, rootFolderId: 'root1', projectId: 'project1', isExpired: false, views: 0, lastViewedAt: null, hasPassword: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) const res = await app.request('/projects/project1/shares', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'My Share' }), }) expect(res.status).toBe(200) const body = await res.json() expect(body.id).toBe('share1') expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Project, id: 'project1', permission: Permission.Edit, }), ) expect(shareService.createShareLink).toHaveBeenCalledWith( 'project1', { name: 'My Share' }, 'user1', ) expect(auditLogService.logAction).toHaveBeenCalledWith({ action: 'share_create', teamId: 't1', userId: 'user1', projectId: 'project1', itemId: 'share1', }) }) test('Passes allowDownload to service', async () => { vi.spyOn(shareService, 'createShareLink').mockResolvedValue({ id: 'share1', name: 'test-share', isDisabled: false, allowDownload: false, rootFolderId: 'root1', projectId: 'project1', isExpired: false, views: 0, lastViewedAt: null, hasPassword: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) const res = await app.request('/projects/project1/shares', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'My Share', allowDownload: false }), }) expect(res.status).toBe(200) expect(shareService.createShareLink).toHaveBeenCalledWith( 'project1', { name: 'My Share', allowDownload: false }, 'user1', ) }) }) describe('GET /projects/:projectId/shares', () => { test('Success', async () => { vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({ data: [], pageInfo: { total: 0, cursor: undefined }, }) const res = await app.request('/projects/project1/shares', { method: 'GET', }) expect(res.status).toBe(200) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Project, id: 'project1', permission: Permission.Read, }), ) expect(shareService.listProjectShareLinks).toHaveBeenCalledWith( expect.objectContaining({ projectId: 'project1', }), ) }) }) describe('GET /shares/:shareId', () => { test('Success', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', name: 'test-share', isDisabled: false, allowDownload: false, rootFolderId: 'root1', projectId: 'project1', isExpired: false, views: 0, lastViewedAt: null, hasPassword: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) const res = await app.request('/shares/share1', { method: 'GET', }) expect(res.status).toBe(200) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Share, id: 'share1', permission: Permission.Read, }), ) expect(shareService.getShareLink).toHaveBeenCalledWith('share1') }) }) describe('POST /shares/:shareId/assets', () => { test('Success', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', name: 'test-share', isDisabled: false, allowDownload: false, rootFolderId: 'root1', projectId: 'project1', isExpired: false, views: 0, lastViewedAt: null, hasPassword: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1) const res = await app.request('/shares/share1/assets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ assetIds: ['asset1'] }), }) expect(res.status).toBe(200) const body = await res.json() expect(body.addedCount).toBe(1) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Share, id: 'share1', permission: Permission.Edit, }), ) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Asset, id: 'asset1', permission: Permission.Read, }), ) expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] }) }) }) describe('Watermark API', () => { test('PUT /shares/:shareId/watermark success', async () => { const { watermarkService } = await import('@shumai/core/src/watermark/watermark') vi.spyOn(watermarkService, 'updateShareLinkWatermark').mockResolvedValue({ id: 'share1', name: 'test-share', isDisabled: false, allowDownload: false, rootFolderId: 'root1', projectId: 'project1', isExpired: false, views: 0, lastViewedAt: null, hasPassword: false, watermarkStatus: 'processing', watermarkConfigId: 'cfg1', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }) const res = await app.request('/shares/share1/watermark', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: true, config: { blocks: [ { id: 'b1', type: 'text', x: 0.5, y: 0.5, opacity: 0.5, rotation: 0, text: 'TEST', size: 0.1, color: '#FFF', }, ], }, }), }) expect(res.status).toBe(200) const body = await res.json() expect(body.watermarkStatus).toBe('processing') }) test('PUT /shares/:shareId/watermark conflict 409', async () => { const { watermarkService } = await import('@shumai/core/src/watermark/watermark') const { ShareLinkWatermarkProcessingError } = await import('@shumai/core/src/share/errors') vi.spyOn(watermarkService, 'updateShareLinkWatermark').mockRejectedValue( new ShareLinkWatermarkProcessingError(), ) const res = await app.request('/shares/share1/watermark', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: false }), }) expect(res.status).toBe(409) const body = await res.json() expect(body.error).toBe('Watermark transcoding is currently in progress') }) test('PUT /shares/:shareId/watermark without config when enabled returns 400', async () => { const res = await app.request('/shares/share1/watermark', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: true }), }) expect(res.status).toBe(400) }) test('GET /shares/:shareId/watermark success', async () => { const { watermarkService } = await import('@shumai/core/src/watermark/watermark') vi.spyOn(watermarkService, 'getShareLinkWatermark').mockResolvedValue({ watermarkStatus: 'ready', watermarkConfig: { id: 'cfg1', config: { blocks: [] }, hash: 'h1', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }, }) const res = await app.request('/shares/share1/watermark', { method: 'GET', }) expect(res.status).toBe(200) const body = await res.json() expect(body.watermarkStatus).toBe('ready') expect(body.watermarkConfig.hash).toBe('h1') }) }) describe('POST /shares/:shareId/files/:fileId/download-url', () => { test('requires share access to the concrete asset selected for download', async () => { vi.spyOn(shareService, 'verifyPublicAccess') .mockResolvedValueOnce({ allowDownload: true, } as Awaited>) .mockRejectedValueOnce(new ShareLinkNotFoundError('Asset is not shared')) vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'unshared', }) const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined) const res = await app.request('/shares/share1/files/file1/download-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'files/download.png' }), }) expect(res.status).toBe(404) expect(await res.json()).toEqual({ error: 'Asset is not shared' }) expect(record).not.toHaveBeenCalled() }) test.each(['prepare', 'clipboard'])( 'does not count a URL requested for %s', async (purpose) => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ allowDownload: true, } as Awaited>) vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1', }) const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined) const res = await app.request('/shares/share1/files/symlink1/download-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'files/target1/fly.png', purpose }), }) expect(res.status).toBe(200) expect(record).not.toHaveBeenCalled() }, ) test('Success for symlink asset in share', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ allowDownload: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'getDownloadUrlWithAsset').mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1', }) const record = vi.spyOn(shareActivityService, 'recordEvent').mockResolvedValue(undefined) const res = await app.request('/shares/share1/files/symlink1/download-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'files/target1/fly.png' }), }) expect(res.status).toBe(200) const body = await res.json() expect(body.url).toBe('https://s3.example.com/download') expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined) expect(assetService.getDownloadUrlWithAsset).toHaveBeenCalledWith( 'symlink1', 'files/target1/fly.png', ) expect(record).toHaveBeenCalledWith('share1', { kind: 'asset_downloaded', assetId: 'target1', userId: undefined, }) }) test('Rejects when allowDownload is disabled', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', name: 'No Download', allowDownload: false, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) const getDownloadUrlSpy = vi .spyOn(assetService, 'getDownloadUrlWithAsset') .mockResolvedValue({ url: 'https://s3.example.com/download', assetId: 'target1' }) const res = await app.request('/shares/share1/files/symlink1/download-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'files/target1/fly.png' }), }) expect(res.status).toBe(403) const body = await res.json() expect(body.error).toBe('Download is disabled for this share link') expect(getDownloadUrlSpy).not.toHaveBeenCalled() }) }) describe('GET /shares/:shareId/files/:fileId/m3u8 routes', () => { test('returns master playlist with query password preserved in variant URLs', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', watermarkConfigId: null, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'getHlsMasterPlaylist').mockResolvedValue( '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=4628000\n1080p/index.m3u8\n', ) const res = await app.request('/shares/share1/files/file1/m3u8/master.m3u8?p=secret123') expect(res.status).toBe(200) 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('share1', 'file1', 'secret123') expect(assetService.getHlsMasterPlaylist).toHaveBeenCalledWith({ assetId: 'file1', watermarkConfigId: null, }) }) test('returns variant playlist with rewritten segment URLs', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', watermarkConfigId: 'wm1', // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'getHlsVariantPlaylist').mockResolvedValue( '#EXTM3U\n#EXT-X-MAP:URI="http://presigned/init.mp4"\nhttp://presigned/seg0.m4s\n', ) const res = await app.request('/shares/share1/files/file1/m3u8/1080p/index.m3u8') expect(res.status).toBe(200) expect(res.headers.get('content-type')).toContain('application/vnd.apple.mpegurl') const text = await res.text() expect(text).toContain('http://presigned/init.mp4') expect(assetService.getHlsVariantPlaylist).toHaveBeenCalledWith({ assetId: 'file1', resolution: '1080p', watermarkConfigId: 'wm1', }) }) test('returns 401 when password is invalid', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( new ShareLinkPasswordInvalidError('Invalid password'), ) const res = await app.request('/shares/share1/files/file1/m3u8/master.m3u8?p=wrong') expect(res.status).toBe(401) const body = await res.json() expect(body.error).toBe('Unauthorized') }) test('resolves latest version id when fileId is a symlink to a version stack', async () => { vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', watermarkConfigId: null, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('child-version-file-id') vi.spyOn(assetService, 'getHlsMasterPlaylist').mockResolvedValue( '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=4628000\n1080p/index.m3u8\n', ) const res = await app.request('/shares/share1/files/symlink1/m3u8/master.m3u8') expect(res.status).toBe(200) expect(assetService.resolveLatestVersionId).toHaveBeenCalledWith('symlink1') expect(assetService.getHlsMasterPlaylist).toHaveBeenCalledWith({ assetId: 'child-version-file-id', watermarkConfigId: null, }) }) }) 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>) vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', } as unknown as Awaited>) 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>) vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', } as unknown as Awaited>) vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1') vi.spyOn(userService, 'getUserById').mockResolvedValue({ id: 'guest1', name: 'Guest Alice', guestEmail: 'alice@guest.com', } as unknown as Awaited>) vi.spyOn(assetService, 'createComment').mockResolvedValue({ id: 'comm1', message: 'hello from alice', } as unknown as Awaited>) vi.spyOn(notificationService, 'create').mockResolvedValue( undefined as unknown as Awaited>, ) 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', }), { shareLinkId: 'share1' }, ) }) test('rejects guest cookie bound to a different shareId', async () => { vi.spyOn(shareService, 'getShareLink').mockResolvedValue({ id: 'share1', projectId: 'p1', } as unknown as Awaited>) vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ id: 'share1', } as unknown as Awaited>) 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) }) }) })