policy.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /**
  2. * URL validation and content-type classification for the local HTTP(S) fetch
  3. * provider — the pure, network-free half. The provider's `fetch()` composes
  4. * these with transport (redirect following, byte caps, decoding).
  5. *
  6. * @module @deepseek-ai/dsh-web-fetch-http/policy
  7. */
  8. import { WebError } from '@deepseek-ai/dsh-web'
  9. /** Maximum accepted request URL length enforced by the public fetch provider. */
  10. export const WEB_FETCH_MAX_URL_LENGTH = 2048
  11. /** The body kinds this provider decodes. */
  12. export type FetchableKind = 'html' | 'text'
  13. /**
  14. * Parse a request URL and enforce network-independent transport restrictions:
  15. * HTTP(S) only and no embedded credentials. The provider applies this before
  16. * resolving a destination.
  17. *
  18. * @param input - the raw URL string from the fetch request.
  19. * @returns the parsed `URL`.
  20. */
  21. export function parseFetchUrl(input: string): URL {
  22. let url: URL
  23. try {
  24. url = new URL(input)
  25. } catch (error: unknown) {
  26. throw new WebError(`invalid URL: ${input}`, 'WEB_INVALID_URL', { cause: error })
  27. }
  28. if (url.protocol !== 'http:' && url.protocol !== 'https:') {
  29. throw new WebError(`unsupported URL scheme "${url.protocol}" (only http and https are allowed)`, 'WEB_INVALID_URL')
  30. }
  31. if (url.username.length > 0 || url.password.length > 0) {
  32. throw new WebError('credentials in URLs are not allowed', 'WEB_BLOCKED_URL')
  33. }
  34. return url
  35. }
  36. /**
  37. * Validate a request URL against the provider's complete pre-network policy:
  38. * bounded length plus the restrictions enforced by {@link parseFetchUrl}.
  39. * Public-address resolution and connection pinning run after this check.
  40. *
  41. * @param input - the raw URL string from the fetch request.
  42. * @returns the parsed `URL`.
  43. */
  44. export function validateFetchUrl(input: string): URL {
  45. if (input.length > WEB_FETCH_MAX_URL_LENGTH) {
  46. throw new WebError(`URL exceeds the maximum length of ${WEB_FETCH_MAX_URL_LENGTH}`, 'WEB_INVALID_URL')
  47. }
  48. return parseFetchUrl(input)
  49. }
  50. /**
  51. * Two URLs are same-origin when scheme, hostname, and port match. A redirect
  52. * that crosses origins is refused so each new origin requires a fresh tool call
  53. * and public-address validation.
  54. *
  55. * @param a - one of the two URLs to compare.
  56. * @param b - the other URL to compare.
  57. * @returns true when `a` and `b` share scheme, hostname, and port.
  58. */
  59. export function isSameOrigin(a: URL, b: URL): boolean {
  60. return a.protocol === b.protocol && a.hostname === b.hostname && a.port === b.port
  61. }
  62. /**
  63. * Classify a response `Content-Type` into a decodable body kind, or `undefined`
  64. * for an unsupported (e.g. binary) type. `text/html` and `application/xhtml+xml`
  65. * are `html`; other `text/*` plus a few structured text types are `text`.
  66. *
  67. * @param contentType - the raw `Content-Type` header, or `null` when the
  68. * response carries none (unsupported).
  69. * @returns the decodable kind, or `undefined` for an unsupported type.
  70. */
  71. export function classifyContentType(contentType: string | null): FetchableKind | undefined {
  72. const mime = (contentType ?? '').replace(/;.*$/s, '').trim().toLowerCase()
  73. if (mime === 'text/html' || mime === 'application/xhtml+xml') return 'html'
  74. if (mime.startsWith('text/')) return 'text'
  75. if (mime === 'application/json' || mime === 'application/xml' || mime.endsWith('+json') || mime.endsWith('+xml')) return 'text'
  76. return undefined
  77. }
  78. /**
  79. * Extract the `charset` parameter from a response `Content-Type`, lower-cased,
  80. * or `undefined` when absent. The provider feeds this label to `TextDecoder`
  81. * so a non-UTF-8 response is decoded with its declared encoding rather than
  82. * silently mangled into replacement characters.
  83. *
  84. * @param contentType - the raw `Content-Type` header, or `null` when the
  85. * response carries none.
  86. * @returns the lower-cased charset label, or `undefined` when none is declared.
  87. */
  88. export function parseCharset(contentType: string | null): string | undefined {
  89. const match = /;\s*charset\s*=\s*"?([^";]+)"?/i.exec(contentType ?? '')
  90. return match?.[1]?.trim().toLowerCase()
  91. }
  92. /**
  93. * Build a `TextDecoder` for the declared charset, falling back to UTF-8 when
  94. * none is declared. Throws {@link WebError} `WEB_UNSUPPORTED_CONTENT_TYPE` when
  95. * the label is present but not a charset `TextDecoder` recognizes — better to
  96. * fail loudly than return mojibake.
  97. *
  98. * @param charset - the declared charset label (from {@link parseCharset}), or
  99. * `undefined` to default to UTF-8.
  100. * @returns a decoder for the declared (or defaulted) encoding.
  101. */
  102. export function decoderForCharset(charset: string | undefined): TextDecoder {
  103. if (charset === undefined) return new TextDecoder('utf-8')
  104. try {
  105. return new TextDecoder(charset)
  106. } catch (error: unknown) {
  107. throw new WebError(`unsupported charset "${charset}"`, 'WEB_UNSUPPORTED_CONTENT_TYPE', { cause: error })
  108. }
  109. }