Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/lib/core/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { hashKey } from './security.mjs'
import { atomicWriteJson } from '../vm/vm-file.mjs'
import { loadDistillRules } from './distill-detect.mjs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
Expand Down
12 changes: 9 additions & 3 deletions src/lib/core/intercept.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,18 @@ export function applyIntercept(rules, phase, ctx) {
return { ...ctx, body, headers }
}

const FORBIDDEN_PATH_PARTS = new Set(['__proto__', 'constructor', 'prototype'])

function setPath(obj, path, value) {
const parts = path.split('.')
const parts = String(path).split('.')
if (parts.some((part) => !part || FORBIDDEN_PATH_PARTS.has(part))) return
let cur = obj
for (let i = 0; i < parts.length - 1; i++) {
if (cur[parts[i]] == null || typeof cur[parts[i]] !== 'object') cur[parts[i]] = {}
cur = cur[parts[i]]
const key = parts[i]
const next = cur[key]
if (next == null || typeof next !== 'object') cur[key] = {}
else cur[key] = Array.isArray(next) ? [...next] : { ...next }
cur = cur[key]
}
cur[parts[parts.length - 1]] = value
}
42 changes: 39 additions & 3 deletions src/lib/core/security.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,29 @@ export function extractApiKey(req) {
return ''
}

const MAX_RATE_LIMIT_BUCKETS = 10_000

