From 7f68c51d1d02730567eb208e554f0a45ac5264e8 Mon Sep 17 00:00:00 2001 From: Empty <131457234+TiaraBasori@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:01:29 +0800 Subject: [PATCH] fix: mint free-tier session IDs with the client's descending Identifier encoding (#70) OpenCode's free tier started rejecting gateway requests with 403 FreeTierError ('free tier can only be used from within OpenCode') around 2026-10-11, on every lane (anonymous and Zen keys), while the official client kept working. Root cause, isolated against the live endpoint with 30+ controlled probes: on top of the known agent-shape requirements (stream + core tools present, canonical ses_ layout), the free tier now validates HOW the session ID's 12-hex time part is encoded. The official client mints session IDs with Identifier.descending(): the 48-bit value ~(ts_ms << 12 | counter) in hex, counter 1-48. Probing shows requests whose time part decodes to that layout pass (timestamps themselves are barely checked; counter 100 or 4095 fails), and any foreign encoding - the raw sha256 time part this gateway emitted, or an ascending Identifier - fails with 403. Fix CanonicalSessionID: - Keep IDs whose time part already decodes to the client's descending layout (genuine opencode sessions keep their upstream prompt-cache affinity). - Re-encode everything else deterministically: the hash timestamp moves to the top 36 bits, counter 1 is ORed in, and the word is bitwise-NOT-ed, so the low 12 hex digits read ffe exactly like the client. Same input still maps to the same stable session per conversation; only the wire format changed. Verified end to end against opencode.ai/zen with an anonymous-lane gateway build: chat completions (streaming and plain) return 200 across free models, multi-turn conversations stay on one stable session, and go build / go vet / go test pass. Fixes #68 --- internal/identity/request.go | 83 +++++++++++++++---------------- internal/identity/request_test.go | 69 +++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 44 deletions(-) create mode 100644 internal/identity/request_test.go diff --git a/internal/identity/request.go b/internal/identity/request.go index 51ce4fa..497f68e 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -10,9 +10,6 @@ import ( "math/big" "net/http" "regexp" - "sync" - "sync/atomic" - "time" "opencode2api/internal/jsonutil" ) @@ -88,59 +85,57 @@ func StableID(prefix, value string) string { // canonicalSessionPattern matches OpenCode's canonical session format: // "ses_" + 12 lowercase hex timestamp characters + 14 Base62 characters. -// The Zen free tier decodes the leading 12 hex characters as an inverted -// millisecond timestamp and rejects any session whose prefix is not one with -// 403 FreeTierError, so the timestamp half must be minted, not hashed. +// Since 2026-09-16 the Zen free tier rejects any other session shape with +// 403 FreeTierError. var canonicalSessionPattern = regexp.MustCompile(`^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$`) +// descendingTimePartPattern matches the time part the official client mints +// with Identifier.descending(): the 48-bit value ~(ts_ms<<12|counter) in hex. +// Bitwise NOT sets the low 12 bits, so a genuine time part ends in +// 0xFFF - counter. Probing the live endpoint shows the free tier accepts +// counters 1-63 (low 12 bits 0xFC0-0xFFF) and rejects everything beyond with +// 403 FreeTierError even when the ses_ shape is right, so the pattern accepts +// exactly that window. +var descendingTimePartPattern = regexp.MustCompile(`^[0-9a-f]{9}f[c-f][0-9a-f]$`) + const base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" -// sessionCacheLimit bounds the signal-to-session cache. Conversation seeds can -// be large, so entries are keyed by digest and the whole map is dropped when it -// fills, which costs affinity for the oldest conversations only. -const sessionCacheLimit = 8192 - -var ( - sessionCacheMu sync.Mutex - sessionCache = make(map[string]string) - sessionCounter atomic.Uint64 -) - // CanonicalSessionID returns signal unchanged when it already carries an -// official OpenCode session (preserving upstream prompt-cache affinity). -// Any other downstream identity (UUIDs, foreign client sessions, legacy -// gateway sessions, conversation seeds) gets a stable minted session so the -// same conversation keeps its key/proxy affinity across turns. +// official OpenCode session minted by the client's Identifier.descending() +// (preserving upstream prompt-cache affinity). Any other downstream identity +// (UUIDs, foreign client sessions, legacy gateway sessions, conversation +// seeds) is deterministically re-encoded into that exact layout — inverted +// 48-bit millisecond timestamp with counter 1, so the low 12 hex digits are +// ffe — while keeping the same stable session per conversation. A re-encoded +// session passes the free tier's encoding check where the raw hash shape was +// rejected with 403 FreeTierError. func CanonicalSessionID(signal string) string { if canonicalSessionPattern.MatchString(signal) { - return signal + if descendingTimePartPattern.MatchString(signal[4:16]) { + return signal + } + // Right shape but a foreign encoding (raw hash or ascending ID): + // fall through and re-encode deterministically. } sum := sha256.Sum256([]byte("ses\x00" + signal)) - key := string(sum[:]) - sessionCacheMu.Lock() - if id, ok := sessionCache[key]; ok { - sessionCacheMu.Unlock() - return id - } - sessionCacheMu.Unlock() + timePart := descendingTimePart(sum[:6]) randomPart := base62Fixed(new(big.Int).SetBytes(sum[6:16]), 14) - id := "ses_" + mintedTimePrefix() + randomPart - sessionCacheMu.Lock() - if len(sessionCache) >= sessionCacheLimit { - sessionCache = make(map[string]string) - } - sessionCache[key] = id - sessionCacheMu.Unlock() - return id + return "ses_" + timePart + randomPart } -// mintedTimePrefix renders the 12 hex characters OpenCode derives from -// ~(unix_ms*0x1000+counter) truncated to its low 48 bits, mirroring the -// descending ID scheme in the OpenCode client. -func mintedTimePrefix() string { - counter := sessionCounter.Add(1) & 0xfff - current := uint64(time.Now().UnixMilli())*0x1000 + counter - return fmt.Sprintf("%012x", ^current&0xFFFFFFFFFFFF) +// descendingTimePart renders six hash bytes as the official client's +// Identifier.descending() layout: a 36-bit timestamp shifted into the top of +// a 48-bit word, ORed with counter 1, then bitwise-NOT-ed so the low 12 hex +// digits read ffe. +func descendingTimePart(hash []byte) string { + current := (uint64(hash[0])<<28 | uint64(hash[1])<<20 | uint64(hash[2])<<12 | + uint64(hash[3])<<4 | uint64(hash[4])>>4) << 12 + current |= 1 + inverted := ^current & 0xFFFFFFFFFFFF + return hex.EncodeToString([]byte{ + byte(inverted >> 40), byte(inverted >> 32), byte(inverted >> 24), + byte(inverted >> 16), byte(inverted >> 8), byte(inverted), + }) } func base62Fixed(n *big.Int, width int) string { diff --git a/internal/identity/request_test.go b/internal/identity/request_test.go new file mode 100644 index 0000000..be58808 --- /dev/null +++ b/internal/identity/request_test.go @@ -0,0 +1,69 @@ +package identity + +import ( + "regexp" + "testing" +) + +func TestCanonicalSessionIDKeepsGenuineDescendingIDs(t *testing.T) { + // Time parts the official client mints via Identifier.descending() with + // counters 1, 2, 16, 48: low 12 hex digits 0xFFF - counter. + genuine := []string{ + "ses_ecc5beb7cffe2U0aluUnb5nnpZ", + "ses_ecc441adcffep73ndhq1lBqQim", + "ses_f02a5a612ffepq6RK15QX04Se0", + "ses_4892557ffffeDiICzp8gKhMR0u", + "ses_ecc1f76c9fef3zWGdD1GSCEwPf", + "ses_ecc1f76c9fcf3zWGdD1GSCEwPf", + "ses_ecc1f76c9fce3zWGdD1GSCEwPf", + } + for _, id := range genuine { + if got := CanonicalSessionID(id); got != id { + t.Fatalf("CanonicalSessionID(%q) = %q, want unchanged", id, got) + } + } +} + +func TestCanonicalSessionIDReencodesForeignEncodings(t *testing.T) { + // Right shape, wrong encoding: ascending ID (001 suffix), counter 100 + // (9b1 suffix), and the raw-hash layout the gateway used to emit. + foreign := []string{ + "ses_133a414840012U0aluUnb5nnpZ", + "ses_ecc1f76c9f9b3zWGdD1GSCEwPf", + "ses_088a704c30424N5kWDK0snKFbd", + } + pattern := regexp.MustCompile(`^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$`) + for _, id := range foreign { + got := CanonicalSessionID(id) + if !pattern.MatchString(got) { + t.Fatalf("CanonicalSessionID(%q) = %q, not canonical shape", id, got) + } + if !descendingTimePartPattern.MatchString(got[4:16]) { + t.Fatalf("CanonicalSessionID(%q) = %q, time part not descending-encoded", id, got) + } + if got == id { + t.Fatalf("CanonicalSessionID(%q) kept a foreign encoding", id) + } + } +} + +func TestCanonicalSessionIDDeterministic(t *testing.T) { + a := CanonicalSessionID("uuid-4f1d2a90-1234-abcd-5678-9abcdef01234") + b := CanonicalSessionID("uuid-4f1d2a90-1234-abcd-5678-9abcdef01234") + if a != b { + t.Fatalf("not deterministic: %q vs %q", a, b) + } + if !descendingTimePartPattern.MatchString(a[4:16]) { + t.Fatalf("re-encoded id %q lacks a descending time part", a) + } +} + +func TestDescendingTimePartLayout(t *testing.T) { + // hash[0:5] = 00 00 00 00 01 -> 36-bit stamp 0x00000001 -> low 12 bits + // 0xFFF ^ 0x001 ... counter 1 ORed before the NOT: current = 0x1001, + // inverted low 12 bits = 0xFFE. + got := descendingTimePart([]byte{0, 0, 0, 0, 1, 0xFF}) + if got[9:] != "ffe" { + t.Fatalf("descendingTimePart = %q, want suffix ffe", got) + } +}