| 1 | import type { AiAvailabilityService } from '../../ai-availability' |
| 2 | import { lookup } from 'node:dns/promises' |
| 3 | import { Logger } from '@nestjs/common' |
| 4 | import { AppException, FileUtil, ResponseCode } from '@yikart/common' |
| 5 | import { vi } from 'vitest' |
| 6 | import { z } from 'zod' |
| 7 | import { |
| 8 | assertSafeMediaUrl, |
| 9 | errorResult, |
| 10 | formatList, |
| 11 | formatObject, |
| 12 | resolveSafeMediaUrl, |
| 13 | secondsToSrtTimestamp, |
| 14 | srtTimestampToMs, |
| 15 | successResult, |
| 16 | wrapTool, |
| 17 | } from './mcp.utils' |
| 18 | |
| 19 | vi.mock('node:dns/promises', () => ({ |
| 20 | lookup: vi.fn(), |
| 21 | })) |
| 22 | |
| 23 | describe('mcp.utils', () => { |
| 24 | describe('assertSafeMediaUrl', () => { |
| 25 | it('should accept http and https URLs', () => { |
| 26 | expect(() => assertSafeMediaUrl('http://example.com/video.mp4')).not.toThrow() |
| 27 | expect(() => assertSafeMediaUrl('https://cdn.example.com/a b/video.mp4?token=1')).not.toThrow() |
| 28 | }) |
| 29 | |
| 30 | it('should reject URLs starting with "-" to avoid ffmpeg option injection', () => { |
| 31 | expect(() => assertSafeMediaUrl('-i https://example.com/video.mp4')).toThrowError( |
| 32 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 33 | ) |
| 34 | }) |
| 35 | |
| 36 | it('should reject non-http schemes such as file://', () => { |
| 37 | expect(() => assertSafeMediaUrl('file:///etc/passwd')).toThrowError( |
| 38 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 39 | ) |
| 40 | expect(() => assertSafeMediaUrl('ftp://example.com/video.mp4')).toThrowError( |
| 41 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 42 | ) |
| 43 | }) |
| 44 | |
| 45 | it('should reject non-URL strings', () => { |
| 46 | expect(() => assertSafeMediaUrl('not a url')).toThrowError( |
| 47 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 48 | ) |
| 49 | expect(() => assertSafeMediaUrl('')).toThrowError( |
| 50 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 51 | ) |
| 52 | }) |
| 53 | }) |
| 54 | |
| 55 | describe('resolveSafeMediaUrl', () => { |
| 56 | const fetchMock = vi.fn() |
| 57 | |
| 58 | beforeEach(() => { |
| 59 | vi.mocked(lookup).mockReset() |
| 60 | fetchMock.mockReset() |
| 61 | vi.stubGlobal('fetch', fetchMock) |
| 62 | FileUtil.init({ endpoint: 'http://rustfs.local:9000', cdnEndpoint: 'http://localhost:8080/oss' }) |
| 63 | }) |
| 64 | |
| 65 | afterEach(() => { |
| 66 | vi.unstubAllGlobals() |
| 67 | }) |
| 68 | |
| 69 | function mockLookup(addresses: Record<string, { address: string, family: number }[]>) { |
| 70 | vi.mocked(lookup).mockImplementation((async (hostname: string) => addresses[hostname] ?? []) as never) |
| 71 | } |
| 72 | |
| 73 | it('should allow own storage URLs even when they point to private networks', async () => { |
| 74 | await expect(resolveSafeMediaUrl('http://localhost:8080/oss/video.mp4')).resolves.toBe('http://localhost:8080/oss/video.mp4') |
| 75 | expect(lookup).not.toHaveBeenCalled() |
| 76 | expect(fetchMock).not.toHaveBeenCalled() |
| 77 | }) |
| 78 | |
| 79 | it('should not treat storage endpoint prefixes as storage URLs', async () => { |
| 80 | mockLookup({ localhost: [{ address: '127.0.0.1', family: 4 }] }) |
| 81 | await expect(resolveSafeMediaUrl('http://localhost:8080/oss-evil/video.mp4')).rejects.toThrowError( |
| 82 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 83 | ) |
| 84 | }) |
| 85 | |
| 86 | it('should reject hosts resolving to private, loopback, link-local or mapped addresses', async () => { |
| 87 | mockLookup({ |
| 88 | '169.254.169.254': [{ address: '169.254.169.254', family: 4 }], |
| 89 | 'internal.example.com': [{ address: '10.0.0.5', family: 4 }], |
| 90 | '::1': [{ address: '::1', family: 6 }], |
| 91 | 'mapped.example.com': [{ address: '::ffff:127.0.0.1', family: 6 }], |
| 92 | }) |
| 93 | for (const url of [ |
| 94 | 'http://169.254.169.254/latest/meta-data/', |
| 95 | 'https://internal.example.com/video.mp4', |
| 96 | 'http://[::1]/video.mp4', |
| 97 | 'http://mapped.example.com/video.mp4', |
| 98 | ]) { |
| 99 | await expect(resolveSafeMediaUrl(url)).rejects.toThrowError( |
| 100 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 101 | ) |
| 102 | } |
| 103 | expect(fetchMock).not.toHaveBeenCalled() |
| 104 | }) |
| 105 | |
| 106 | it('should reject redirects to private addresses', async () => { |
| 107 | mockLookup({ |
| 108 | 'cdn.example.com': [{ address: '93.184.216.34', family: 4 }], |
| 109 | '169.254.169.254': [{ address: '169.254.169.254', family: 4 }], |
| 110 | }) |
| 111 | fetchMock.mockResolvedValueOnce(new Response(null, { |
| 112 | status: 302, |
| 113 | headers: { location: 'http://169.254.169.254/latest/meta-data/' }, |
| 114 | })) |
| 115 | |
| 116 | await expect(resolveSafeMediaUrl('https://cdn.example.com/video.mp4')).rejects.toThrowError( |
| 117 | expect.objectContaining({ code: ResponseCode.ValidationFailed }), |
| 118 | ) |
| 119 | }) |
| 120 | |
| 121 | it('should return the final public URL after following redirects', async () => { |
| 122 | mockLookup({ |
| 123 | 'cdn.example.com': [{ address: '93.184.216.34', family: 4 }], |
| 124 | 'media.example.net': [{ address: '93.184.216.35', family: 4 }], |
| 125 | }) |
| 126 | fetchMock |
| 127 | .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: 'https://media.example.net/signed.mp4?x=1' } })) |
| 128 | .mockResolvedValueOnce(new Response(null, { status: 206 })) |
| 129 | |
| 130 | await expect(resolveSafeMediaUrl('https://cdn.example.com/video.mp4')).resolves.toBe('https://media.example.net/signed.mp4?x=1') |
| 131 | }) |
| 132 | }) |
| 133 | |
| 134 | describe('srtTimestampToMs', () => { |
| 135 | it('should convert SRT timestamp to milliseconds', () => { |
| 136 | expect(srtTimestampToMs('00:01:20,460')).toBe(80460) |
| 137 | }) |
| 138 | |
| 139 | it('should handle zero timestamp', () => { |
| 140 | expect(srtTimestampToMs('00:00:00,000')).toBe(0) |
| 141 | }) |
| 142 | |
| 143 | it('should handle hours correctly', () => { |
| 144 | expect(srtTimestampToMs('01:00:00,000')).toBe(3600000) |
| 145 | }) |
| 146 | |
| 147 | it('should handle minutes correctly', () => { |
| 148 | expect(srtTimestampToMs('00:30:00,000')).toBe(1800000) |
| 149 | }) |
| 150 | |
| 151 | it('should handle seconds correctly', () => { |
| 152 | expect(srtTimestampToMs('00:00:45,000')).toBe(45000) |
| 153 | }) |
| 154 | |
| 155 | it('should handle milliseconds correctly', () => { |
| 156 | expect(srtTimestampToMs('00:00:00,500')).toBe(500) |
| 157 | }) |
| 158 | |
| 159 | it('should handle complex timestamp', () => { |
| 160 | expect(srtTimestampToMs('02:15:30,750')).toBe(8130750) |
| 161 | }) |
| 162 | }) |
| 163 | |
| 164 | describe('secondsToSrtTimestamp', () => { |
| 165 | it('should convert seconds to SRT timestamp', () => { |
| 166 | expect(secondsToSrtTimestamp(80.46)).toBe('00:01:20,460') |
| 167 | }) |
| 168 | |
| 169 | it('should handle zero seconds', () => { |
| 170 | expect(secondsToSrtTimestamp(0)).toBe('00:00:00,000') |
| 171 | }) |
| 172 | |
| 173 | it('should handle hours', () => { |
| 174 | expect(secondsToSrtTimestamp(3600)).toBe('01:00:00,000') |
| 175 | }) |
| 176 | |
| 177 | it('should handle minutes', () => { |
| 178 | expect(secondsToSrtTimestamp(1800)).toBe('00:30:00,000') |
| 179 | }) |
| 180 | |
| 181 | it('should handle complex time', () => { |
| 182 | expect(secondsToSrtTimestamp(8130.75)).toBe('02:15:30,750') |
| 183 | }) |
| 184 | |
| 185 | it('should pad numbers correctly', () => { |
| 186 | expect(secondsToSrtTimestamp(1.001)).toBe('00:00:01,001') |
| 187 | }) |
| 188 | }) |
| 189 | |
| 190 | describe('successResult', () => { |
| 191 | it('should create success result with string content', () => { |
| 192 | const result = successResult('test message') |
| 193 | expect(result.content).toEqual([{ type: 'text', text: 'test message' }]) |
| 194 | expect(result.isError).toBeUndefined() |
| 195 | }) |
| 196 | |
| 197 | it('should create success result with object content', () => { |
| 198 | const obj = { key: 'value', num: 123 } |
| 199 | const result = successResult(obj) |
| 200 | expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(obj) }]) |
| 201 | expect(result.isError).toBeUndefined() |
| 202 | }) |
| 203 | |
| 204 | it('should create success result with array content', () => { |
| 205 | const arr = ['item1', 'item2'] |
| 206 | const result = successResult(arr) |
| 207 | expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(arr) }]) |
| 208 | expect(result.isError).toBeUndefined() |
| 209 | }) |
| 210 | |
| 211 | it('should pass through content array with type property', () => { |
| 212 | const content = [{ type: 'text', text: 'hello' }] |
| 213 | const result = successResult(content) |
| 214 | expect(result.content).toEqual(content) |
| 215 | }) |
| 216 | }) |
| 217 | |
| 218 | describe('errorResult', () => { |
| 219 | it('should create error result with string message', () => { |
| 220 | const result = errorResult('error message') |
| 221 | expect(result.content).toEqual([{ type: 'text', text: 'error message' }]) |
| 222 | expect(result.isError).toBe(true) |
| 223 | }) |
| 224 | |
| 225 | it('should create error result with object message', () => { |
| 226 | const obj = { error: 'details' } |
| 227 | const result = errorResult(obj) |
| 228 | expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(obj) }]) |
| 229 | expect(result.isError).toBe(true) |
| 230 | }) |
| 231 | }) |
| 232 | |
| 233 | describe('wrapTool', () => { |
| 234 | let mockLogger: Logger |
| 235 | let mockAiAvailability: vi.Mocked<Pick<AiAvailabilityService, 'execute'>> |
| 236 | |
| 237 | beforeEach(() => { |
| 238 | mockLogger = { |
| 239 | debug: vi.fn(), |
| 240 | warn: vi.fn(), |
| 241 | error: vi.fn(), |
| 242 | fatal: vi.fn(), |
| 243 | } as unknown as Logger |
| 244 | |
| 245 | mockAiAvailability = { |
| 246 | execute: vi.fn().mockImplementation((_ctx, fn) => fn()), |
| 247 | } |
| 248 | }) |
| 249 | |
| 250 | it('should wrap tool and have correct name/description', async () => { |
| 251 | const handler = vi.fn().mockResolvedValue(successResult('success')) |
| 252 | const schema = { param: z.string() } |
| 253 | |
| 254 | const wrappedTool = wrapTool( |
| 255 | mockLogger, |
| 256 | 'testTool', |
| 257 | 'Test description', |
| 258 | schema, |
| 259 | handler, |
| 260 | mockAiAvailability as unknown as AiAvailabilityService, |
| 261 | ) |
| 262 | |
| 263 | expect(wrappedTool).toBeDefined() |
| 264 | expect(wrappedTool.name).toBe('testTool') |
| 265 | expect(wrappedTool.description).toBe('Test description') |
| 266 | }) |
| 267 | |
| 268 | it('should delegate to aiAvailability.execute on handler call', async () => { |
| 269 | const handler = vi.fn().mockResolvedValue(successResult('success')) |
| 270 | const schema = { param: z.string() } |
| 271 | |
| 272 | const wrappedTool = wrapTool( |
| 273 | mockLogger, |
| 274 | 'testTool', |
| 275 | 'Test description', |
| 276 | schema, |
| 277 | handler, |
| 278 | mockAiAvailability as unknown as AiAvailabilityService, |
| 279 | ) |
| 280 | |
| 281 | const result = await wrappedTool.handler({ param: 'test' }, {}) |
| 282 | |
| 283 | expect(result.isError).toBeUndefined() |
| 284 | expect(mockAiAvailability.execute).toHaveBeenCalledWith( |
| 285 | expect.objectContaining({ provider: 'mcp', operation: 'testTool' }), |
| 286 | expect.any(Function), |
| 287 | ) |
| 288 | }) |
| 289 | |
| 290 | it('should return errorResult for handler returning error', async () => { |
| 291 | const handler = vi.fn().mockResolvedValue(errorResult('failed')) |
| 292 | const schema = { param: z.string() } |
| 293 | |
| 294 | const wrappedTool = wrapTool( |
| 295 | mockLogger, |
| 296 | 'testTool', |
| 297 | 'Test description', |
| 298 | schema, |
| 299 | handler, |
| 300 | mockAiAvailability as unknown as AiAvailabilityService, |
| 301 | ) |
| 302 | |
| 303 | const result = await wrappedTool.handler({ param: 'test' }, {}) |
| 304 | |
| 305 | expect(result.isError).toBe(true) |
| 306 | }) |
| 307 | |
| 308 | it('should catch non-AppException errors and return errorResult with fatal log', async () => { |
| 309 | const testError = new Error('Test error') |
| 310 | const handler = vi.fn().mockRejectedValue(testError) |
| 311 | mockAiAvailability.execute.mockRejectedValue(testError) |
| 312 | const schema = { param: z.string() } |
| 313 | |
| 314 | const wrappedTool = wrapTool( |
| 315 | mockLogger, |
| 316 | 'testTool', |
| 317 | 'Test description', |
| 318 | schema, |
| 319 | handler, |
| 320 | mockAiAvailability as unknown as AiAvailabilityService, |
| 321 | ) |
| 322 | |
| 323 | const result = await wrappedTool.handler({ param: 'test' }, {}) |
| 324 | |
| 325 | expect(result.isError).toBe(true) |
| 326 | expect(result.content).toEqual([{ type: 'text', text: 'Test error' }]) |
| 327 | expect(mockLogger.fatal).toHaveBeenCalled() |
| 328 | }) |
| 329 | |
| 330 | it('should catch AppException and return errorResult without fatal log', async () => { |
| 331 | const handler = vi.fn().mockRejectedValue( |
| 332 | new AppException(ResponseCode.InvalidModel), |
| 333 | ) |
| 334 | const schema = { param: z.string() } |
| 335 | |
| 336 | const wrappedTool = wrapTool( |
| 337 | mockLogger, |
| 338 | 'testTool', |
| 339 | 'Test description', |
| 340 | schema, |
| 341 | handler, |
| 342 | mockAiAvailability as unknown as AiAvailabilityService, |
| 343 | ) |
| 344 | |
| 345 | const result = await wrappedTool.handler({ param: 'test' }, {}) |
| 346 | |
| 347 | expect(result.isError).toBe(true) |
| 348 | expect(mockLogger.fatal).not.toHaveBeenCalled() |
| 349 | expect(mockLogger.warn).toHaveBeenCalled() |
| 350 | }) |
| 351 | }) |
| 352 | |
| 353 | describe('formatObject', () => { |
| 354 | it('should format object as YAML-like string', () => { |
| 355 | const obj = { name: 'test', value: 123 } |
| 356 | const result = formatObject(obj) |
| 357 | expect(result).toBe('name: test\nvalue: 123') |
| 358 | }) |
| 359 | |
| 360 | it('should filter out timestamp fields', () => { |
| 361 | const obj = { |
| 362 | name: 'test', |
| 363 | createdAt: new Date(), |
| 364 | updatedAt: new Date(), |
| 365 | deletedAt: null, |
| 366 | __v: 0, |
| 367 | _id: 'abc123', |
| 368 | } |
| 369 | const result = formatObject(obj) |
| 370 | expect(result).toBe('name: test') |
| 371 | }) |
| 372 | |
| 373 | it('should handle nested objects', () => { |
| 374 | const obj = { name: 'test', nested: { key: 'value' } } |
| 375 | const result = formatObject(obj) |
| 376 | expect(result).toContain('name: test') |
| 377 | expect(result).toContain('nested: {"key":"value"}') |
| 378 | }) |
| 379 | |
| 380 | it('should handle arrays', () => { |
| 381 | const obj = { name: 'test', items: ['a', 'b', 'c'] } |
| 382 | const result = formatObject(obj) |
| 383 | expect(result).toContain('name: test') |
| 384 | expect(result).toContain('items: a, b, c') |
| 385 | }) |
| 386 | |
| 387 | it('should skip null and undefined values', () => { |
| 388 | const obj = { name: 'test', empty: null, missing: undefined } |
| 389 | const result = formatObject(obj) |
| 390 | expect(result).toBe('name: test') |
| 391 | }) |
| 392 | |
| 393 | it('should return empty string for null input', () => { |
| 394 | const result = formatObject(null as unknown as Record<string, unknown>) |
| 395 | expect(result).toBe('') |
| 396 | }) |
| 397 | |
| 398 | it('should filter by keepFields when provided', () => { |
| 399 | const obj = { name: 'test', value: 123, extra: 'ignored' } |
| 400 | const result = formatObject(obj, ['name', 'value']) |
| 401 | expect(result).toBe('name: test\nvalue: 123') |
| 402 | }) |
| 403 | }) |
| 404 | |
| 405 | describe('formatList', () => { |
| 406 | it('should format list with default formatter', () => { |
| 407 | const list = ['item1', 'item2', 'item3'] |
| 408 | const result = formatList(list) |
| 409 | expect(result).toBe('Total 3:\n1. item1\n2. item2\n3. item3') |
| 410 | }) |
| 411 | |
| 412 | it('should format list with custom formatter', () => { |
| 413 | const list = [{ name: 'a' }, { name: 'b' }] |
| 414 | const result = formatList(list, item => item.name) |
| 415 | expect(result).toBe('Total 2:\n1. a\n2. b') |
| 416 | }) |
| 417 | |
| 418 | it('should return "No data" for empty list', () => { |
| 419 | const result = formatList([]) |
| 420 | expect(result).toBe('No data') |
| 421 | }) |
| 422 | |
| 423 | it('should return "No data" for null list', () => { |
| 424 | const result = formatList(null as unknown as unknown[]) |
| 425 | expect(result).toBe('No data') |
| 426 | }) |
| 427 | |
| 428 | it('should pass index to formatter', () => { |
| 429 | const list = ['a', 'b'] |
| 430 | const result = formatList(list, (item, index) => `${index}: ${item}`) |
| 431 | expect(result).toBe('Total 2:\n1. 0: a\n2. 1: b') |
| 432 | }) |
| 433 | }) |
| 434 | }) |
| 435 |