/** Simple token bucket per key; non-positive capacity or refill disables throttling. */
export function createRateLimiter({ capacity = 60, refillPerSec = 1 } = {}) {
export function createRateLimiter({ capacity = 60, refillPerSec = 1, maxKeys = MAX_RATE_LIMIT_BUCKETS } = {}) {
if (!(capacity > 0) || !(refillPerSec > 0)) return () => true
const cap = Number.isInteger(maxKeys) && maxKeys > 0 ? maxKeys : MAX_RATE_LIMIT_BUCKETS
const buckets = new Map()
const sweep = (now) => {
for (const [k, entry] of buckets) {
const refilled = entry.tokens + ((now - entry.updated) / 1000) * refillPerSec
if (refilled >= capacity) buckets.delete(k)
}
while (buckets.size >= cap) {
const oldest = buckets.keys().next().value
if (oldest === undefined) break
buckets.delete(oldest)
}
}
return function allow(key) {
const now = Date.now()
let b = buckets.get(key)
if (!b) {
if (buckets.size >= cap) sweep(now)
b = { tokens: capacity, updated: now }
buckets.set(key, b)
}
Expand All @@ -87,6 +102,7 @@ export function getPanelAdmin() {
}

const SESSION_TTL_MS = 7 * 24 * 3600 * 1000
const MAX_PANEL_SESSIONS = 10_000
const panelSessions = new Map() // sha256(token) -> { user, role, exp }
let _authenticateUser = null
let _lookupRole = null
Expand Down Expand Up @@ -137,12 +153,24 @@ function loadSessions() {
}
}

function prunePanelSessions(now = Date.now()) {
for (const [token, s] of panelSessions.entries()) {
if (!s || s.exp <= now) panelSessions.delete(token)
}
while (panelSessions.size > MAX_PANEL_SESSIONS) {
const oldest = panelSessions.keys().next().value
if (oldest === undefined) break
panelSessions.delete(oldest)
}
}

function saveSessions() {
try {
const f = sessionFile()
fs.mkdirSync(path.dirname(f), { recursive: true })
const obj = {}
const now = Date.now()
prunePanelSessions(now)
const obj = {}
for (const [token, s] of panelSessions.entries()) {
if (s.exp > now) obj[token] = s
}
Expand Down Expand Up @@ -240,6 +268,14 @@ export function verifyPanelLogin(username, password) {
return { username: admin.username, role: 'admin', id: null, source: 'env' }
}

function decodeCookieValue(raw) {
try {
return decodeURIComponent(raw)
} catch {
return raw
}
}

function parseCookie(header) {
const out = {}
if (!header) return out
Expand All @@ -248,7 +284,7 @@ function parseCookie(header) {
if (i < 0) continue
const k = part.slice(0, i).trim()
const v = part.slice(i + 1).trim()
if (k) out[k] = decodeURIComponent(v)
if (k) out[k] = decodeCookieValue(v)
}
return out
}
Expand Down
10 changes: 1 addition & 9 deletions src/lib/identity/claude-code-only.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import { makeError, ErrorType, ErrorCode } from '../core/errors.mjs'
import { detectProxiedOfficialCcFromRouting } from './crs-persona.mjs'
import { verifyDirectClaudeCodeHeaders, verifyOfficialClaudeCode } from './official-cc-verifier.mjs'
import { verifyOfficialClaudeCode } from './official-cc-verifier.mjs'

export function claudeCodeOnlyFromRouting(routing) {
return routing?.compatibility?.claude_code_only === true
Expand All @@ -15,14 +15,6 @@ function headerText(headers, key) {
return String(headers?.[key] ?? '').trim()
}

/**
* Complete direct Claude Code header bundle (strict UA + x-app + anthropic-version +
* browser-access + all 8 Stainless JS headers + UUIDv4 session header + optional beta).
*/
export function hasClaudeCodeClientHeaders(headers = {}, { requireCodeBeta = true } = {}) {
return verifyDirectClaudeCodeHeaders(headers, { requireCodeBeta }).ok
}

/**
* Claude Desktop's fixed gateway sign-in check (4.4212.0): Electron UA, `anthropic-version`,
* one user turn `.`, `max_tokens` 1 (a local gateway may raise it to 16), no
Expand Down
23 changes: 11 additions & 12 deletions src/lib/identity/crs-headers.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { applyBetaPolicyToHeader, shouldPassContext1mByPolicy } from '../protocol/model-policy.mjs'
import { CONTEXT_1M_BETA, hasClaudeCode1mSuffix } from '../protocol/context-1m.mjs'
import { atomicWriteJson } from '../vm/vm-file.mjs'
import { OFFICIAL_CLAUDE_CLI_UA, OFFICIAL_STAINLESS } from './vm-identity.mjs'
import { isOfficialClaudeUa } from './official-claude-ua.mjs'

Expand Down Expand Up @@ -184,18 +185,16 @@ function readHeaderFile(homeDir) {
}

function writeHeaderFile(homeDir, headers, extra = {}) {
fs.mkdirSync(path.dirname(headerFile(homeDir)), { recursive: true })
fs.writeFileSync(
headerFile(homeDir),
JSON.stringify(
{
headers,
updated_at: extra.updated_at || new Date().toISOString(),
...extra,
},
null,
2,
),
const file = headerFile(homeDir)
fs.mkdirSync(path.dirname(file), { recursive: true })
atomicWriteJson(
file,
{
headers,
updated_at: extra.updated_at || new Date().toISOString(),
...extra,
},
{ mode: 0o600 },
)
}

Expand Down
4 changes: 2 additions & 2 deletions src/lib/identity/official-profiles.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* Named official presets use 2.1.303. Empty and legacy presets retain 2.1.296.
*/
import { createRequire } from 'node:module'
import { OFFICIAL_SLOT_CWD, officialProjectSlug, sanitizeInboundCwd } from './official-cc-system-2.1.241.mjs'
import { OFFICIAL_303_PRESET, normalizePersonaPreset } from './persona-template.mjs'
import { officialProjectSlug, sanitizeInboundCwd } from './official-cc-system-2.1.241.mjs'
import { OFFICIAL_303_PRESET } from './persona-template.mjs'

const require = createRequire(import.meta.url)
const FIXTURE_303 = require('./official-cc-system-2.1.303.json')
Expand Down
2 changes: 1 addition & 1 deletion src/lib/identity/workstation-fingerprint.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { US_TIMEZONES, validTimezone } from '../core/timezone.mjs'
import { validTimezone } from '../core/timezone.mjs'
import { isValidSlotUsername } from '../vm/slot-identity.mjs'
import { workstationFamily, workstationKernel, workstationSkuId } from './workstation-profile.mjs'

Expand Down
9 changes: 1 addition & 8 deletions src/lib/oauth/auth-scheme.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* Defaults: OAuth / official setup-token → Bearer (Claude Console accepts
* sk-ant-oat01-… this way). Console API key → x-api-key.
*/
import { credentialModeOfVm, normalizeCredentialMode } from './credential-mode.mjs'
import { normalizeCredentialMode } from './credential-mode.mjs'

export const AUTH_SCHEME_X_API_KEY = 'x_api_key'
export const AUTH_SCHEME_BEARER = 'authorization_bearer'
Expand Down Expand Up @@ -41,10 +41,3 @@ export function resolveAuthScheme({ mode, auth_scheme, authScheme, extra } = {})
)
return explicit || defaultAuthScheme(mode)
}

export function authSchemeOfVm(vm = {}) {
return resolveAuthScheme({
mode: credentialModeOfVm(vm),
auth_scheme: vm.auth_scheme || vm.claude?.auth_scheme,
})
}
13 changes: 7 additions & 6 deletions src/lib/oauth/claude-reset-credits.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -295,13 +295,14 @@ function statePath(projectRoot) {
function withFileLock(key, fn) {
const prev = fileLocks.get(key) || Promise.resolve()
const run = prev.then(fn, fn)
fileLocks.set(
key,
run.then(
() => {},
() => {},
),
const settled = run.then(
() => {},
() => {},
)
const tail = settled.finally(() => {
if (fileLocks.get(key) === tail) fileLocks.delete(key)
})
fileLocks.set(key, tail)
return run
}

Expand Down
6 changes: 6 additions & 0 deletions src/lib/oauth/codex-oauth.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { resolveSlotOAuthProxy } from '../vm/proxy-resolve.mjs'

export const CODEX_OAUTH_SESSION_TTL_MS = 10 * 60 * 1000
export const MAX_CODEX_OAUTH_SESSIONS = 1000
const SURFACE_STABLE_ID_DOMAIN = Buffer.from('openai/codex-desktop/surface-stable-id/v1\0')

const sessions = new Map()
Expand Down Expand Up @@ -115,6 +116,11 @@ export function generateCodexAuthUrl({ vmId, proxyUrl, installationId } = {}) {
const sessionId = crypto.randomBytes(16).toString('hex')
const createdAt = Date.now()
const install = String(installationId || crypto.randomUUID())
while (sessions.size >= MAX_CODEX_OAUTH_SESSIONS) {
const oldest = sessions.keys().next().value
if (oldest === undefined) break
sessions.delete(oldest)
}
sessions.set(sessionId, {
state,
codeVerifier,
Expand Down
55 changes: 47 additions & 8 deletions src/lib/oauth/cookie-auth.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
* macOS path is unchanged; auth.js is loaded only by fetch test seams.
*/
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { resolvePackagedBin } from '../vm/vm-file.mjs'
import {
CAI_AUTHORIZE_URL,
Expand Down Expand Up @@ -33,40 +31,81 @@ function serviceFailure(code, message) {
return error
}

const MAX_NATIVE_OAUTH_OUTPUT_BYTES = 1024 * 1024

function runNativeOAuthAuthService(payload) {
const bin = findOAuthAuthBin()
if (!bin) return Promise.reject(serviceFailure('oauth_auth_bin_missing', 'kin-oauth-auth not found'))
const reqTimeout = Number(payload?.timeout_ms)
const timeoutMs =
Number.isFinite(reqTimeout) && reqTimeout > 0
? Math.max(reqTimeout * 9, 120_000)
: Math.max(OAUTH_REQUEST_TIMEOUT_MS * 9, 120_000)
return new Promise((resolve, reject) => {
const child = spawn(bin, [], { env: process.env, stdio: ['pipe', 'pipe', 'pipe'] })
let stdout = ''
let stderr = ''
let outputExceeded = false
let settled = false
const finish = (err, value) => {
if (settled) return
settled = true
clearTimeout(timer)
if (err) reject(err)
else resolve(value)
}
const timer = setTimeout(() => {
try {
child.kill('SIGKILL')
} catch {
/* child already exited */
}
finish(serviceFailure('oauth_auth_timeout', 'Native OAuth helper timed out'))
}, timeoutMs)
timer.unref?.()
child.stdin.on('error', () => {})
child.stdout.on('data', (chunk) => {
if (stdout.length + chunk.length > MAX_NATIVE_OAUTH_OUTPUT_BYTES) {
outputExceeded = true
try {
child.kill('SIGKILL')
} catch {
/* child already exited */
}
finish(serviceFailure('oauth_auth_output_invalid', 'Native OAuth helper exceeded its output limit'))
return
}
stdout += chunk.toString('utf8')
})
child.stderr.on('data', (chunk) => {
stderr += chunk.toString('utf8')
if (stderr.length < MAX_NATIVE_OAUTH_OUTPUT_BYTES) {
stderr += chunk.toString('utf8').slice(0, MAX_NATIVE_OAUTH_OUTPUT_BYTES - stderr.length)
}
})
child.on('error', (error) => reject(serviceFailure('oauth_auth_spawn_failed', error.message)))
child.on('error', (error) => finish(serviceFailure('oauth_auth_spawn_failed', error.message)))
child.on('close', (code) => {
if (outputExceeded) return
const lines = stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
let result = null
try {
result = lines.length ? JSON.parse(lines[lines.length - 1]) : null
} catch {}
} catch {
/* handled by null check below */
}
if (!result || typeof result !== 'object') {
reject(serviceFailure('oauth_auth_output_invalid', stderr.trim().slice(0, 300) || `service exited ${code}`))
finish(serviceFailure('oauth_auth_output_invalid', stderr.trim().slice(0, 300) || `service exited ${code}`))
return
}
if (result.ok !== true) {
reject(
finish(
serviceFailure(result.error?.code || 'oauth_auth_failed', result.error?.message || 'OAuth service failed'),
)
return
}
resolve(result.credential)
finish(null, result.credential)
})
child.stdin.end(JSON.stringify(payload) + '\n')
})
Expand Down
Loading
Loading