shotluma/scripts/opencode-proxy.test.ts
Enderson Vizcaino 952cd42c0b
fix(ai): send x-opencode-session on every OpenCode request (#23)
* fix(ai): send x-opencode-session on every OpenCode request

OpenCode Go and Zen require a stable per-conversation session id in the
x-opencode-session header so the gateway can route traffic and reuse prompt
caches (https://opencode.ai/docs/go/#where-can-i-use-it). Without it the
gateway answers "Request is missing x-opencode-session and cannot be routed
efficiently" and the run fails.

- build one module-scope session id per browser session and pass it through
  headers to all four OpenCode dialects (responses, chat, messages, google),
  which also covers the vision describer
- forward the header through the hosted Cloudflare Worker proxy, whose
  allowlist previously stripped it; the Vite dev proxy already forwarded it

* fix(ai): keep the OpenCode session id stable across reloads

The module-scope session id was regenerated on every full page load, so
reloads dropped the stable identity the OpenCode gateway needs for routing
and prompt caching.

Read the id from sessionStorage, generate one when none is stored, and
persist it; a fresh tab still gets its own id, which keeps sharding traffic
across clients. Storage that is unavailable or throws falls back to a
per-page-load id instead of failing the request.
2026-10-19 23:16:55 +02:00

141 lines
5.5 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import {
copyOpencodeProxyHeaders,
isOpencodeProxyMethod,
proxyOpencodeRequest,
rewriteOpencodeProxyUrl,
} from './opencode-proxy'
describe('OpenCode CORS proxy rewrite', () => {
it('maps Zen and Go prefixes onto the public OpenCode origins', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/chat/completions'),
)?.toString()).toBe('https://opencode.ai/zen/v1/chat/completions')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/v1/models?foo=1'),
)?.toString()).toBe('https://opencode.ai/zen/go/v1/models?foo=1')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen'),
)?.toString()).toBe('https://opencode.ai/zen/')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/moonshot/v1/chat/completions'),
)).toBeNull()
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go'),
)?.toString()).toBe('https://opencode.ai/zen/go/')
})
it('maps every dialect path each gateway serves', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/v1/responses'),
)?.toString()).toBe('https://opencode.ai/zen/go/v1/responses')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/messages'),
)?.toString()).toBe('https://opencode.ai/zen/v1/messages')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/models/gemini-3.7-flash:streamGenerateContent'),
)?.toString()).toBe('https://opencode.ai/zen/v1/models/gemini-3.7-flash:streamGenerateContent')
})
it('does not treat a zen path as go', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/models'),
)?.toString()).toBe('https://opencode.ai/zen/v1/models')
})
})
describe('OpenCode CORS proxy headers and methods', () => {
it('forwards only the allowlisted request headers', () => {
const headers = copyOpencodeProxyHeaders(new Headers({
authorization: 'Bearer test-key',
'content-type': 'application/json',
accept: 'text/event-stream',
'x-opencode-session': 'shotluma-test-session',
cookie: 'session=secret',
host: 'app.shotluma.com',
}))
expect(Object.fromEntries(headers.entries())).toEqual({
authorization: 'Bearer test-key',
'content-type': 'application/json',
accept: 'text/event-stream',
'x-opencode-session': 'shotluma-test-session',
})
})
it('forwards the Anthropic and Google credentials the other dialects use', () => {
const headers = copyOpencodeProxyHeaders(new Headers({
'x-api-key': 'sk-test',
'anthropic-version': '2023-06-01',
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
'x-goog-api-key': 'goog-test',
origin: 'https://evil.example',
}))
expect(Object.fromEntries(headers.entries())).toEqual({
'x-api-key': 'sk-test',
'anthropic-version': '2023-06-01',
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
'x-goog-api-key': 'goog-test',
})
})
it('allows GET, POST, and OPTIONS only', () => {
expect(isOpencodeProxyMethod('get')).toBe(true)
expect(isOpencodeProxyMethod('POST')).toBe(true)
expect(isOpencodeProxyMethod('OPTIONS')).toBe(true)
expect(isOpencodeProxyMethod('PUT')).toBe(false)
})
it('answers OPTIONS without contacting OpenCode', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const response = await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/models',
{ method: 'OPTIONS' },
))
expect(response.status).toBe(204)
expect(fetchMock).not.toHaveBeenCalled()
vi.unstubAllGlobals()
})
it('rejects unsupported methods and unknown paths', async () => {
expect((await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/models',
{ method: 'DELETE' },
))).status).toBe(405)
expect((await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/moonshot/v1/models',
{ method: 'GET' },
))).status).toBe(404)
})
it('forwards GET and POST to the rewritten OpenCode origin', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const getResponse = await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/go/v1/models',
{ method: 'GET', headers: { authorization: 'Bearer test-key' } },
))
expect(getResponse.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [getUrl, getInit] = fetchMock.mock.calls[0] as [URL, RequestInit]
expect(getUrl.toString()).toBe('https://opencode.ai/zen/go/v1/models')
expect(getInit.method).toBe('GET')
expect(getInit.body).toBeUndefined()
await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/chat/completions',
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{"model":"kimi-k3"}',
},
))
const [, postInit] = fetchMock.mock.calls[1] as [URL, RequestInit & { duplex?: string }]
expect(postInit.method).toBe('POST')
expect(postInit.body).toBeDefined()
expect(postInit.duplex).toBe('half')
vi.unstubAllGlobals()
})
})