safety-check-v2.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. /** Wire values from matrix/chat/chat_server.thrift; independent of V1 scenes. */
  2. export const SAFETY_CHECK_V2_SCENE = {
  3. AssistantReply: 1,
  4. GeneratedImage: 2,
  5. AssistantThinking: 3,
  6. DesktopAssistantReply: 11,
  7. DesktopAssistantThinking: 13,
  8. AppAssistantReply: 21,
  9. AppAssistantThinking: 23,
  10. WebAssistantReply: 31,
  11. WebAssistantThinking: 33,
  12. UserQuery: 100,
  13. UserUploadImage: 101,
  14. UserUploadFile: 102,
  15. DesktopUserQuery: 110,
  16. AppUserQuery: 120,
  17. WebUserQuery: 130,
  18. UserAvatar: 200,
  19. InterfaceImage: 201,
  20. } as const;
  21. export type SafetyCheckV2Scene = (typeof SAFETY_CHECK_V2_SCENE)[keyof typeof SAFETY_CHECK_V2_SCENE];
  22. /** biz-gateway V2 HTTP verdicts; these values are not chat-server RPC actions. */
  23. export const GATEWAY_SAFETY_CHECK_V2_HTTP_ACTION = {
  24. Allow: 1,
  25. Block: 2,
  26. Replace: 3,
  27. Guide: 4,
  28. } as const;
  29. export type GatewaySafetyCheckV2HttpAction =
  30. (typeof GATEWAY_SAFETY_CHECK_V2_HTTP_ACTION)[keyof typeof GATEWAY_SAFETY_CHECK_V2_HTTP_ACTION];
  31. export type SafetyCheckV2Headers = NonNullable<RequestInit['headers']>;
  32. export type SafetyCheckV2ErrorKind = 'auth' | 'http' | 'transport' | 'response' | 'upstream';
  33. export type SafetyTransportKind = 'dns' | 'connect' | 'tls' | 'timeout' | 'aborted' | 'unknown';
  34. /** Only allowlisted categories survive; never retain exception text, URLs or causes. */
  35. export function classifySafetyTransportError(error: unknown): SafetyTransportKind {
  36. let current = error;
  37. for (let depth = 0; depth < 4 && isSafetyCheckV2Record(current); depth += 1) {
  38. const { name } = current;
  39. const code = typeof current.code === 'string' ? current.code : '';
  40. if (
  41. name === 'TimeoutError' ||
  42. [
  43. 'ETIMEDOUT',
  44. 'UND_ERR_CONNECT_TIMEOUT',
  45. 'UND_ERR_HEADERS_TIMEOUT',
  46. 'UND_ERR_BODY_TIMEOUT',
  47. ].includes(code)
  48. )
  49. return 'timeout';
  50. if (name === 'AbortError' || code === 'ABORT_ERR') return 'aborted';
  51. if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return 'dns';
  52. if (
  53. ['ECONNREFUSED', 'ECONNRESET', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_SOCKET'].includes(code)
  54. )
  55. return 'connect';
  56. if (
  57. [
  58. 'CERT_HAS_EXPIRED',
  59. 'DEPTH_ZERO_SELF_SIGNED_CERT',
  60. 'SELF_SIGNED_CERT_IN_CHAIN',
  61. 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
  62. 'ERR_TLS_CERT_ALTNAME_INVALID',
  63. 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
  64. ].includes(code)
  65. )
  66. return 'tls';
  67. current = current.cause;
  68. }
  69. return 'unknown';
  70. }
  71. /** A failed check has no verdict. Callers must handle it separately from Allow. */
  72. export class SafetyCheckV2Error extends Error {
  73. constructor(
  74. readonly kind: SafetyCheckV2ErrorKind,
  75. readonly statusCode?: number,
  76. readonly transportKind?: SafetyTransportKind,
  77. ) {
  78. super(`SafetyCheckV2 ${kind} error`);
  79. this.name = 'SafetyCheckV2Error';
  80. }
  81. }
  82. export function isSafetyCheckV2Record(value: unknown): value is Record<string, unknown> {
  83. return typeof value === 'object' && value !== null && !Array.isArray(value);
  84. }
  85. /** No retry or V1 fallback: transport failures never manufacture an Allow verdict. */
  86. export async function postSafetyCheckV2(input: {
  87. url: string;
  88. headers?: SafetyCheckV2Headers;
  89. body: unknown;
  90. fetchImpl?: typeof fetch;
  91. signal?: AbortSignal;
  92. }): Promise<Record<string, unknown>> {
  93. let response: Response;
  94. try {
  95. const headers = new Headers(input.headers);
  96. headers.set('Content-Type', 'application/json');
  97. const timeout = AbortSignal.timeout(10_000);
  98. response = await (input.fetchImpl ?? fetch)(input.url, {
  99. method: 'POST',
  100. headers,
  101. body: JSON.stringify(input.body),
  102. signal: input.signal ? AbortSignal.any([input.signal, timeout]) : timeout,
  103. redirect: 'error',
  104. });
  105. } catch (error) {
  106. throw new SafetyCheckV2Error('transport', undefined, classifySafetyTransportError(error));
  107. }
  108. if (!response.ok) {
  109. throw new SafetyCheckV2Error(
  110. response.status === 401 || response.status === 403 ? 'auth' : 'http',
  111. response.status,
  112. );
  113. }
  114. let body: unknown;
  115. try {
  116. body = await response.json();
  117. } catch (error) {
  118. const transportKind = classifySafetyTransportError(error);
  119. throw new SafetyCheckV2Error(
  120. transportKind === 'unknown' ? 'response' : 'transport',
  121. response.status,
  122. transportKind,
  123. );
  124. }
  125. if (!isSafetyCheckV2Record(body)) throw new SafetyCheckV2Error('response');
  126. return body;
  127. }