|
| 1 | +package openrouter |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "strconv" |
| 10 | + |
| 11 | + regexp "github.com/wasilibs/go-re2" |
| 12 | + |
| 13 | + "github.com/trufflesecurity/trufflehog/v3/pkg/common" |
| 14 | + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" |
| 15 | + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" |
| 16 | +) |
| 17 | + |
| 18 | +type Scanner struct { |
| 19 | + client *http.Client |
| 20 | +} |
| 21 | + |
| 22 | +// Ensure the Scanner satisfies the interface at compile time. |
| 23 | +var _ detectors.Detector = (*Scanner)(nil) |
| 24 | + |
| 25 | +var ( |
| 26 | + defaultClient = common.SaneHttpClient() |
| 27 | + |
| 28 | + keyPat = regexp.MustCompile(`\b(sk-or-v1-[0-9a-f]{64})\b`) |
| 29 | +) |
| 30 | + |
| 31 | +// Keywords are used for efficiently pre-filtering chunks. |
| 32 | +// Use identifiers in the secret preferably, or the provider name. |
| 33 | +func (s Scanner) Keywords() []string { |
| 34 | + return []string{"sk-or-v1-"} |
| 35 | +} |
| 36 | + |
| 37 | +// FromData will find and optionally verify OpenRouter secrets in a given set of bytes. |
| 38 | +func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) { |
| 39 | + dataStr := string(data) |
| 40 | + |
| 41 | + uniqueMatches := make(map[string]struct{}) |
| 42 | + for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) { |
| 43 | + uniqueMatches[match[1]] = struct{}{} |
| 44 | + } |
| 45 | + |
| 46 | + for token := range uniqueMatches { |
| 47 | + s1 := detectors.Result{ |
| 48 | + DetectorType: s.Type(), |
| 49 | + // NOTE: we redact the same way it is done in the `Label` field |
| 50 | + Redacted: token[:12] + "..." + token[70:], |
| 51 | + Raw: []byte(token), |
| 52 | + SecretParts: map[string]string{"key": token}, |
| 53 | + } |
| 54 | + |
| 55 | + if verify { |
| 56 | + client := s.client |
| 57 | + if client == nil { |
| 58 | + client = defaultClient |
| 59 | + } |
| 60 | + |
| 61 | + verified, extraData, verificationErr := verifyToken(ctx, client, token) |
| 62 | + s1.Verified = verified |
| 63 | + s1.ExtraData = extraData |
| 64 | + s1.SetVerificationError(verificationErr) |
| 65 | + } |
| 66 | + |
| 67 | + results = append(results, s1) |
| 68 | + } |
| 69 | + |
| 70 | + return results, err |
| 71 | +} |
| 72 | + |
| 73 | +func verifyToken(ctx context.Context, client *http.Client, token string) (bool, map[string]string, error) { |
| 74 | + req, err := http.NewRequestWithContext(ctx, "GET", "https://openrouter.ai/api/v1/key", nil) |
| 75 | + if err != nil { |
| 76 | + return false, nil, err |
| 77 | + } |
| 78 | + |
| 79 | + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 80 | + res, err := client.Do(req) |
| 81 | + if err != nil { |
| 82 | + return false, nil, err |
| 83 | + } |
| 84 | + defer func() { |
| 85 | + _, _ = io.Copy(io.Discard, res.Body) |
| 86 | + _ = res.Body.Close() |
| 87 | + }() |
| 88 | + |
| 89 | + switch res.StatusCode { |
| 90 | + case http.StatusOK: |
| 91 | + var keyResponse keyResponse |
| 92 | + if err = json.NewDecoder(res.Body).Decode(&keyResponse); err != nil { |
| 93 | + return false, nil, err |
| 94 | + } |
| 95 | + |
| 96 | + key := keyResponse.Data |
| 97 | + extraData := map[string]string{ |
| 98 | + "label": key.Label, |
| 99 | + "limit": fmtFloatPtr(key.Limit), |
| 100 | + "usage": fmt.Sprintf("%f", key.Usage), |
| 101 | + "is_free_tier": strconv.FormatBool(key.IsFreeTier), |
| 102 | + "limit_remaining": fmtFloatPtr(key.LimitRemaining), |
| 103 | + } |
| 104 | + return true, extraData, nil |
| 105 | + case http.StatusUnauthorized: |
| 106 | + // Invalid |
| 107 | + return false, nil, nil |
| 108 | + default: |
| 109 | + return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +func (s Scanner) Type() detector_typepb.DetectorType { |
| 114 | + return detector_typepb.DetectorType_OpenRouter |
| 115 | +} |
| 116 | + |
| 117 | +func (s Scanner) Description() string { |
| 118 | + return "OpenRouter provides a unified API that gives you access to hundreds of AI models through a single endpoint, while automatically handling fallbacks and selecting the most cost-effective options." |
| 119 | +} |
| 120 | + |
| 121 | +func fmtFloatPtr(f *float64) string { |
| 122 | + if f == nil { |
| 123 | + return "<nil>" |
| 124 | + } |
| 125 | + return fmt.Sprintf("%f", *f) |
| 126 | +} |
| 127 | + |
| 128 | +type keyResponse struct { |
| 129 | + Data key `json:"data"` |
| 130 | +} |
| 131 | + |
| 132 | +type key struct { |
| 133 | + Label string `json:"label"` |
| 134 | + Limit *float64 `json:"limit"` |
| 135 | + Usage float64 `json:"usage"` |
| 136 | + IsFreeTier bool `json:"is_free_tier"` |
| 137 | + LimitRemaining *float64 `json:"limit_remaining"` |
| 138 | +} |
0 commit comments