claude-codex-proxy 1.0.5-beta.28 → 1.0.5-beta.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/middleware/auth.js +7 -11
- package/src/middleware/credentials.js +4 -4
- package/src/middleware/sse.js +39 -75
- package/src/utils/logger.js +0 -3
package/package.json
CHANGED
package/src/middleware/auth.js
CHANGED
|
@@ -2,6 +2,7 @@ import crypto from 'crypto';
|
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
3
|
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
4
|
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
5
|
+
import { createErrorResponse } from './sse.js';
|
|
5
6
|
|
|
6
7
|
function timingSafeEqualString(a, b) {
|
|
7
8
|
const left = Buffer.from(String(a));
|
|
@@ -36,10 +37,9 @@ function getRequestApiKey(req) {
|
|
|
36
37
|
|
|
37
38
|
function sendUnauthorized(req, res) {
|
|
38
39
|
if (req.path?.startsWith('/v1/')) {
|
|
39
|
-
return res.status(401).json(
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
});
|
|
40
|
+
return res.status(401).json(
|
|
41
|
+
createErrorResponse('authentication_error', 'Invalid API key')
|
|
42
|
+
);
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
@@ -66,13 +66,9 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
function sendQuotaExceeded(res, quota) {
|
|
69
|
-
return res.status(429).json(
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
type: 'rate_limit_error',
|
|
73
|
-
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
-
}
|
|
75
|
-
});
|
|
69
|
+
return res.status(429).json(
|
|
70
|
+
createErrorResponse('rate_limit_error', `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`)
|
|
71
|
+
);
|
|
76
72
|
}
|
|
77
73
|
|
|
78
74
|
function findClientKey(requestKey) {
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
loadAccounts
|
|
13
13
|
} from '../account-manager.js';
|
|
14
14
|
import { logger } from '../utils/logger.js';
|
|
15
|
+
import { createErrorResponse } from './sse.js';
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Resolves the active account credentials, refreshing the token if needed.
|
|
@@ -117,10 +118,9 @@ export async function getCredentialsForAccount(email) {
|
|
|
117
118
|
* @param {string} [message]
|
|
118
119
|
*/
|
|
119
120
|
export function sendAuthError(res, message = 'No active account with valid credentials. Add an account via /accounts/add') {
|
|
120
|
-
return res.status(401).json(
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
});
|
|
121
|
+
return res.status(401).json(
|
|
122
|
+
createErrorResponse('authentication_error', message)
|
|
123
|
+
);
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
export default { getCredentialsOrError, getCredentialsForAccount, sendAuthError };
|
package/src/middleware/sse.js
CHANGED
|
@@ -7,49 +7,34 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
7
7
|
import { formatSSEEvent } from '../response-streamer.js';
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
10
|
+
function createEmptyUsage() {
|
|
11
|
+
return {
|
|
12
|
+
input_tokens: 0,
|
|
13
|
+
output_tokens: 0,
|
|
14
|
+
cache_creation_input_tokens: 0,
|
|
15
|
+
cache_read_input_tokens: 0
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createErrorResponse(errorType, message, extraErrorFields = {}) {
|
|
20
|
+
return {
|
|
21
|
+
type: 'error',
|
|
22
|
+
error: { type: errorType, message, ...extraErrorFields },
|
|
23
|
+
// Claude Code may still read usage on exceptional responses (for example Agent startup failures).
|
|
24
|
+
usage: createEmptyUsage()
|
|
25
|
+
};
|
|
20
26
|
}
|
|
21
27
|
|
|
22
28
|
/**
|
|
23
|
-
* Sets the standard SSE response headers
|
|
29
|
+
* Sets the standard SSE response headers and flushes them.
|
|
24
30
|
* @param {import('express').Response} res
|
|
25
|
-
* @param {number} heartbeatIntervalMs
|
|
26
31
|
*/
|
|
27
|
-
export function initSSEResponse(res
|
|
32
|
+
export function initSSEResponse(res) {
|
|
28
33
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
29
34
|
res.setHeader('Cache-Control', 'no-cache');
|
|
30
35
|
res.setHeader('Connection', 'keep-alive');
|
|
31
36
|
res.setHeader('X-Accel-Buffering', 'no');
|
|
32
37
|
res.flushHeaders();
|
|
33
|
-
|
|
34
|
-
const state = { timer: null, count: 0, lastSentAt: null, writeError: null };
|
|
35
|
-
state.timer = setInterval(() => {
|
|
36
|
-
if (res.destroyed === true || res.socket?.destroyed === true || res.writableEnded === true) {
|
|
37
|
-
stopSSEHeartbeat(res);
|
|
38
|
-
return;
|
|
39
|
-
}
|
|
40
|
-
try {
|
|
41
|
-
// SSE comments keep the transport alive without producing a model event
|
|
42
|
-
// that resets Claude Code's semantic stream-idle watchdog.
|
|
43
|
-
res.write(': keep-alive\n\n');
|
|
44
|
-
state.count++;
|
|
45
|
-
state.lastSentAt = Date.now();
|
|
46
|
-
} catch (error) {
|
|
47
|
-
state.writeError = error instanceof Error ? error.message : String(error);
|
|
48
|
-
stopSSEHeartbeat(res);
|
|
49
|
-
}
|
|
50
|
-
}, heartbeatIntervalMs);
|
|
51
|
-
state.timer.unref?.();
|
|
52
|
-
heartbeatStates.set(res, state);
|
|
53
38
|
}
|
|
54
39
|
|
|
55
40
|
/**
|
|
@@ -62,19 +47,15 @@ export function initSSEResponse(res, heartbeatIntervalMs = SSE_HEARTBEAT_INTERVA
|
|
|
62
47
|
export async function pipeSSEStream(res, eventStream) {
|
|
63
48
|
let usage = null;
|
|
64
49
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
usage = event.data.usage;
|
|
69
|
-
}
|
|
70
|
-
res.write(formatSSEEvent(event));
|
|
50
|
+
for await (const event of eventStream) {
|
|
51
|
+
if (event?.data?.type === 'message_delta' && event.data.usage) {
|
|
52
|
+
usage = event.data.usage;
|
|
71
53
|
}
|
|
72
|
-
res.write(
|
|
73
|
-
res.end();
|
|
74
|
-
return usage;
|
|
75
|
-
} finally {
|
|
76
|
-
stopSSEHeartbeat(res);
|
|
54
|
+
res.write(formatSSEEvent(event));
|
|
77
55
|
}
|
|
56
|
+
res.write('data: [DONE]\n\n');
|
|
57
|
+
res.end();
|
|
58
|
+
return usage;
|
|
78
59
|
}
|
|
79
60
|
|
|
80
61
|
/**
|
|
@@ -94,8 +75,6 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
94
75
|
? resolveModelRouting(model).upstreamModel
|
|
95
76
|
: model;
|
|
96
77
|
const isStreamError = res.headersSent;
|
|
97
|
-
const heartbeatState = heartbeatStates.get(res);
|
|
98
|
-
stopSSEHeartbeat(res);
|
|
99
78
|
const logDetails = {
|
|
100
79
|
model: loggedModel,
|
|
101
80
|
transport: isStreamError ? 'sse' : 'http',
|
|
@@ -106,11 +85,6 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
106
85
|
errorCode: error?.code,
|
|
107
86
|
upstreamStatus: error?.upstreamStatus,
|
|
108
87
|
isUpstreamError: error?.isUpstreamError === true,
|
|
109
|
-
heartbeatCount: heartbeatState?.count ?? 0,
|
|
110
|
-
lastHeartbeatMsAgo: heartbeatState?.lastSentAt === null || heartbeatState?.lastSentAt === undefined
|
|
111
|
-
? undefined
|
|
112
|
-
: Date.now() - heartbeatState.lastSentAt,
|
|
113
|
-
heartbeatWriteError: heartbeatState?.writeError,
|
|
114
88
|
error: error?.message,
|
|
115
89
|
duration
|
|
116
90
|
};
|
|
@@ -122,10 +96,7 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
122
96
|
let sseWriteBackpressure = false;
|
|
123
97
|
if (sseWriteAttempted) {
|
|
124
98
|
sseWriteBackpressure = !res.write(
|
|
125
|
-
`event: error\ndata: ${JSON.stringify(
|
|
126
|
-
type: 'error',
|
|
127
|
-
error: { type: errorType, message: getClientErrorMessage(error) }
|
|
128
|
-
})}\n\n`
|
|
99
|
+
`event: error\ndata: ${JSON.stringify(createErrorResponse(errorType, getClientErrorMessage(error)))}\n\n`
|
|
129
100
|
);
|
|
130
101
|
res.end();
|
|
131
102
|
}
|
|
@@ -136,17 +107,15 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
136
107
|
socketDestroyed,
|
|
137
108
|
writableEnded
|
|
138
109
|
});
|
|
139
|
-
heartbeatStates.delete(res);
|
|
140
110
|
return;
|
|
141
111
|
}
|
|
142
112
|
|
|
143
113
|
logger.response(status, logDetails);
|
|
144
114
|
|
|
145
115
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
146
|
-
return res.status(401).json(
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
});
|
|
116
|
+
return res.status(401).json(
|
|
117
|
+
createErrorResponse('authentication_error', 'Token expired. Please refresh or re-authenticate.')
|
|
118
|
+
);
|
|
150
119
|
}
|
|
151
120
|
|
|
152
121
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -154,28 +123,23 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
154
123
|
const resetMs = parseInt(parts[1], 10);
|
|
155
124
|
const errorText = parts.slice(2).join(':') || error.message;
|
|
156
125
|
|
|
157
|
-
return res.status(429).json(
|
|
158
|
-
|
|
159
|
-
error: {
|
|
160
|
-
type: 'rate_limit_error',
|
|
161
|
-
message: errorText,
|
|
126
|
+
return res.status(429).json(
|
|
127
|
+
createErrorResponse('rate_limit_error', errorText, {
|
|
162
128
|
resetMs: resetMs,
|
|
163
129
|
resetSeconds: Math.round(resetMs / 1000)
|
|
164
|
-
}
|
|
165
|
-
|
|
130
|
+
})
|
|
131
|
+
);
|
|
166
132
|
}
|
|
167
133
|
|
|
168
134
|
if (error.message.includes('RESOURCE_EXHAUSTED')) {
|
|
169
|
-
return res.status(429).json(
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
});
|
|
135
|
+
return res.status(429).json(
|
|
136
|
+
createErrorResponse('rate_limit_error', error.message)
|
|
137
|
+
);
|
|
173
138
|
}
|
|
174
139
|
|
|
175
|
-
res.status(status).json(
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
});
|
|
140
|
+
res.status(status).json(
|
|
141
|
+
createErrorResponse(errorType, getClientErrorMessage(error))
|
|
142
|
+
);
|
|
179
143
|
}
|
|
180
144
|
|
|
181
145
|
function getErrorStatus(error) {
|
package/src/utils/logger.js
CHANGED
|
@@ -186,9 +186,6 @@ class Logger extends EventEmitter {
|
|
|
186
186
|
if (details.sseWriteBackpressure !== undefined) parts.push(`sse_write_backpressure=${details.sseWriteBackpressure}`);
|
|
187
187
|
if (details.socketDestroyed !== undefined) parts.push(`socket_destroyed=${details.socketDestroyed}`);
|
|
188
188
|
if (details.writableEnded !== undefined) parts.push(`writable_ended=${details.writableEnded}`);
|
|
189
|
-
if (details.heartbeatCount !== undefined) parts.push(`heartbeat_count=${details.heartbeatCount}`);
|
|
190
|
-
if (details.lastHeartbeatMsAgo !== undefined) parts.push(`last_heartbeat_ms_ago=${details.lastHeartbeatMsAgo}`);
|
|
191
|
-
if (details.heartbeatWriteError) parts.push(`heartbeat_write_error=${details.heartbeatWriteError}`);
|
|
192
189
|
if (details.duration) parts.push(`${details.duration}ms`);
|
|
193
190
|
if (details.error) parts.push(`error=${details.error}`);
|
|
194
191
|
|