openai_opencode_session.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package service
  2. import (
  3. "net/http"
  4. "net/url"
  5. "strings"
  6. "github.com/gin-gonic/gin"
  7. )
  8. const openCodeSessionHeader = "X-OpenCode-Session"
  9. // applyOpenCodeSessionHeader forwards the caller-owned conversation identifier
  10. // only to OpenCode's official API origin. The caller applies this after account
  11. // header overrides so a per-conversation value cannot be replaced by a fixed
  12. // account-wide override.
  13. func applyOpenCodeSessionHeader(c *gin.Context, account *Account, targetURL string, headers http.Header) {
  14. if c == nil || c.Request == nil || account == nil || account.Type != AccountTypeAPIKey || headers == nil {
  15. return
  16. }
  17. parsed, err := url.Parse(targetURL)
  18. if err != nil || !strings.EqualFold(parsed.Scheme, "https") || !strings.EqualFold(parsed.Hostname(), "opencode.ai") {
  19. return
  20. }
  21. sessionID := strings.TrimSpace(c.GetHeader(openCodeSessionHeader))
  22. if sessionID == "" {
  23. return
  24. }
  25. for key := range headers {
  26. if strings.EqualFold(key, openCodeSessionHeader) {
  27. delete(headers, key)
  28. }
  29. }
  30. headers.Set(openCodeSessionHeader, sessionID)
  31. }