File size: 6,912 Bytes
e48a2d8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | // session.go 免费车道的会话/项目身份与请求头。
//
// 这些值不是业务字段,而是上游用来校验「这是官方 OpenCode 客户端」的指纹:
// - ses_<12 hex><14 base62>,12 位 hex 是 ~(ms<<12|1) 的降序编码;
// - x-opencode-project 是 40 位 hex(git 根提交形状);
// - 四个会话头同值,另带 traceparent/b3。
//
// 移植自 dsh-our-free-model 的 src/o2a/{identity,headers}.js。
package freemodel
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"net/http"
"strings"
"sync"
"time"
)
const (
base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
clientUA = "opencode/latest/2.2.3/cli"
anonCredential = "public"
sessionPrefix = "ses_"
)
var (
bootNonce = randomBytes(16)
lastStamp int64
seq int
stampMu sync.Mutex
sessionNow = time.Now
)
func randomBytes(n int) []byte {
buf := make([]byte, n)
_, _ = rand.Read(buf)
return buf
}
func isHex(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f')) {
return false
}
}
return true
}
// isCanonicalSession 报告 id 是否是上游接受的会话形状。
func isCanonicalSession(id string) bool {
if !strings.HasPrefix(id, sessionPrefix) || len(id) != 4+12+14 {
return false
}
if !isHex(id[4:16]) {
return false
}
// 降序时间编码的计数器窗口:第 10 位必须是 f,第 11 位 c-f。
if id[13] != 'f' {
return false
}
if id[14] < 'c' || id[14] > 'f' {
return false
}
for _, r := range id[16:] {
if !strings.ContainsRune(base62Alphabet, r) {
return false
}
}
return true
}
// canonicalSession 把任意 signal 收敛成上游接受的会话 id。
func canonicalSession(signal string) string {
signal = strings.TrimSpace(signal)
if isCanonicalSession(signal) {
return signal
}
h := sha256.New()
h.Write([]byte("ses\x00"))
h.Write(bootNonce)
h.Write([]byte{0})
h.Write([]byte(signal))
digest := h.Sum(nil)
return sessionPrefix + descendingTimePart(digest) + base62Fixed(digest[6:16], 14)
}
// descendingTimePart 生成 12 位降序时间 hex:今日 UTC 零点减去最多 30 天的
// 哈希偏移,再 <<12|1 取反。
func descendingTimePart(hash []byte) string {
offset := (uint32(hash[0])<<24 | uint32(hash[1])<<16 | uint32(hash[2])<<8 | uint32(hash[3])) % uint32(30*24*60*60*1000)
now := sessionNow().UTC()
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).UnixMilli()
base := uint64(midnight) - uint64(offset)
inverted := ^((base << 12) | 1) & 0xFFFFFFFFFFFF
return hex.EncodeToString([]byte{
byte(inverted >> 40), byte(inverted >> 32), byte(inverted >> 24),
byte(inverted >> 16), byte(inverted >> 8), byte(inverted),
})
}
func base62Fixed(bytes []byte, width int) string {
n := newBigInt()
for _, b := range bytes {
n.mul(256)
n.add(int(b))
}
out := make([]byte, width)
for i := width - 1; i >= 0; i-- {
out[i] = base62Alphabet[n.mod(62)]
n.div(62)
}
return string(out)
}
// 极小的大整数实现:只用于 8 字节 → 14 位 base62,避免为一行逻辑引入 math/big。
type smallBig struct{ words [8]uint32 } // 256-bit,足够
func newBigInt() *smallBig { return &smallBig{} }
func (b *smallBig) mul(m uint32) {
carry := uint64(0)
for i := range b.words {
v := uint64(b.words[i])*uint64(m) + carry
b.words[i] = uint32(v)
carry = v >> 32
}
}
func (b *smallBig) add(v int) {
carry := uint64(v)
for i := range b.words {
if carry == 0 {
return
}
sum := uint64(b.words[i]) + carry
b.words[i] = uint32(sum)
carry = sum >> 32
}
}
func (b *smallBig) div(d uint32) {
rem := uint64(0)
for i := len(b.words) - 1; i >= 0; i-- {
cur := (rem << 32) | uint64(b.words[i])
b.words[i] = uint32(cur / uint64(d))
rem = cur % uint64(d)
}
}
func (b *smallBig) mod(d uint32) int {
rem := uint64(0)
for i := len(b.words) - 1; i >= 0; i-- {
rem = ((rem << 32) | uint64(b.words[i])) % uint64(d)
}
return int(rem)
}
// sessionSignal 从请求里挑一个稳定的会话信号:优先显式头,其次首条用户消息,
// 最后回落到全局桶。
func sessionSignal(r *http.Request, body map[string]any) string {
for _, key := range []string{"x-opencode-session", "x-session-id", "X-Session-Id", "x-session-affinity"} {
if v := strings.TrimSpace(r.Header.Get(key)); isCanonicalSession(v) {
return v
}
}
if v, ok := body["user"].(string); ok && strings.TrimSpace(v) != "" {
return "user:" + strings.TrimSpace(v)
}
if messages, ok := body["messages"].([]any); ok {
for _, raw := range messages {
msg, _ := raw.(map[string]any)
if msg == nil {
continue
}
if role, _ := msg["role"].(string); role != "system" && role != "developer" {
if text, ok := msg["content"].(string); ok && strings.TrimSpace(text) != "" {
sum := sha256.Sum256([]byte(text))
return "chat:" + hex.EncodeToString(sum[:8])
}
}
}
}
return "global"
}
func sessionFor(r *http.Request, body map[string]any) string {
return canonicalSession(sessionSignal(r, body))
}
// projectID 生成 40 位 hex 项目 id:调用方给了 git 提交形状或 global 就沿用,
// 其余从会话 id 派生(同一会话一个配额桶)。
func projectID(r *http.Request, session string) string {
if r != nil {
if raw := strings.TrimSpace(r.Header.Get("x-opencode-project")); raw == "global" || (len(raw) == 40 && isHex(raw)) {
return raw
}
}
sum := sha256.Sum256([]byte("opencode-project\x00" + session))
return hex.EncodeToString(sum[:20])
}
// gatewayHeaders 官方 2.2.3 客户端的请求头集合。
func gatewayHeaders(session, project string) map[string]string {
trace := randomBytes(16)
span := randomBytes(8)
parent := randomBytes(8)
return map[string]string{
"content-type": "application/json",
"authorization": "Bearer " + anonCredential,
"user-agent": clientUA,
"accept": "*/*",
"x-opencode-client": "cli",
"x-session-affinity": session,
"x-session-id": session,
"x-opencode-session": session,
"x-opencode-session-id": session,
"x-opencode-project": project,
"traceparent": "00-" + hex.EncodeToString(trace) + "-" + hex.EncodeToString(span) + "-01",
"b3": hex.EncodeToString(trace) + "-" + hex.EncodeToString(span) + "-1-" + hex.EncodeToString(parent),
}
}
// mintSessionID 仅用于测试与调试:按上游算法铸造一个新会话。
func mintSessionID(t time.Time) string {
stampMu.Lock()
defer stampMu.Unlock()
ms := t.UnixMilli()
if ms != lastStamp {
lastStamp = ms
seq = 0
}
seq++
value := ^((uint64(ms) << 12) | uint64(seq))
var out [6]byte
for i := 0; i < 6; i++ {
out[i] = byte(value >> (40 - 8*i))
}
return sessionPrefix + hex.EncodeToString(out[:]) + base62Fixed(randomBytes(14), 14)
}
|