prompt_snapshot.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. package securityaudit
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "regexp"
  8. "sort"
  9. "strings"
  10. "unicode/utf8"
  11. )
  12. var (
  13. ErrNoPromptText = errors.New("prompt audit request contains no user text")
  14. bearerPattern = regexp.MustCompile(`(?i)\bBearer\s+[A-Za-z0-9._~+\-/]+=*`)
  15. apiKeyPattern = regexp.MustCompile(`(?i)\b(sk|rk|pk|api[_-]?key|token|secret|password)[-_:=\s]+[A-Za-z0-9._~+\-/]{8,}`)
  16. canaryPattern = regexp.MustCompile(`(?i)([A-Z]+_CANARY_)[A-Za-z0-9_-]+`)
  17. emailPattern = regexp.MustCompile(`(?i)\b[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,}\b`)
  18. phonePattern = regexp.MustCompile(`(?:\+?\d[\d\s().-]{8,}\d)`)
  19. )
  20. const promptAuditPrioritySeparator = "\x00SUB2API_PROMPT_AUDIT_PRIORITY_END\x00"
  21. type promptSegment struct {
  22. text string
  23. user bool
  24. role string
  25. }
  26. func ExtractPromptSnapshot(req Request) (PromptSnapshot, error) {
  27. return extractPromptSnapshot(req, false)
  28. }
  29. // ExtractBlockingPromptSnapshot builds the narrow, low-latency blocking input
  30. // when configured. Asynchronous auditing always uses ExtractPromptSnapshot so
  31. // the complete client-controlled transcript is retained for review.
  32. func ExtractBlockingPromptSnapshot(req Request, latestTurnOnly bool) (PromptSnapshot, error) {
  33. return extractPromptSnapshot(req, latestTurnOnly)
  34. }
  35. func extractPromptSnapshot(req Request, latestTurnOnly bool) (PromptSnapshot, error) {
  36. var document any
  37. if err := json.Unmarshal(req.Body, &document); err != nil {
  38. return PromptSnapshot{}, errors.New("prompt audit request JSON is invalid")
  39. }
  40. extracted := extractProtocolSegments(req.Protocol, document)
  41. segments := normalizeSegmentsLatestUserFirst(extracted)
  42. if latestTurnOnly {
  43. segments = blockingSegmentsLatestUserAndPreviousOutput(extracted)
  44. }
  45. if len(segments) == 0 {
  46. return PromptSnapshot{}, ErrNoPromptText
  47. }
  48. scanText, metadataText := buildPrioritizedScanText(segments)
  49. digest := sha256.Sum256([]byte(metadataText))
  50. stage := strings.TrimSpace(req.Stage)
  51. if stage == "" {
  52. stage = "http"
  53. }
  54. return PromptSnapshot{
  55. RequestID: req.RequestID, UserID: req.UserID, UsernameSnapshot: req.Username,
  56. UserEmailSnapshot: req.UserEmail, APIKeyID: req.APIKeyID, APIKeyNameSnapshot: req.APIKeyName,
  57. GroupID: cloneInt64Ptr(req.GroupID), GroupName: req.GroupName, Provider: req.Provider,
  58. Endpoint: req.Endpoint, Protocol: req.Protocol, Model: req.Model,
  59. PromptHash: hex.EncodeToString(digest[:]), RedactedPreview: BuildPromptPreview(metadataText, DefaultPromptPreviewMaxRunes),
  60. FullPrompt: BuildFullPrompt(metadataText, DefaultFullPromptMaxRunes),
  61. PromptLength: utf8.RuneCountInString(metadataText), MessageCount: len(segments), Stage: stage,
  62. ScanText: scanText,
  63. }, nil
  64. }
  65. // DefaultPromptPreviewMaxRunes caps how much sanitized prompt text may be
  66. // considered before BuildPromptPreview withholds the majority for storage/UI.
  67. const DefaultPromptPreviewMaxRunes = 96
  68. // DefaultFullPromptMaxRunes caps how much unredacted prompt text is persisted
  69. // on an audit event for admin review. It is deliberately generous so realistic
  70. // prompts are kept intact while bounding per-row storage.
  71. const DefaultFullPromptMaxRunes = 65536
  72. func extractProtocolSegments(protocol string, document any) []promptSegment {
  73. root, _ := document.(map[string]any)
  74. protocol = strings.ToLower(strings.TrimSpace(protocol))
  75. switch protocol {
  76. case "openai_chat_completions", "openai_chat", "chat_completions":
  77. return extractChatLikeSegments(root)
  78. case "anthropic_messages", "claude_messages", "messages":
  79. return append(extractAnthropicSystem(root["system"]), extractMessages(root["messages"], clientInstructionRoles...)...)
  80. case "gemini", "gemini_generate_content":
  81. return extractGeminiRoot(root)
  82. case "openai_responses", "responses", "responses_websocket":
  83. if frameType := stringValue(root["type"]); frameType != "" || protocol == "responses_websocket" {
  84. if frameType != "response.create" {
  85. return nil
  86. }
  87. if input, exists := root["input"]; exists && input != nil {
  88. return append(extractInstructions(root["instructions"]), extractResponses(input)...)
  89. }
  90. if response, ok := root["response"].(map[string]any); ok {
  91. return append(extractInstructions(response["instructions"]), extractResponses(response["input"])...)
  92. }
  93. return extractInstructions(root["instructions"])
  94. }
  95. return append(extractInstructions(root["instructions"]), extractResponses(root["input"])...)
  96. case "openai_images", "grok_media", "media", "images":
  97. return userPromptSegments(extractMediaPrompts(root))
  98. default:
  99. if segments := extractChatLikeSegments(root); len(segments) > 0 {
  100. return segments
  101. }
  102. if responses := append(extractInstructions(root["instructions"]), extractResponses(root["input"])...); len(responses) > 0 {
  103. return responses
  104. }
  105. if gemini := extractGeminiRoot(root); len(gemini) > 0 {
  106. return gemini
  107. }
  108. return userPromptSegments(extractMediaPrompts(root))
  109. }
  110. }
  111. // clientInstructionRoles are roles a client may freely populate. Attackers can
  112. // place jailbreak/PII text in assistant/tool turns, so blocking audit must scan
  113. // them too—not only user/system/developer instructions.
  114. var clientInstructionRoles = []string{"user", "system", "developer", "assistant", "tool"}
  115. func extractChatLikeSegments(root map[string]any) []promptSegment {
  116. if root == nil {
  117. return nil
  118. }
  119. return extractMessages(root["messages"], clientInstructionRoles...)
  120. }
  121. func extractMessages(value any, wantedRoles ...string) []promptSegment {
  122. items, ok := value.([]any)
  123. if !ok {
  124. return nil
  125. }
  126. wanted := make(map[string]struct{}, len(wantedRoles))
  127. for _, role := range wantedRoles {
  128. wanted[strings.ToLower(strings.TrimSpace(role))] = struct{}{}
  129. }
  130. result := make([]promptSegment, 0, len(items))
  131. for _, item := range items {
  132. message, ok := item.(map[string]any)
  133. if !ok {
  134. continue
  135. }
  136. role := strings.ToLower(stringValue(message["role"]))
  137. if _, match := wanted[role]; !match {
  138. continue
  139. }
  140. texts := contentTexts(message["content"])
  141. for _, text := range texts {
  142. result = append(result, promptSegment{text: text, user: role == "user", role: role})
  143. }
  144. }
  145. return result
  146. }
  147. func extractInstructions(value any) []promptSegment {
  148. switch typed := value.(type) {
  149. case string:
  150. if text := strings.TrimSpace(typed); text != "" {
  151. return []promptSegment{{text: text, role: "system"}}
  152. }
  153. case []any:
  154. return systemPromptSegments(contentTexts(typed))
  155. case map[string]any:
  156. return systemPromptSegments(contentTexts(typed))
  157. }
  158. return nil
  159. }
  160. func extractAnthropicSystem(value any) []promptSegment {
  161. switch typed := value.(type) {
  162. case string:
  163. if text := strings.TrimSpace(typed); text != "" {
  164. return []promptSegment{{text: text, role: "system"}}
  165. }
  166. case []any:
  167. return systemPromptSegments(contentTexts(typed))
  168. case map[string]any:
  169. return systemPromptSegments(contentTexts(typed))
  170. }
  171. return nil
  172. }
  173. func extractResponses(value any) []promptSegment {
  174. switch typed := value.(type) {
  175. case string:
  176. return []promptSegment{{text: typed, user: true, role: "user"}}
  177. case []any:
  178. result := make([]promptSegment, 0, len(typed))
  179. for _, item := range typed {
  180. switch entry := item.(type) {
  181. case string:
  182. result = append(result, promptSegment{text: entry, user: true, role: "user"})
  183. case map[string]any:
  184. role := strings.ToLower(stringValue(entry["role"]))
  185. if role != "" && !isClientInstructionRole(role) {
  186. continue
  187. }
  188. if content, exists := entry["content"]; exists {
  189. for _, text := range contentTexts(content) {
  190. result = append(result, promptSegment{text: text, user: role == "" || role == "user", role: role})
  191. }
  192. } else if text := stringValue(entry["text"]); text != "" {
  193. result = append(result, promptSegment{text: text, user: role == "" || role == "user", role: role})
  194. }
  195. }
  196. }
  197. return result
  198. case map[string]any:
  199. role := strings.ToLower(stringValue(typed["role"]))
  200. if role != "" && !isClientInstructionRole(role) {
  201. return nil
  202. }
  203. return promptSegmentsForRole(contentTexts(typed["content"]), role)
  204. default:
  205. return nil
  206. }
  207. }
  208. func isClientInstructionRole(role string) bool {
  209. switch strings.ToLower(strings.TrimSpace(role)) {
  210. case "user", "system", "developer", "assistant", "tool", "model":
  211. return true
  212. default:
  213. return false
  214. }
  215. }
  216. func extractGemini(value any) []promptSegment {
  217. var contents []any
  218. switch typed := value.(type) {
  219. case []any:
  220. contents = typed
  221. case map[string]any:
  222. contents = []any{typed}
  223. default:
  224. return nil
  225. }
  226. result := make([]promptSegment, 0, len(contents))
  227. for _, item := range contents {
  228. content, ok := item.(map[string]any)
  229. if !ok {
  230. continue
  231. }
  232. role := strings.ToLower(stringValue(content["role"]))
  233. if role != "" && !isClientInstructionRole(role) {
  234. continue
  235. }
  236. parts, _ := content["parts"].([]any)
  237. for _, part := range parts {
  238. if object, ok := part.(map[string]any); ok {
  239. if text := stringValue(object["text"]); text != "" {
  240. result = append(result, promptSegment{text: text, user: role == "" || role == "user", role: role})
  241. }
  242. }
  243. }
  244. }
  245. return result
  246. }
  247. func extractGeminiRoot(root map[string]any) []promptSegment {
  248. if root == nil {
  249. return nil
  250. }
  251. result := extractGeminiSystemInstruction(root["systemInstruction"])
  252. result = append(result, extractGeminiSystemInstruction(root["system_instruction"])...)
  253. result = append(result, extractGemini(root["contents"])...)
  254. result = append(result, extractGemini(root["content"])...)
  255. result = append(result, extractGeminiInstances(root["instances"])...)
  256. if requests, ok := root["requests"].([]any); ok {
  257. for _, item := range requests {
  258. request, ok := item.(map[string]any)
  259. if !ok {
  260. continue
  261. }
  262. result = append(result, extractGeminiSystemInstruction(request["systemInstruction"])...)
  263. result = append(result, extractGeminiSystemInstruction(request["system_instruction"])...)
  264. result = append(result, extractGemini(request["contents"])...)
  265. result = append(result, extractGemini(request["content"])...)
  266. result = append(result, extractGeminiInstances(request["instances"])...)
  267. }
  268. }
  269. return result
  270. }
  271. func extractGeminiSystemInstruction(value any) []promptSegment {
  272. switch typed := value.(type) {
  273. case string:
  274. if text := strings.TrimSpace(typed); text != "" {
  275. return []promptSegment{{text: text, role: "system"}}
  276. }
  277. case map[string]any:
  278. if parts, ok := typed["parts"].([]any); ok {
  279. result := make([]promptSegment, 0, len(parts))
  280. for _, part := range parts {
  281. if object, ok := part.(map[string]any); ok {
  282. if text := stringValue(object["text"]); text != "" {
  283. result = append(result, promptSegment{text: text, role: "system"})
  284. }
  285. }
  286. }
  287. return result
  288. }
  289. return systemPromptSegments(contentTexts(typed))
  290. case []any:
  291. segments := extractGemini(typed)
  292. for index := range segments {
  293. segments[index].user = false
  294. segments[index].role = "system"
  295. }
  296. return segments
  297. }
  298. return nil
  299. }
  300. func extractGeminiInstances(value any) []promptSegment {
  301. instances, ok := value.([]any)
  302. if !ok {
  303. return nil
  304. }
  305. result := make([]promptSegment, 0, len(instances))
  306. for _, item := range instances {
  307. if instance, ok := item.(map[string]any); ok {
  308. if prompt := stringValue(instance["prompt"]); prompt != "" {
  309. result = append(result, promptSegment{text: prompt, user: true, role: "user"})
  310. }
  311. }
  312. }
  313. return result
  314. }
  315. func extractMediaPrompts(root map[string]any) []string {
  316. if root == nil {
  317. return nil
  318. }
  319. result := make([]string, 0, 4)
  320. seen := map[string]struct{}{}
  321. var walk func(any, string)
  322. walk = func(value any, key string) {
  323. switch typed := value.(type) {
  324. case map[string]any:
  325. keys := make([]string, 0, len(typed))
  326. for childKey := range typed {
  327. keys = append(keys, childKey)
  328. }
  329. sort.Strings(keys)
  330. for _, childKey := range keys {
  331. walk(typed[childKey], childKey)
  332. }
  333. case []any:
  334. for _, item := range typed {
  335. walk(item, key)
  336. }
  337. case string:
  338. if !isMediaPromptKey(key) || looksLikeMediaPayload(typed) {
  339. return
  340. }
  341. text := strings.TrimSpace(typed)
  342. if text == "" {
  343. return
  344. }
  345. if _, duplicate := seen[text]; duplicate {
  346. return
  347. }
  348. seen[text] = struct{}{}
  349. result = append(result, text)
  350. }
  351. }
  352. walk(root, "")
  353. return result
  354. }
  355. func isMediaPromptKey(key string) bool {
  356. normalized := strings.NewReplacer("_", "", "-", "").Replace(strings.ToLower(strings.TrimSpace(key)))
  357. switch normalized {
  358. case "prompt", "inputprompt", "textprompt", "description", "query", "lyrics", "negativeprompt",
  359. "positiveprompt", "gptdescriptionprompt", "prompten", "finalprompt", "finalzhprompt",
  360. "origprompt", "actualprompt", "imageprompt", "input":
  361. return true
  362. default:
  363. return false
  364. }
  365. }
  366. func looksLikeMediaPayload(value string) bool {
  367. trimmed := strings.TrimSpace(value)
  368. lower := strings.ToLower(trimmed)
  369. if strings.HasPrefix(lower, "data:image/") || strings.HasPrefix(lower, "data:video/") ||
  370. strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
  371. return true
  372. }
  373. if len(trimmed) >= 256 {
  374. for _, r := range trimmed {
  375. alphaNumeric := (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
  376. if !alphaNumeric && r != '+' && r != '/' && r != '=' {
  377. return false
  378. }
  379. }
  380. return true
  381. }
  382. return false
  383. }
  384. func contentTexts(value any) []string {
  385. switch typed := value.(type) {
  386. case string:
  387. return []string{typed}
  388. case []any:
  389. result := make([]string, 0, len(typed))
  390. for _, part := range typed {
  391. object, ok := part.(map[string]any)
  392. if !ok {
  393. continue
  394. }
  395. typeName := strings.ToLower(stringValue(object["type"]))
  396. if typeName != "" && typeName != "text" && typeName != "input_text" && typeName != "output_text" {
  397. continue
  398. }
  399. if text := stringValue(object["text"]); text != "" {
  400. result = append(result, text)
  401. }
  402. }
  403. return result
  404. case map[string]any:
  405. if text := stringValue(typed["text"]); text != "" {
  406. return []string{text}
  407. }
  408. }
  409. return nil
  410. }
  411. func normalizeSegmentsLatestUserFirst(values []promptSegment) []string {
  412. normalized := normalizedPromptSegments(values)
  413. if len(normalized) == 0 {
  414. return nil
  415. }
  416. priorityIndex := len(normalized) - 1
  417. for index := len(normalized) - 1; index >= 0; index-- {
  418. if isUserSegment(normalized[index]) {
  419. priorityIndex = index
  420. break
  421. }
  422. }
  423. result := make([]string, 0, len(normalized))
  424. result = append(result, normalized[priorityIndex].text)
  425. for index, segment := range normalized {
  426. if index != priorityIndex {
  427. result = append(result, segment.text)
  428. }
  429. }
  430. return result
  431. }
  432. // blockingSegmentsLatestUserAndPreviousOutput limits synchronous guard input to
  433. // the current user turn and the nearest preceding assistant/model turn. It is
  434. // deliberately opt-in because full transcript scanning remains stronger at
  435. // finding client-controlled content placed in older or non-user messages.
  436. func blockingSegmentsLatestUserAndPreviousOutput(values []promptSegment) []string {
  437. normalized := normalizedPromptSegments(values)
  438. latestUserStart := latestUserSegmentStart(normalized)
  439. if latestUserStart < 0 {
  440. // A request without user content cannot be narrowed safely. Preserve the
  441. // established full-snapshot behavior for unusual protocol payloads.
  442. return normalizeSegmentsLatestUserFirst(values)
  443. }
  444. latestUserEnd := latestUserStart
  445. for latestUserEnd < len(normalized) && isUserSegment(normalized[latestUserEnd]) {
  446. latestUserEnd++
  447. }
  448. currentUserText := make([]string, 0, latestUserEnd-latestUserStart)
  449. for _, segment := range normalized[latestUserStart:latestUserEnd] {
  450. currentUserText = append(currentUserText, segment.text)
  451. }
  452. // A single client turn may have several text content parts. Keep it in one
  453. // priority segment so every part of the latest input is scanned before the
  454. // prior output begins.
  455. selected := []promptSegment{{text: strings.Join(currentUserText, "\n\n"), user: true, role: "user"}}
  456. for index := latestUserStart - 1; index >= 0; index-- {
  457. if !isAssistantOutputSegment(normalized[index]) {
  458. continue
  459. }
  460. start := index
  461. for start > 0 && isAssistantOutputSegment(normalized[start-1]) {
  462. start--
  463. }
  464. selected = append(selected, normalized[start:index+1]...)
  465. break
  466. }
  467. return promptSegmentTexts(selected)
  468. }
  469. func normalizedPromptSegments(values []promptSegment) []promptSegment {
  470. normalized := make([]promptSegment, 0, len(values))
  471. for _, value := range values {
  472. value.text = strings.TrimSpace(value.text)
  473. if value.text != "" {
  474. normalized = append(normalized, value)
  475. }
  476. }
  477. return normalized
  478. }
  479. func latestUserSegmentStart(values []promptSegment) int {
  480. latest := -1
  481. for index := len(values) - 1; index >= 0; index-- {
  482. if isUserSegment(values[index]) {
  483. latest = index
  484. break
  485. }
  486. }
  487. for latest > 0 && isUserSegment(values[latest-1]) {
  488. latest--
  489. }
  490. return latest
  491. }
  492. func isUserSegment(segment promptSegment) bool {
  493. return segment.user || segment.role == "user"
  494. }
  495. func isAssistantOutputSegment(segment promptSegment) bool {
  496. return segment.role == "assistant" || segment.role == "model"
  497. }
  498. func promptSegmentTexts(values []promptSegment) []string {
  499. result := make([]string, 0, len(values))
  500. for _, value := range values {
  501. result = append(result, value.text)
  502. }
  503. return result
  504. }
  505. func buildPrioritizedScanText(segments []string) (scanText string, metadataText string) {
  506. metadataText = strings.Join(segments, "\n\n")
  507. if len(segments) <= 1 {
  508. return metadataText, metadataText
  509. }
  510. return segments[0] + promptAuditPrioritySeparator + strings.Join(segments[1:], "\n\n"), metadataText
  511. }
  512. func promptSegmentsForRole(texts []string, role string) []promptSegment {
  513. result := make([]promptSegment, 0, len(texts))
  514. for _, text := range texts {
  515. result = append(result, promptSegment{text: text, user: role == "" || role == "user", role: role})
  516. }
  517. return result
  518. }
  519. func userPromptSegments(texts []string) []promptSegment {
  520. return promptSegmentsForRole(texts, "user")
  521. }
  522. func systemPromptSegments(texts []string) []promptSegment {
  523. return promptSegmentsForRole(texts, "system")
  524. }
  525. func RedactPreview(value string, maxRunes int) string {
  526. value = bearerPattern.ReplaceAllString(value, "Bearer ***")
  527. value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string {
  528. if index := strings.IndexAny(match, ":= \t"); index >= 0 {
  529. return match[:index+1] + "***"
  530. }
  531. return "***"
  532. })
  533. value = canaryPattern.ReplaceAllString(value, "${1}***")
  534. value = emailPattern.ReplaceAllString(value, "***@***")
  535. value = phonePattern.ReplaceAllString(value, "***PHONE***")
  536. return TrimRunes(value, maxRunes)
  537. }
  538. // BuildPromptPreview stores only a short, non-recoverable head of sanitized
  539. // input. Ordinary confidential prompts must not land nearly intact in PostgreSQL
  540. // or the admin UI merely because no secret regex matched.
  541. func BuildPromptPreview(value string, maxRunes int) string {
  542. if maxRunes <= 0 {
  543. maxRunes = DefaultPromptPreviewMaxRunes
  544. }
  545. redacted := strings.TrimSpace(RedactPreview(value, maxRunes))
  546. if redacted == "" {
  547. return ""
  548. }
  549. runes := []rune(redacted)
  550. hadTruncation := strings.HasSuffix(redacted, "…")
  551. if hadTruncation && len(runes) > 0 {
  552. runes = runes[:len(runes)-1]
  553. }
  554. if len(runes) == 0 {
  555. return "***…"
  556. }
  557. // Short unlabelled secrets would otherwise leak a recoverable prefix (e.g.
  558. // 20 runes → 5 visible). Fully withhold anything below the keep threshold.
  559. const minLengthForPartialPreview = 32
  560. if len(runes) < minLengthForPartialPreview {
  561. if hadTruncation {
  562. return "***…"
  563. }
  564. return "***"
  565. }
  566. // Keep at most a quarter of the already-truncated text, and never more than
  567. // 24 runes, so the majority of prompt content is withheld by default.
  568. keep := len(runes) / 4
  569. if keep > 24 {
  570. keep = 24
  571. }
  572. preview := string(runes[:keep]) + "***"
  573. if hadTruncation || keep < len(runes) {
  574. preview += "…"
  575. }
  576. return preview
  577. }
  578. // BuildFullPrompt returns the complete prompt text for audit-event storage and
  579. // admin review, without redaction. NUL bytes are stripped because PostgreSQL
  580. // TEXT rejects them, and the result is capped at maxRunes.
  581. func BuildFullPrompt(value string, maxRunes int) string {
  582. if maxRunes <= 0 {
  583. maxRunes = DefaultFullPromptMaxRunes
  584. }
  585. value = strings.ReplaceAll(value, "\x00", "")
  586. return TrimRunes(strings.TrimSpace(value), maxRunes)
  587. }
  588. // FullPromptFromScanText reconstructs the display prompt from the worker scan
  589. // payload. buildPrioritizedScanText inserts exactly one priority separator
  590. // between the prioritized segment and the remainder, so replacing it with the
  591. // metadata joiner yields the original multi-segment text.
  592. func FullPromptFromScanText(scanText string) string {
  593. return BuildFullPrompt(strings.ReplaceAll(scanText, promptAuditPrioritySeparator, "\n\n"), DefaultFullPromptMaxRunes)
  594. }
  595. func TrimRunes(value string, limit int) string {
  596. if limit <= 0 {
  597. return ""
  598. }
  599. runes := []rune(value)
  600. if len(runes) <= limit {
  601. return value
  602. }
  603. return string(runes[:limit]) + "…"
  604. }
  605. func stringValue(value any) string {
  606. text, _ := value.(string)
  607. return strings.TrimSpace(text)
  608. }
  609. func cloneInt64Ptr(value *int64) *int64 {
  610. if value == nil {
  611. return nil
  612. }
  613. cloned := *value
  614. return &cloned
  615. }