zen-free 0.1.5: a request carries a session id OpenCode itself could have made, so Zen's free tier serves it again (#100, xqvvu)
Zen's chat endpoints now answer the free tier's requests 403 FreeTierError
("can only be used from within OpenCode") unless x-opencode-session looks
like an id OpenCode made. 0.1.4 sent a sha256 cut to the ses_ shape; Zen
decodes the id as OpenCode's identifier.ts lays it out (12 hex of
~(Date.now()*0x1000 + counter), then 14 base62) and turns away one whose
counter is not small.
Bisected against the real upstream by replaying 0.1.4's captured request:
- 0.1.4's ses_e9283da055b15JwOAra76bwUx4: 403. The same request with the
session of a real OpenCode 1.19.0 run: 200. The real UA alone, or a real
msg_ request id alone: still 403.
- Any timestamp passes (epoch 0, a year back, an hour ahead); the low 3 hex
ffe/ffd/ff0 (counter 1/2/15) pass, f00/c00/800/001 get 403; 25 or 27
characters after ses_ get 403.
Now:
- sessionID makes a real descending id with the current time and counter,
kept per conversation (sha256 of the signal, at most 1000 kept) so a
conversation's turns share one session. An id the caller sent through
that OpenCode could have made is passed on unchanged.
- x-opencode-request is an ascending msg_ id, x-opencode-session-id is
sent too, and the User-Agent is OpenCode 1.19.0's
(opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14), as
captured from the real client.
Run: bun test in packages/zen-free, 166 pass. With 0.1.4's hash put back,
the new session tests and the streaming header test go red (3 fail).
tools-smoke.mjs against the real opencode.ai: big-pickle,
mimo-v2.6-flash-free and muse-spark-1.3-contributor-free each 200 with a
Bash call, streamed and not; 0.1.4's provider.mjs in the same run: 403
FreeTierError.
Not done here: magpie maps this 403 to permission_error, which reads as a
sign-in problem; that is magpie's gateway, not this package.
This commit is contained in:
@@ -171,7 +171,10 @@ for (const [input, supplied, expected] of [
|
||||
});
|
||||
await response.text();
|
||||
assert.equal(state.calls.at(-1).headers["x-opencode-project"], expected);
|
||||
assert.equal(state.calls.at(-1).headers["user-agent"], "opencode/1.18.34");
|
||||
assert.equal(
|
||||
state.calls.at(-1).headers["user-agent"],
|
||||
"opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -286,10 +289,11 @@ test("forces upstream streaming, preserves existing tools and returns the SSE bo
|
||||
assert.match(await response.text(), /\[DONE\]/);
|
||||
const sent = state.calls.at(-1);
|
||||
assert.equal(sent.headers.authorization, "Bearer public");
|
||||
assert.match(sent.headers["x-opencode-session"], /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/);
|
||||
assert.match(sent.headers["x-opencode-session"], /^ses_[0-9a-f]{9}ff[0-9a-f][0-9A-Za-z]{14}$/);
|
||||
assert.equal(sent.headers["x-session-affinity"], sent.headers["x-opencode-session"]);
|
||||
assert.equal(sent.headers["x-session-id"], sent.headers["x-opencode-session"]);
|
||||
assert.ok(sent.headers["x-opencode-request"]);
|
||||
assert.equal(sent.headers["x-opencode-session-id"], sent.headers["x-opencode-session"]);
|
||||
assert.match(sent.headers["x-opencode-request"], /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/);
|
||||
assert.equal(sent.body.stream, true);
|
||||
assert.equal(sent.body.stream_options.include_usage, true);
|
||||
assert.deepEqual(sent.body.tools[0], bash);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zen-free-auth",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5",
|
||||
"description": "OpenCode Zen free models through the public credential, with native streaming protocols",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import {
|
||||
PROVIDER,
|
||||
SDK,
|
||||
@@ -16,7 +16,9 @@ const DOCS =
|
||||
"https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx";
|
||||
const PATHS = { chat: "/chat/completions", responses: "/responses", anthropic: "/messages" };
|
||||
const CORE_TOOLS = ["bash", "edit", "glob", "grep", "read"];
|
||||
const OPENCODE_VERSION = "1.18.34";
|
||||
const OPENCODE_VERSION = "1.19.0";
|
||||
// What OpenCode 1.19.0 sends as its User-Agent, ai-sdk and Bun included.
|
||||
const USER_AGENT = `opencode/${OPENCODE_VERSION} ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14`;
|
||||
// How long a request for a model the last list didn't have waits before it
|
||||
// asks Zen's list again: a model Zen made free since is served at once,
|
||||
// and a model typed in by hand doesn't ask the list on every request.
|
||||
@@ -82,10 +84,45 @@ function normalizeTools(body, protocol) {
|
||||
return { declared };
|
||||
}
|
||||
|
||||
function sessionID(headers, body) {
|
||||
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
let lastStamp = 0;
|
||||
let counter = 0;
|
||||
|
||||
// An id the way OpenCode makes one (packages/schema/src/identifier.ts):
|
||||
// 12 hex of Date.now() * 0x1000 + a per-millisecond counter (bit-inverted
|
||||
// for a session, so newer sorts first), then 14 random base62 characters.
|
||||
// Zen's free tier checks a session id has this shape, a small counter
|
||||
// included, and answers 403 FreeTierError to one that doesn't (#100).
|
||||
export function opencodeID(prefix, descending, now = Date.now()) {
|
||||
if (now !== lastStamp) {
|
||||
lastStamp = now;
|
||||
counter = 0;
|
||||
}
|
||||
counter++;
|
||||
const current = BigInt(now) * 0x1000n + BigInt(counter);
|
||||
const value = (descending ? ~current : current) & 0xffffffffffffn;
|
||||
const random = randomBytes(14);
|
||||
let tail = "";
|
||||
for (const byte of random) tail += ALPHABET[byte % 62];
|
||||
return `${prefix}_${value.toString(16).padStart(12, "0")}${tail}`;
|
||||
}
|
||||
|
||||
// A session id OpenCode itself could have made: its counter (the low 12
|
||||
// bits, inverted) is small. A hash cut to the same shape isn't one.
|
||||
export function realSessionID(value) {
|
||||
const match = /^ses_[0-9a-f]{9}([0-9a-f]{3})[0-9A-Za-z]{14}$/.exec(value ?? "");
|
||||
return !!match && 0xfff - Number.parseInt(match[1], 16) < 16;
|
||||
}
|
||||
|
||||
// One made-up session per conversation, so its turns keep one session.
|
||||
const SESSIONS = new Map();
|
||||
const KEEP_SESSIONS = 1000;
|
||||
|
||||
export function sessionID(headers, body) {
|
||||
let signal;
|
||||
for (const name of [
|
||||
"x-opencode-session",
|
||||
"x-opencode-session-id",
|
||||
"x-session-affinity",
|
||||
"x-session-id",
|
||||
"conversation-id",
|
||||
@@ -96,24 +133,25 @@ function sessionID(headers, body) {
|
||||
}
|
||||
}
|
||||
if (!signal && typeof body.metadata?.session_id === "string") signal = body.metadata.session_id;
|
||||
if (realSessionID(signal)) return signal;
|
||||
if (!signal) {
|
||||
const messages = body.messages ?? body.input;
|
||||
const first = Array.isArray(messages)
|
||||
? messages.find((message) => message.role === "user")?.content
|
||||
: messages;
|
||||
signal = first ? JSON.stringify(first) : randomUUID();
|
||||
if (!first) return opencodeID("ses", true);
|
||||
signal = JSON.stringify(first);
|
||||
}
|
||||
if (/^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/.test(signal)) return signal;
|
||||
// Keep conversation affinity using OpenCode's canonical session format.
|
||||
const hash = createHash("sha256").update(`ses\0${signal}`).digest("hex");
|
||||
let value = BigInt(`0x${hash.slice(12, 32)}`);
|
||||
let suffix = "";
|
||||
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
for (let i = 0; i < 14; i++) {
|
||||
suffix = alphabet[Number(value % 62n)] + suffix;
|
||||
value /= 62n;
|
||||
const key = createHash("sha256").update(`ses\0${signal}`).digest("hex");
|
||||
let session = SESSIONS.get(key);
|
||||
if (session) {
|
||||
SESSIONS.delete(key);
|
||||
} else {
|
||||
session = opencodeID("ses", true);
|
||||
if (SESSIONS.size >= KEEP_SESSIONS) SESSIONS.delete(SESSIONS.keys().next().value);
|
||||
}
|
||||
return `ses_${hash.slice(0, 12)}${suffix}`;
|
||||
SESSIONS.set(key, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
async function server(_input, options = {}) {
|
||||
@@ -258,9 +296,9 @@ async function server(_input, options = {}) {
|
||||
}
|
||||
headers.set("content-type", "application/json");
|
||||
headers.set("accept", "text/event-stream");
|
||||
headers.set("user-agent", `opencode/${OPENCODE_VERSION}`);
|
||||
headers.set("user-agent", USER_AGENT);
|
||||
headers.set("x-opencode-client", "cli");
|
||||
headers.set("x-opencode-request", `req_${randomUUID().replaceAll("-", "")}`);
|
||||
headers.set("x-opencode-request", opencodeID("msg", false));
|
||||
if (!headers.has("x-opencode-project")) {
|
||||
const project = _input?.project;
|
||||
headers.set(
|
||||
@@ -269,7 +307,12 @@ async function server(_input, options = {}) {
|
||||
);
|
||||
}
|
||||
const session = sessionID(headers, body);
|
||||
for (const name of ["x-session-id", "x-opencode-session", "x-session-affinity"])
|
||||
for (const name of [
|
||||
"x-session-id",
|
||||
"x-opencode-session",
|
||||
"x-opencode-session-id",
|
||||
"x-session-affinity",
|
||||
])
|
||||
headers.set(name, session);
|
||||
if (protocol === "anthropic") {
|
||||
headers.set("x-api-key", "public");
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { opencodeID, realSessionID, sessionID } from "./provider.mjs";
|
||||
|
||||
const SHAPE = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
|
||||
|
||||
// Decode an id the way OpenCode's identifier.ts lays it out.
|
||||
function decode(id, descending) {
|
||||
let value = BigInt(`0x${id.slice(4, 16)}`);
|
||||
if (descending) value = ~value & 0xffffffffffffn;
|
||||
return { time: Number(value / 0x1000n), counter: Number(value % 0x1000n) };
|
||||
}
|
||||
|
||||
test("a made-up session id is OpenCode's: descending, the time it was made, a small counter", () => {
|
||||
const before = Date.now();
|
||||
const id = sessionID(new Headers({ "x-session-id": "conversation-a" }), {});
|
||||
const after = Date.now();
|
||||
assert.match(id, SHAPE);
|
||||
assert.ok(realSessionID(id), id);
|
||||
const { time, counter } = decode(id, true);
|
||||
// OpenCode keeps 48 bits, so the time is Date.now() modulo 2^36.
|
||||
const wrap = 2 ** 36;
|
||||
assert.ok(time >= before % wrap && time <= after % wrap, `${time} not in ${before}..${after}`);
|
||||
assert.ok(counter >= 1 && counter < 16, `counter ${counter}`);
|
||||
});
|
||||
|
||||
test("one conversation keeps one session, another gets its own", () => {
|
||||
const a1 = sessionID(new Headers({ "x-session-id": "conversation-b" }), {});
|
||||
const a2 = sessionID(new Headers({ "x-session-id": "conversation-b" }), {});
|
||||
const b = sessionID(new Headers({ "x-session-id": "conversation-c" }), {});
|
||||
assert.equal(a1, a2);
|
||||
assert.notEqual(a1, b);
|
||||
const body = { messages: [{ role: "user", content: "first question" }] };
|
||||
assert.equal(sessionID(new Headers(), body), sessionID(new Headers(), body));
|
||||
});
|
||||
|
||||
test("OpenCode's own session id is passed through, a hash cut to its shape is not", () => {
|
||||
const real = "ses_ecc5d8f28ffe9Cy14V8Em7lI2u";
|
||||
assert.equal(sessionID(new Headers({ "x-opencode-session": real }), {}), real);
|
||||
// 0.1.4 sent this for "x-session-id: session_123"; Zen answers it 403.
|
||||
const hashed = "ses_e9283da055b15JwOAra76bwUx4";
|
||||
assert.equal(realSessionID(hashed), false);
|
||||
const sent = sessionID(new Headers({ "x-opencode-session": hashed }), {});
|
||||
assert.notEqual(sent, hashed);
|
||||
assert.ok(realSessionID(sent), sent);
|
||||
});
|
||||
|
||||
test("ids made in one millisecond count up, as OpenCode's do", () => {
|
||||
const now = 1_790_000_000_000;
|
||||
const first = opencodeID("msg", false, now);
|
||||
const second = opencodeID("msg", false, now);
|
||||
assert.equal(decode(first, false).counter, 1);
|
||||
assert.equal(decode(second, false).counter, 2);
|
||||
assert.ok(second > first);
|
||||
});
|
||||
Reference in New Issue
Block a user