claude-codex-proxy 1.0.5-beta.27 → 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 -73
- 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,47 +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
|
-
res.write('event: ping\ndata: {"type":"ping"}\n\n');
|
|
42
|
-
state.count++;
|
|
43
|
-
state.lastSentAt = Date.now();
|
|
44
|
-
} catch (error) {
|
|
45
|
-
state.writeError = error instanceof Error ? error.message : String(error);
|
|
46
|
-
stopSSEHeartbeat(res);
|
|
47
|
-
}
|
|
48
|
-
}, heartbeatIntervalMs);
|
|
49
|
-
state.timer.unref?.();
|
|
50
|
-
heartbeatStates.set(res, state);
|
|
51
38
|
}
|
|
52
39
|
|
|
53
40
|
/**
|
|
@@ -60,19 +47,15 @@ export function initSSEResponse(res, heartbeatIntervalMs = SSE_HEARTBEAT_INTERVA
|
|
|
60
47
|
export async function pipeSSEStream(res, eventStream) {
|
|
61
48
|
let usage = null;
|
|
62
49
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
usage = event.data.usage;
|
|
67
|
-
}
|
|
68
|
-
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;
|
|
69
53
|
}
|
|
70
|
-
res.write(
|
|
71
|
-
res.end();
|
|
72
|
-
return usage;
|
|
73
|
-
} finally {
|
|
74
|
-
stopSSEHeartbeat(res);
|
|
54
|
+
res.write(formatSSEEvent(event));
|
|
75
55
|
}
|
|
56
|
+
res.write('data: [DONE]\n\n');
|
|
57
|
+
res.end();
|
|
58
|
+
return usage;
|
|
76
59
|
}
|
|
77
60
|
|
|
78
61
|
/**
|
|
@@ -92,8 +75,6 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
92
75
|
? resolveModelRouting(model).upstreamModel
|
|
93
76
|
: model;
|
|
94
77
|
const isStreamError = res.headersSent;
|
|
95
|
-
const heartbeatState = heartbeatStates.get(res);
|
|
96
|
-
stopSSEHeartbeat(res);
|
|
97
78
|
const logDetails = {
|
|
98
79
|
model: loggedModel,
|
|
99
80
|
transport: isStreamError ? 'sse' : 'http',
|
|
@@ -104,11 +85,6 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
104
85
|
errorCode: error?.code,
|
|
105
86
|
upstreamStatus: error?.upstreamStatus,
|
|
106
87
|
isUpstreamError: error?.isUpstreamError === true,
|
|
107
|
-
heartbeatCount: heartbeatState?.count ?? 0,
|
|
108
|
-
lastHeartbeatMsAgo: heartbeatState?.lastSentAt === null || heartbeatState?.lastSentAt === undefined
|
|
109
|
-
? undefined
|
|
110
|
-
: Date.now() - heartbeatState.lastSentAt,
|
|
111
|
-
heartbeatWriteError: heartbeatState?.writeError,
|
|
112
88
|
error: error?.message,
|
|
113
89
|
duration
|
|
114
90
|
};
|
|
@@ -120,10 +96,7 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
120
96
|
let sseWriteBackpressure = false;
|
|
121
97
|
if (sseWriteAttempted) {
|
|
122
98
|
sseWriteBackpressure = !res.write(
|
|
123
|
-
`event: error\ndata: ${JSON.stringify(
|
|
124
|
-
type: 'error',
|
|
125
|
-
error: { type: errorType, message: getClientErrorMessage(error) }
|
|
126
|
-
})}\n\n`
|
|
99
|
+
`event: error\ndata: ${JSON.stringify(createErrorResponse(errorType, getClientErrorMessage(error)))}\n\n`
|
|
127
100
|
);
|
|
128
101
|
res.end();
|
|
129
102
|
}
|
|
@@ -134,17 +107,15 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
134
107
|
socketDestroyed,
|
|
135
108
|
writableEnded
|
|
136
109
|
});
|
|
137
|
-
heartbeatStates.delete(res);
|
|
138
110
|
return;
|
|
139
111
|
}
|
|
140
112
|
|
|
141
113
|
logger.response(status, logDetails);
|
|
142
114
|
|
|
143
115
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
144
|
-
return res.status(401).json(
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
});
|
|
116
|
+
return res.status(401).json(
|
|
117
|
+
createErrorResponse('authentication_error', 'Token expired. Please refresh or re-authenticate.')
|
|
118
|
+
);
|
|
148
119
|
}
|
|
149
120
|
|
|
150
121
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -152,28 +123,23 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
152
123
|
const resetMs = parseInt(parts[1], 10);
|
|
153
124
|
const errorText = parts.slice(2).join(':') || error.message;
|
|
154
125
|
|
|
155
|
-
return res.status(429).json(
|
|
156
|
-
|
|
157
|
-
error: {
|
|
158
|
-
type: 'rate_limit_error',
|
|
159
|
-
message: errorText,
|
|
126
|
+
return res.status(429).json(
|
|
127
|
+
createErrorResponse('rate_limit_error', errorText, {
|
|
160
128
|
resetMs: resetMs,
|
|
161
129
|
resetSeconds: Math.round(resetMs / 1000)
|
|
162
|
-
}
|
|
163
|
-
|
|
130
|
+
})
|
|
131
|
+
);
|
|
164
132
|
}
|
|
165
133
|
|
|
166
134
|
if (error.message.includes('RESOURCE_EXHAUSTED')) {
|
|
167
|
-
return res.status(429).json(
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
});
|
|
135
|
+
return res.status(429).json(
|
|
136
|
+
createErrorResponse('rate_limit_error', error.message)
|
|
137
|
+
);
|
|
171
138
|
}
|
|
172
139
|
|
|
173
|
-
res.status(status).json(
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
});
|
|
140
|
+
res.status(status).json(
|
|
141
|
+
createErrorResponse(errorType, getClientErrorMessage(error))
|
|
142
|
+
);
|
|
177
143
|
}
|
|
178
144
|
|
|
179
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
|
|