import { describe, expect, it } from 'vitest';

import {
  EMPTY_IMAGE_DATA_URL,
  isBlockedMarkdownImageUrl,
  isSafeMarkdownLinkHref,
  resolveSafeExternalMarkdownImageUrl,
} from './markdown-security';

describe('markdown image URL safety', () => {
  it.each([
    'javascript:alert(1)',
    'file:///etc/passwd',
    'blob:https://example.com/foreign',
    'data:image/svg+xml,<svg onload=alert(1)>',
    'http://example.com/insecure.png',
    '//example.com/image.png',
    '../assets/image.png',
  ])('blocks URLs that require an application resolver: %s', (url) => {
    expect(isBlockedMarkdownImageUrl(url)).toBe(true);
    expect(resolveSafeExternalMarkdownImageUrl(url)).toBe(EMPTY_IMAGE_DATA_URL);
  });

  it('allows credential-free HTTPS images', () => {
    expect(resolveSafeExternalMarkdownImageUrl('https://cdn.test/a.png')).toBe(
      'https://cdn.test/a.png',
    );
    expect(
      isBlockedMarkdownImageUrl('https://user:secret@cdn.test/a.png'),
    ).toBe(true);
  });

  it.each([
    'javascript:alert(1)',
    'file:///etc/passwd',
    'blob:https://example.com/foreign',
    'data:text/html,<script>alert(1)</script>',
    '//example.com/path',
    'https://user:secret@example.com/path',
  ])('blocks unsafe rendered links: %s', (href) => {
    expect(isSafeMarkdownLinkHref(href)).toBe(false);
  });

  it.each([
    '#section',
    'mailto:team@example.com',
    'https://example.com/path',
    'http://example.com/path',
    '../references/guide.md',
  ])('allows supported rendered links: %s', (href) => {
    expect(isSafeMarkdownLinkHref(href)).toBe(true);
  });
});
