@certalis/agent-smith 0.1.12 → 0.1.13
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/README.md +5 -0
- package/dist/bin.js +124 -113
- package/dist/edge.js +24 -10
- package/dist/https.js +28 -11
- package/dist/pool.js +124 -113
- package/dist/server.js +124 -113
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -96,6 +96,11 @@ key; provider tokens and the single database stay on the server.
|
|
|
96
96
|
Device keys allow independent revocation and cannot read management data.
|
|
97
97
|
This does not add per-client fairness or budgets.
|
|
98
98
|
|
|
99
|
+
Seat owners join through the server's optional `/pool-enroll` page, not its
|
|
100
|
+
proxy homepage. Enable the existing email-listed sign-in flow with
|
|
101
|
+
`AGENT_SMITH_ENROLLMENT_ORIGIN` as described in the
|
|
102
|
+
[HTTPS deployment guide](docs/https-edge.md#standalone-render-web-service).
|
|
103
|
+
|
|
99
104
|
Copy [`https-client.json`](examples/config/https-client.json) into your private
|
|
100
105
|
Agent Smith config. Put the device key in the owner-only file named by
|
|
101
106
|
`proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
|
package/dist/bin.js
CHANGED
|
@@ -8467,6 +8467,118 @@ var init_team_router = __esm(() => {
|
|
|
8467
8467
|
PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8468
8468
|
});
|
|
8469
8469
|
|
|
8470
|
+
// ../../packages/proxy/src/constants.ts
|
|
8471
|
+
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8472
|
+
var init_constants2 = __esm(() => {
|
|
8473
|
+
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8474
|
+
});
|
|
8475
|
+
|
|
8476
|
+
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8477
|
+
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8478
|
+
return {
|
|
8479
|
+
...ctx,
|
|
8480
|
+
provider,
|
|
8481
|
+
providerName: provider.name,
|
|
8482
|
+
upstreamPath
|
|
8483
|
+
};
|
|
8484
|
+
}
|
|
8485
|
+
function resolveProxyContext(url, ctx) {
|
|
8486
|
+
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8487
|
+
if (!resolvedProvider) {
|
|
8488
|
+
return null;
|
|
8489
|
+
}
|
|
8490
|
+
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8491
|
+
}
|
|
8492
|
+
var ERROR_MESSAGES, TIMING;
|
|
8493
|
+
var init_proxy_types = __esm(() => {
|
|
8494
|
+
ERROR_MESSAGES = {
|
|
8495
|
+
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8496
|
+
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8497
|
+
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8498
|
+
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8499
|
+
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8500
|
+
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8501
|
+
};
|
|
8502
|
+
TIMING = {
|
|
8503
|
+
WORKER_SHUTDOWN_DELAY: 5000
|
|
8504
|
+
};
|
|
8505
|
+
});
|
|
8506
|
+
|
|
8507
|
+
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8508
|
+
function refreshBackoffUntil(accountId, now = Date.now()) {
|
|
8509
|
+
const failure = refreshFailures.get(accountId);
|
|
8510
|
+
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8511
|
+
}
|
|
8512
|
+
function quarantineAccount(account2, ctx, reason) {
|
|
8513
|
+
account2.paused = true;
|
|
8514
|
+
account2.error_reason = reason;
|
|
8515
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
8516
|
+
}
|
|
8517
|
+
function recordRefreshFailure(account2, ctx, error) {
|
|
8518
|
+
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8519
|
+
refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
|
|
8520
|
+
const status = error?.status;
|
|
8521
|
+
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8522
|
+
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
8523
|
+
}
|
|
8524
|
+
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8525
|
+
return refreshError;
|
|
8526
|
+
}
|
|
8527
|
+
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8528
|
+
const lastFailure = refreshFailures.get(account2.id);
|
|
8529
|
+
if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
|
|
8530
|
+
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8531
|
+
throw lastFailure.error;
|
|
8532
|
+
}
|
|
8533
|
+
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8534
|
+
if (!ctx.provider.refreshToken) {
|
|
8535
|
+
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8536
|
+
}
|
|
8537
|
+
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8538
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8539
|
+
account2.access_token = result.accessToken;
|
|
8540
|
+
account2.expires_at = result.expiresAt;
|
|
8541
|
+
if (result.refreshToken) {
|
|
8542
|
+
account2.refresh_token = result.refreshToken;
|
|
8543
|
+
}
|
|
8544
|
+
account2.last_used = Date.now();
|
|
8545
|
+
refreshFailures.delete(account2.id);
|
|
8546
|
+
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8547
|
+
return result.accessToken;
|
|
8548
|
+
}).catch((error) => {
|
|
8549
|
+
throw recordRefreshFailure(account2, ctx, error);
|
|
8550
|
+
}).finally(() => {
|
|
8551
|
+
ctx.refreshInFlight.delete(account2.id);
|
|
8552
|
+
});
|
|
8553
|
+
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8554
|
+
}
|
|
8555
|
+
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8556
|
+
if (!promise) {
|
|
8557
|
+
throw new TokenRefreshError(account2.id, new Error(ERROR_MESSAGES.REFRESH_NOT_FOUND));
|
|
8558
|
+
}
|
|
8559
|
+
return promise;
|
|
8560
|
+
}
|
|
8561
|
+
async function getValidAccessToken(account2, ctx) {
|
|
8562
|
+
if (!account2.refresh_token && account2.api_key) {
|
|
8563
|
+
return "";
|
|
8564
|
+
}
|
|
8565
|
+
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8566
|
+
return account2.access_token;
|
|
8567
|
+
}
|
|
8568
|
+
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8569
|
+
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8570
|
+
return await refreshAccessTokenSafe(account2, ctx);
|
|
8571
|
+
}
|
|
8572
|
+
var log18, refreshFailures;
|
|
8573
|
+
var init_token_manager = __esm(() => {
|
|
8574
|
+
init_src2();
|
|
8575
|
+
init_src3();
|
|
8576
|
+
init_constants2();
|
|
8577
|
+
init_proxy_types();
|
|
8578
|
+
log18 = new Logger("TokenManager");
|
|
8579
|
+
refreshFailures = new Map;
|
|
8580
|
+
});
|
|
8581
|
+
|
|
8470
8582
|
// ../../packages/proxy/src/handlers/account-selector.ts
|
|
8471
8583
|
function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
|
|
8472
8584
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
@@ -8492,7 +8604,9 @@ function fleetAccounts(provider, ctx) {
|
|
|
8492
8604
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
|
|
8493
8605
|
}
|
|
8494
8606
|
function cooldownEnd(account2, now) {
|
|
8495
|
-
|
|
8607
|
+
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8608
|
+
const refreshEnd = refreshBackoffUntil(account2.id, now);
|
|
8609
|
+
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8496
8610
|
}
|
|
8497
8611
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8498
8612
|
return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
|
|
@@ -8555,8 +8669,8 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8555
8669
|
return [probe];
|
|
8556
8670
|
}
|
|
8557
8671
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8558
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
|
|
8559
8672
|
const now = Date.now();
|
|
8673
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
|
|
8560
8674
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8561
8675
|
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
8562
8676
|
const prioritized = [...candidates].sort((left, right) => {
|
|
@@ -8574,6 +8688,7 @@ var init_account_selector = __esm(() => {
|
|
|
8574
8688
|
init_src();
|
|
8575
8689
|
init_seat_usage();
|
|
8576
8690
|
init_team_router();
|
|
8691
|
+
init_token_manager();
|
|
8577
8692
|
});
|
|
8578
8693
|
|
|
8579
8694
|
// ../../packages/proxy/src/handlers/request-handler.ts
|
|
@@ -8665,101 +8780,6 @@ var init_request_handler = __esm(() => {
|
|
|
8665
8780
|
DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
8666
8781
|
});
|
|
8667
8782
|
|
|
8668
|
-
// ../../packages/proxy/src/constants.ts
|
|
8669
|
-
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8670
|
-
var init_constants2 = __esm(() => {
|
|
8671
|
-
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8672
|
-
});
|
|
8673
|
-
|
|
8674
|
-
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8675
|
-
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8676
|
-
return {
|
|
8677
|
-
...ctx,
|
|
8678
|
-
provider,
|
|
8679
|
-
providerName: provider.name,
|
|
8680
|
-
upstreamPath
|
|
8681
|
-
};
|
|
8682
|
-
}
|
|
8683
|
-
function resolveProxyContext(url, ctx) {
|
|
8684
|
-
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8685
|
-
if (!resolvedProvider) {
|
|
8686
|
-
return null;
|
|
8687
|
-
}
|
|
8688
|
-
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8689
|
-
}
|
|
8690
|
-
var ERROR_MESSAGES, TIMING;
|
|
8691
|
-
var init_proxy_types = __esm(() => {
|
|
8692
|
-
ERROR_MESSAGES = {
|
|
8693
|
-
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8694
|
-
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8695
|
-
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8696
|
-
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8697
|
-
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8698
|
-
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8699
|
-
};
|
|
8700
|
-
TIMING = {
|
|
8701
|
-
WORKER_SHUTDOWN_DELAY: 5000
|
|
8702
|
-
};
|
|
8703
|
-
});
|
|
8704
|
-
|
|
8705
|
-
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8706
|
-
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8707
|
-
const lastFailure = refreshFailures.get(account2.id);
|
|
8708
|
-
if (lastFailure && Date.now() - lastFailure < TOKEN_REFRESH_BACKOFF_MS) {
|
|
8709
|
-
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8710
|
-
throw new ServiceUnavailableError(`Token refresh for account ${account2.name} is in backoff period after recent failure`);
|
|
8711
|
-
}
|
|
8712
|
-
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8713
|
-
if (!ctx.provider.refreshToken) {
|
|
8714
|
-
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8715
|
-
}
|
|
8716
|
-
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8717
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8718
|
-
account2.access_token = result.accessToken;
|
|
8719
|
-
account2.expires_at = result.expiresAt;
|
|
8720
|
-
if (result.refreshToken) {
|
|
8721
|
-
account2.refresh_token = result.refreshToken;
|
|
8722
|
-
}
|
|
8723
|
-
account2.last_used = Date.now();
|
|
8724
|
-
refreshFailures.delete(account2.id);
|
|
8725
|
-
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8726
|
-
return result.accessToken;
|
|
8727
|
-
}).catch((error) => {
|
|
8728
|
-
refreshFailures.set(account2.id, Date.now());
|
|
8729
|
-
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8730
|
-
throw new TokenRefreshError(account2.id, error);
|
|
8731
|
-
}).finally(() => {
|
|
8732
|
-
ctx.refreshInFlight.delete(account2.id);
|
|
8733
|
-
});
|
|
8734
|
-
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8735
|
-
}
|
|
8736
|
-
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8737
|
-
if (!promise) {
|
|
8738
|
-
throw new ServiceUnavailableError(`${ERROR_MESSAGES.REFRESH_NOT_FOUND} ${account2.id}`);
|
|
8739
|
-
}
|
|
8740
|
-
return promise;
|
|
8741
|
-
}
|
|
8742
|
-
async function getValidAccessToken(account2, ctx) {
|
|
8743
|
-
if (!account2.refresh_token && account2.api_key) {
|
|
8744
|
-
return "";
|
|
8745
|
-
}
|
|
8746
|
-
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8747
|
-
return account2.access_token;
|
|
8748
|
-
}
|
|
8749
|
-
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8750
|
-
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8751
|
-
return await refreshAccessTokenSafe(account2, ctx);
|
|
8752
|
-
}
|
|
8753
|
-
var log18, refreshFailures;
|
|
8754
|
-
var init_token_manager = __esm(() => {
|
|
8755
|
-
init_src2();
|
|
8756
|
-
init_src3();
|
|
8757
|
-
init_constants2();
|
|
8758
|
-
init_proxy_types();
|
|
8759
|
-
log18 = new Logger("TokenManager");
|
|
8760
|
-
refreshFailures = new Map;
|
|
8761
|
-
});
|
|
8762
|
-
|
|
8763
8783
|
// ../../packages/proxy/src/outside-spend.ts
|
|
8764
8784
|
class OutsideSpendTracker {
|
|
8765
8785
|
now;
|
|
@@ -8969,7 +8989,12 @@ class TeamAdmission {
|
|
|
8969
8989
|
holdSeconds: 0,
|
|
8970
8990
|
quotaProbeSeconds: 0
|
|
8971
8991
|
});
|
|
8972
|
-
account2.
|
|
8992
|
+
if (account2.active > 0 || account2.queue.length > 0)
|
|
8993
|
+
return;
|
|
8994
|
+
const now = this.now();
|
|
8995
|
+
if (account2.switchedAt === undefined || now - account2.switchedAt >= RAMP_WINDOW_MS) {
|
|
8996
|
+
account2.switchedAt = now;
|
|
8997
|
+
}
|
|
8973
8998
|
this.scheduleRamp(accountId, account2);
|
|
8974
8999
|
}
|
|
8975
9000
|
advance() {
|
|
@@ -9661,17 +9686,6 @@ var init_stream_failure = __esm(() => {
|
|
|
9661
9686
|
});
|
|
9662
9687
|
|
|
9663
9688
|
// ../../packages/proxy/src/handlers/proxy-operations.ts
|
|
9664
|
-
function shouldQuarantineAfterRefreshFailure(error) {
|
|
9665
|
-
if (!(error instanceof TokenRefreshError))
|
|
9666
|
-
return false;
|
|
9667
|
-
const status = error.originalError?.status;
|
|
9668
|
-
return typeof status === "number" && status >= 400 && status < 500;
|
|
9669
|
-
}
|
|
9670
|
-
function quarantineAccount(account2, ctx, reason) {
|
|
9671
|
-
account2.paused = true;
|
|
9672
|
-
account2.error_reason = reason;
|
|
9673
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
9674
|
-
}
|
|
9675
9689
|
function createUpstreamSender(input) {
|
|
9676
9690
|
const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
|
|
9677
9691
|
return async (token) => {
|
|
@@ -9704,10 +9718,7 @@ async function sendAuthorizedRequest(input, send) {
|
|
|
9704
9718
|
try {
|
|
9705
9719
|
accessToken = await refreshAccessTokenSafe(input.account, input.ctx);
|
|
9706
9720
|
upstream = await send(accessToken);
|
|
9707
|
-
} catch
|
|
9708
|
-
if (shouldQuarantineAfterRefreshFailure(error)) {
|
|
9709
|
-
quarantineAccount(input.account, input.ctx, "OAuth refresh was rejected by the upstream");
|
|
9710
|
-
}
|
|
9721
|
+
} catch {
|
|
9711
9722
|
return { kind: "failed" };
|
|
9712
9723
|
}
|
|
9713
9724
|
return upstream.response.status === 401 ? { kind: "authentication-failure" } : upstream;
|
package/dist/edge.js
CHANGED
|
@@ -48,35 +48,45 @@ var RESPONSE_HEADERS = [
|
|
|
48
48
|
"anthropic-ratelimit-requests-reset",
|
|
49
49
|
"anthropic-ratelimit-tokens-limit",
|
|
50
50
|
"anthropic-ratelimit-tokens-remaining",
|
|
51
|
-
"anthropic-ratelimit-tokens-reset"
|
|
51
|
+
"anthropic-ratelimit-tokens-reset",
|
|
52
|
+
"content-security-policy",
|
|
53
|
+
"referrer-policy",
|
|
54
|
+
"x-frame-options"
|
|
52
55
|
];
|
|
56
|
+
function isEnrollmentRoute(method, path) {
|
|
57
|
+
return method === "GET" && path === "/pool-enroll" || method === "POST" && ["request", "start", "verify", "confirm", "disconnect"].some((action) => path === `/pool-enroll/${action}`);
|
|
58
|
+
}
|
|
53
59
|
function selectHeaders(headers, names) {
|
|
54
60
|
return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
|
|
55
61
|
}
|
|
56
|
-
function requestFailure(req, origin, maxBodyBytes) {
|
|
62
|
+
function requestFailure(req, origin, maxBodyBytes, enrollment) {
|
|
57
63
|
const health = req.method === "GET" && req.url === "/pool-health";
|
|
58
|
-
if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
|
|
64
|
+
if (!enrollment && !health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
|
|
59
65
|
return 404;
|
|
60
|
-
if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
|
|
66
|
+
if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !(enrollment && req.method === "GET") && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
|
|
61
67
|
return 403;
|
|
62
68
|
if (req.headers.upgrade || req.headers.expect)
|
|
63
69
|
return 400;
|
|
64
70
|
if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
|
|
65
71
|
return 413;
|
|
66
|
-
if (
|
|
72
|
+
if (enrollment) {
|
|
73
|
+
if (req.method === "POST" && req.headers.origin !== origin)
|
|
74
|
+
return 403;
|
|
75
|
+
} else if (!req.headers["x-api-key"] && !req.headers.authorization)
|
|
67
76
|
return 401;
|
|
68
77
|
return null;
|
|
69
78
|
}
|
|
70
79
|
function createProxyEdgeHandler({
|
|
71
80
|
origin,
|
|
72
81
|
socketPath,
|
|
82
|
+
enrollmentOrigin,
|
|
73
83
|
maxBodyBytes = 64 * 1024 * 1024,
|
|
74
84
|
timeoutMs = 300000,
|
|
75
85
|
maxConcurrentRequests = 128
|
|
76
86
|
}) {
|
|
77
87
|
const url = new URL(origin);
|
|
78
|
-
if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
|
|
79
|
-
throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
|
|
88
|
+
if (url.protocol !== "https:" || url.origin !== origin || enrollmentOrigin !== undefined && enrollmentOrigin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
|
|
89
|
+
throw new Error("Proxy edge requires an exact HTTPS origin, a matching enrollment origin, an absolute socket path and positive limits");
|
|
80
90
|
}
|
|
81
91
|
let activeRequests = 0;
|
|
82
92
|
return (req, res) => {
|
|
@@ -93,7 +103,9 @@ function createProxyEdgeHandler({
|
|
|
93
103
|
});
|
|
94
104
|
res.end();
|
|
95
105
|
};
|
|
96
|
-
const
|
|
106
|
+
const enrollment = enrollmentOrigin !== undefined && isEnrollmentRoute(req.method ?? "", req.url ?? "");
|
|
107
|
+
const bodyLimit = enrollment ? Math.min(maxBodyBytes, 8192) : maxBodyBytes;
|
|
108
|
+
const rejected = requestFailure(req, origin, bodyLimit, enrollment);
|
|
97
109
|
if (rejected)
|
|
98
110
|
return finish(rejected);
|
|
99
111
|
if (activeRequests >= maxConcurrentRequests)
|
|
@@ -101,7 +113,9 @@ function createProxyEdgeHandler({
|
|
|
101
113
|
activeRequests++;
|
|
102
114
|
const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
|
|
103
115
|
const headers = selectHeaders(req.headers, REQUEST_HEADERS);
|
|
104
|
-
headers.host = "localhost";
|
|
116
|
+
headers.host = enrollment ? url.host : "localhost";
|
|
117
|
+
if (enrollment && req.headers.origin)
|
|
118
|
+
headers.origin = req.headers.origin;
|
|
105
119
|
headers.connection = "keep-alive";
|
|
106
120
|
headers["x-forwarded-for"] = "proxy-edge";
|
|
107
121
|
let upstreamResponse;
|
|
@@ -146,7 +160,7 @@ function createProxyEdgeHandler({
|
|
|
146
160
|
let bytes = 0;
|
|
147
161
|
req.on("data", (chunk) => {
|
|
148
162
|
bytes += chunk.length;
|
|
149
|
-
if (bytes >
|
|
163
|
+
if (bytes > bodyLimit) {
|
|
150
164
|
req.unpipe(upstream);
|
|
151
165
|
upstream.destroy();
|
|
152
166
|
finish(413);
|
package/dist/https.js
CHANGED
|
@@ -142,35 +142,45 @@ var RESPONSE_HEADERS = [
|
|
|
142
142
|
"anthropic-ratelimit-requests-reset",
|
|
143
143
|
"anthropic-ratelimit-tokens-limit",
|
|
144
144
|
"anthropic-ratelimit-tokens-remaining",
|
|
145
|
-
"anthropic-ratelimit-tokens-reset"
|
|
145
|
+
"anthropic-ratelimit-tokens-reset",
|
|
146
|
+
"content-security-policy",
|
|
147
|
+
"referrer-policy",
|
|
148
|
+
"x-frame-options"
|
|
146
149
|
];
|
|
150
|
+
function isEnrollmentRoute(method, path) {
|
|
151
|
+
return method === "GET" && path === "/pool-enroll" || method === "POST" && ["request", "start", "verify", "confirm", "disconnect"].some((action) => path === `/pool-enroll/${action}`);
|
|
152
|
+
}
|
|
147
153
|
function selectHeaders(headers, names) {
|
|
148
154
|
return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
|
|
149
155
|
}
|
|
150
|
-
function requestFailure(req, origin, maxBodyBytes) {
|
|
156
|
+
function requestFailure(req, origin, maxBodyBytes, enrollment) {
|
|
151
157
|
const health = req.method === "GET" && req.url === "/pool-health";
|
|
152
|
-
if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
|
|
158
|
+
if (!enrollment && !health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
|
|
153
159
|
return 404;
|
|
154
|
-
if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
|
|
160
|
+
if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !(enrollment && req.method === "GET") && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
|
|
155
161
|
return 403;
|
|
156
162
|
if (req.headers.upgrade || req.headers.expect)
|
|
157
163
|
return 400;
|
|
158
164
|
if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
|
|
159
165
|
return 413;
|
|
160
|
-
if (
|
|
166
|
+
if (enrollment) {
|
|
167
|
+
if (req.method === "POST" && req.headers.origin !== origin)
|
|
168
|
+
return 403;
|
|
169
|
+
} else if (!req.headers["x-api-key"] && !req.headers.authorization)
|
|
161
170
|
return 401;
|
|
162
171
|
return null;
|
|
163
172
|
}
|
|
164
173
|
function createProxyEdgeHandler({
|
|
165
174
|
origin,
|
|
166
175
|
socketPath,
|
|
176
|
+
enrollmentOrigin,
|
|
167
177
|
maxBodyBytes = 64 * 1024 * 1024,
|
|
168
178
|
timeoutMs = 300000,
|
|
169
179
|
maxConcurrentRequests = 128
|
|
170
180
|
}) {
|
|
171
181
|
const url = new URL(origin);
|
|
172
|
-
if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute2(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
|
|
173
|
-
throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
|
|
182
|
+
if (url.protocol !== "https:" || url.origin !== origin || enrollmentOrigin !== undefined && enrollmentOrigin !== origin || !isAbsolute2(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
|
|
183
|
+
throw new Error("Proxy edge requires an exact HTTPS origin, a matching enrollment origin, an absolute socket path and positive limits");
|
|
174
184
|
}
|
|
175
185
|
let activeRequests = 0;
|
|
176
186
|
return (req, res) => {
|
|
@@ -187,7 +197,9 @@ function createProxyEdgeHandler({
|
|
|
187
197
|
});
|
|
188
198
|
res.end();
|
|
189
199
|
};
|
|
190
|
-
const
|
|
200
|
+
const enrollment = enrollmentOrigin !== undefined && isEnrollmentRoute(req.method ?? "", req.url ?? "");
|
|
201
|
+
const bodyLimit = enrollment ? Math.min(maxBodyBytes, 8192) : maxBodyBytes;
|
|
202
|
+
const rejected = requestFailure(req, origin, bodyLimit, enrollment);
|
|
191
203
|
if (rejected)
|
|
192
204
|
return finish(rejected);
|
|
193
205
|
if (activeRequests >= maxConcurrentRequests)
|
|
@@ -195,7 +207,9 @@ function createProxyEdgeHandler({
|
|
|
195
207
|
activeRequests++;
|
|
196
208
|
const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
|
|
197
209
|
const headers = selectHeaders(req.headers, REQUEST_HEADERS);
|
|
198
|
-
headers.host = "localhost";
|
|
210
|
+
headers.host = enrollment ? url.host : "localhost";
|
|
211
|
+
if (enrollment && req.headers.origin)
|
|
212
|
+
headers.origin = req.headers.origin;
|
|
199
213
|
headers.connection = "keep-alive";
|
|
200
214
|
headers["x-forwarded-for"] = "proxy-edge";
|
|
201
215
|
let upstreamResponse;
|
|
@@ -240,7 +254,7 @@ function createProxyEdgeHandler({
|
|
|
240
254
|
let bytes = 0;
|
|
241
255
|
req.on("data", (chunk) => {
|
|
242
256
|
bytes += chunk.length;
|
|
243
|
-
if (bytes >
|
|
257
|
+
if (bytes > bodyLimit) {
|
|
244
258
|
req.unpipe(upstream);
|
|
245
259
|
upstream.destroy();
|
|
246
260
|
finish(413);
|
|
@@ -319,7 +333,10 @@ async function prepareStandaloneState(options) {
|
|
|
319
333
|
async function startStandalone(options, poolEntry, env = process.env) {
|
|
320
334
|
process.umask(63);
|
|
321
335
|
await prepareStandaloneState(options);
|
|
322
|
-
const edge = createProxyEdgeHandler(
|
|
336
|
+
const edge = createProxyEdgeHandler({
|
|
337
|
+
...options,
|
|
338
|
+
enrollmentOrigin: env.AGENT_SMITH_ENROLLMENT_ORIGIN
|
|
339
|
+
});
|
|
323
340
|
const server = createServer((req, res) => {
|
|
324
341
|
if (req.method === "GET" && req.url === "/readyz" && req.headers.host === new URL(options.origin).host) {
|
|
325
342
|
res.writeHead(200, {
|
package/dist/pool.js
CHANGED
|
@@ -8466,6 +8466,118 @@ var init_team_router = __esm(() => {
|
|
|
8466
8466
|
PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8467
8467
|
});
|
|
8468
8468
|
|
|
8469
|
+
// ../../packages/proxy/src/constants.ts
|
|
8470
|
+
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8471
|
+
var init_constants2 = __esm(() => {
|
|
8472
|
+
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8473
|
+
});
|
|
8474
|
+
|
|
8475
|
+
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8476
|
+
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8477
|
+
return {
|
|
8478
|
+
...ctx,
|
|
8479
|
+
provider,
|
|
8480
|
+
providerName: provider.name,
|
|
8481
|
+
upstreamPath
|
|
8482
|
+
};
|
|
8483
|
+
}
|
|
8484
|
+
function resolveProxyContext(url, ctx) {
|
|
8485
|
+
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8486
|
+
if (!resolvedProvider) {
|
|
8487
|
+
return null;
|
|
8488
|
+
}
|
|
8489
|
+
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8490
|
+
}
|
|
8491
|
+
var ERROR_MESSAGES, TIMING;
|
|
8492
|
+
var init_proxy_types = __esm(() => {
|
|
8493
|
+
ERROR_MESSAGES = {
|
|
8494
|
+
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8495
|
+
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8496
|
+
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8497
|
+
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8498
|
+
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8499
|
+
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8500
|
+
};
|
|
8501
|
+
TIMING = {
|
|
8502
|
+
WORKER_SHUTDOWN_DELAY: 5000
|
|
8503
|
+
};
|
|
8504
|
+
});
|
|
8505
|
+
|
|
8506
|
+
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8507
|
+
function refreshBackoffUntil(accountId, now = Date.now()) {
|
|
8508
|
+
const failure = refreshFailures.get(accountId);
|
|
8509
|
+
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8510
|
+
}
|
|
8511
|
+
function quarantineAccount(account2, ctx, reason) {
|
|
8512
|
+
account2.paused = true;
|
|
8513
|
+
account2.error_reason = reason;
|
|
8514
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
8515
|
+
}
|
|
8516
|
+
function recordRefreshFailure(account2, ctx, error) {
|
|
8517
|
+
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8518
|
+
refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
|
|
8519
|
+
const status = error?.status;
|
|
8520
|
+
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8521
|
+
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
8522
|
+
}
|
|
8523
|
+
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8524
|
+
return refreshError;
|
|
8525
|
+
}
|
|
8526
|
+
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8527
|
+
const lastFailure = refreshFailures.get(account2.id);
|
|
8528
|
+
if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
|
|
8529
|
+
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8530
|
+
throw lastFailure.error;
|
|
8531
|
+
}
|
|
8532
|
+
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8533
|
+
if (!ctx.provider.refreshToken) {
|
|
8534
|
+
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8535
|
+
}
|
|
8536
|
+
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8537
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8538
|
+
account2.access_token = result.accessToken;
|
|
8539
|
+
account2.expires_at = result.expiresAt;
|
|
8540
|
+
if (result.refreshToken) {
|
|
8541
|
+
account2.refresh_token = result.refreshToken;
|
|
8542
|
+
}
|
|
8543
|
+
account2.last_used = Date.now();
|
|
8544
|
+
refreshFailures.delete(account2.id);
|
|
8545
|
+
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8546
|
+
return result.accessToken;
|
|
8547
|
+
}).catch((error) => {
|
|
8548
|
+
throw recordRefreshFailure(account2, ctx, error);
|
|
8549
|
+
}).finally(() => {
|
|
8550
|
+
ctx.refreshInFlight.delete(account2.id);
|
|
8551
|
+
});
|
|
8552
|
+
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8553
|
+
}
|
|
8554
|
+
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8555
|
+
if (!promise) {
|
|
8556
|
+
throw new TokenRefreshError(account2.id, new Error(ERROR_MESSAGES.REFRESH_NOT_FOUND));
|
|
8557
|
+
}
|
|
8558
|
+
return promise;
|
|
8559
|
+
}
|
|
8560
|
+
async function getValidAccessToken(account2, ctx) {
|
|
8561
|
+
if (!account2.refresh_token && account2.api_key) {
|
|
8562
|
+
return "";
|
|
8563
|
+
}
|
|
8564
|
+
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8565
|
+
return account2.access_token;
|
|
8566
|
+
}
|
|
8567
|
+
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8568
|
+
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8569
|
+
return await refreshAccessTokenSafe(account2, ctx);
|
|
8570
|
+
}
|
|
8571
|
+
var log18, refreshFailures;
|
|
8572
|
+
var init_token_manager = __esm(() => {
|
|
8573
|
+
init_src2();
|
|
8574
|
+
init_src4();
|
|
8575
|
+
init_constants2();
|
|
8576
|
+
init_proxy_types();
|
|
8577
|
+
log18 = new Logger("TokenManager");
|
|
8578
|
+
refreshFailures = new Map;
|
|
8579
|
+
});
|
|
8580
|
+
|
|
8469
8581
|
// ../../packages/proxy/src/handlers/account-selector.ts
|
|
8470
8582
|
function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
|
|
8471
8583
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
@@ -8491,7 +8603,9 @@ function fleetAccounts(provider, ctx) {
|
|
|
8491
8603
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
|
|
8492
8604
|
}
|
|
8493
8605
|
function cooldownEnd(account2, now) {
|
|
8494
|
-
|
|
8606
|
+
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8607
|
+
const refreshEnd = refreshBackoffUntil(account2.id, now);
|
|
8608
|
+
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8495
8609
|
}
|
|
8496
8610
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8497
8611
|
return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
|
|
@@ -8554,8 +8668,8 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8554
8668
|
return [probe];
|
|
8555
8669
|
}
|
|
8556
8670
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8557
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
|
|
8558
8671
|
const now = Date.now();
|
|
8672
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
|
|
8559
8673
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8560
8674
|
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
8561
8675
|
const prioritized = [...candidates].sort((left, right) => {
|
|
@@ -8573,6 +8687,7 @@ var init_account_selector = __esm(() => {
|
|
|
8573
8687
|
init_src();
|
|
8574
8688
|
init_seat_usage();
|
|
8575
8689
|
init_team_router();
|
|
8690
|
+
init_token_manager();
|
|
8576
8691
|
});
|
|
8577
8692
|
|
|
8578
8693
|
// ../../packages/proxy/src/handlers/request-handler.ts
|
|
@@ -8664,101 +8779,6 @@ var init_request_handler = __esm(() => {
|
|
|
8664
8779
|
DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
8665
8780
|
});
|
|
8666
8781
|
|
|
8667
|
-
// ../../packages/proxy/src/constants.ts
|
|
8668
|
-
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8669
|
-
var init_constants2 = __esm(() => {
|
|
8670
|
-
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8671
|
-
});
|
|
8672
|
-
|
|
8673
|
-
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8674
|
-
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8675
|
-
return {
|
|
8676
|
-
...ctx,
|
|
8677
|
-
provider,
|
|
8678
|
-
providerName: provider.name,
|
|
8679
|
-
upstreamPath
|
|
8680
|
-
};
|
|
8681
|
-
}
|
|
8682
|
-
function resolveProxyContext(url, ctx) {
|
|
8683
|
-
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8684
|
-
if (!resolvedProvider) {
|
|
8685
|
-
return null;
|
|
8686
|
-
}
|
|
8687
|
-
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8688
|
-
}
|
|
8689
|
-
var ERROR_MESSAGES, TIMING;
|
|
8690
|
-
var init_proxy_types = __esm(() => {
|
|
8691
|
-
ERROR_MESSAGES = {
|
|
8692
|
-
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8693
|
-
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8694
|
-
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8695
|
-
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8696
|
-
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8697
|
-
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8698
|
-
};
|
|
8699
|
-
TIMING = {
|
|
8700
|
-
WORKER_SHUTDOWN_DELAY: 5000
|
|
8701
|
-
};
|
|
8702
|
-
});
|
|
8703
|
-
|
|
8704
|
-
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8705
|
-
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8706
|
-
const lastFailure = refreshFailures.get(account2.id);
|
|
8707
|
-
if (lastFailure && Date.now() - lastFailure < TOKEN_REFRESH_BACKOFF_MS) {
|
|
8708
|
-
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8709
|
-
throw new ServiceUnavailableError(`Token refresh for account ${account2.name} is in backoff period after recent failure`);
|
|
8710
|
-
}
|
|
8711
|
-
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8712
|
-
if (!ctx.provider.refreshToken) {
|
|
8713
|
-
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8714
|
-
}
|
|
8715
|
-
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8716
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8717
|
-
account2.access_token = result.accessToken;
|
|
8718
|
-
account2.expires_at = result.expiresAt;
|
|
8719
|
-
if (result.refreshToken) {
|
|
8720
|
-
account2.refresh_token = result.refreshToken;
|
|
8721
|
-
}
|
|
8722
|
-
account2.last_used = Date.now();
|
|
8723
|
-
refreshFailures.delete(account2.id);
|
|
8724
|
-
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8725
|
-
return result.accessToken;
|
|
8726
|
-
}).catch((error) => {
|
|
8727
|
-
refreshFailures.set(account2.id, Date.now());
|
|
8728
|
-
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8729
|
-
throw new TokenRefreshError(account2.id, error);
|
|
8730
|
-
}).finally(() => {
|
|
8731
|
-
ctx.refreshInFlight.delete(account2.id);
|
|
8732
|
-
});
|
|
8733
|
-
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8734
|
-
}
|
|
8735
|
-
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8736
|
-
if (!promise) {
|
|
8737
|
-
throw new ServiceUnavailableError(`${ERROR_MESSAGES.REFRESH_NOT_FOUND} ${account2.id}`);
|
|
8738
|
-
}
|
|
8739
|
-
return promise;
|
|
8740
|
-
}
|
|
8741
|
-
async function getValidAccessToken(account2, ctx) {
|
|
8742
|
-
if (!account2.refresh_token && account2.api_key) {
|
|
8743
|
-
return "";
|
|
8744
|
-
}
|
|
8745
|
-
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8746
|
-
return account2.access_token;
|
|
8747
|
-
}
|
|
8748
|
-
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8749
|
-
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8750
|
-
return await refreshAccessTokenSafe(account2, ctx);
|
|
8751
|
-
}
|
|
8752
|
-
var log18, refreshFailures;
|
|
8753
|
-
var init_token_manager = __esm(() => {
|
|
8754
|
-
init_src2();
|
|
8755
|
-
init_src4();
|
|
8756
|
-
init_constants2();
|
|
8757
|
-
init_proxy_types();
|
|
8758
|
-
log18 = new Logger("TokenManager");
|
|
8759
|
-
refreshFailures = new Map;
|
|
8760
|
-
});
|
|
8761
|
-
|
|
8762
8782
|
// ../../packages/proxy/src/outside-spend.ts
|
|
8763
8783
|
class OutsideSpendTracker {
|
|
8764
8784
|
now;
|
|
@@ -8968,7 +8988,12 @@ class TeamAdmission {
|
|
|
8968
8988
|
holdSeconds: 0,
|
|
8969
8989
|
quotaProbeSeconds: 0
|
|
8970
8990
|
});
|
|
8971
|
-
account2.
|
|
8991
|
+
if (account2.active > 0 || account2.queue.length > 0)
|
|
8992
|
+
return;
|
|
8993
|
+
const now = this.now();
|
|
8994
|
+
if (account2.switchedAt === undefined || now - account2.switchedAt >= RAMP_WINDOW_MS) {
|
|
8995
|
+
account2.switchedAt = now;
|
|
8996
|
+
}
|
|
8972
8997
|
this.scheduleRamp(accountId, account2);
|
|
8973
8998
|
}
|
|
8974
8999
|
advance() {
|
|
@@ -9660,17 +9685,6 @@ var init_stream_failure = __esm(() => {
|
|
|
9660
9685
|
});
|
|
9661
9686
|
|
|
9662
9687
|
// ../../packages/proxy/src/handlers/proxy-operations.ts
|
|
9663
|
-
function shouldQuarantineAfterRefreshFailure(error) {
|
|
9664
|
-
if (!(error instanceof TokenRefreshError))
|
|
9665
|
-
return false;
|
|
9666
|
-
const status = error.originalError?.status;
|
|
9667
|
-
return typeof status === "number" && status >= 400 && status < 500;
|
|
9668
|
-
}
|
|
9669
|
-
function quarantineAccount(account2, ctx, reason) {
|
|
9670
|
-
account2.paused = true;
|
|
9671
|
-
account2.error_reason = reason;
|
|
9672
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
9673
|
-
}
|
|
9674
9688
|
function createUpstreamSender(input) {
|
|
9675
9689
|
const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
|
|
9676
9690
|
return async (token) => {
|
|
@@ -9703,10 +9717,7 @@ async function sendAuthorizedRequest(input, send) {
|
|
|
9703
9717
|
try {
|
|
9704
9718
|
accessToken = await refreshAccessTokenSafe(input.account, input.ctx);
|
|
9705
9719
|
upstream = await send(accessToken);
|
|
9706
|
-
} catch
|
|
9707
|
-
if (shouldQuarantineAfterRefreshFailure(error)) {
|
|
9708
|
-
quarantineAccount(input.account, input.ctx, "OAuth refresh was rejected by the upstream");
|
|
9709
|
-
}
|
|
9720
|
+
} catch {
|
|
9710
9721
|
return { kind: "failed" };
|
|
9711
9722
|
}
|
|
9712
9723
|
return upstream.response.status === 401 ? { kind: "authentication-failure" } : upstream;
|
package/dist/server.js
CHANGED
|
@@ -8466,6 +8466,118 @@ var init_team_router = __esm(() => {
|
|
|
8466
8466
|
PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8467
8467
|
});
|
|
8468
8468
|
|
|
8469
|
+
// ../../packages/proxy/src/constants.ts
|
|
8470
|
+
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8471
|
+
var init_constants2 = __esm(() => {
|
|
8472
|
+
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8473
|
+
});
|
|
8474
|
+
|
|
8475
|
+
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8476
|
+
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8477
|
+
return {
|
|
8478
|
+
...ctx,
|
|
8479
|
+
provider,
|
|
8480
|
+
providerName: provider.name,
|
|
8481
|
+
upstreamPath
|
|
8482
|
+
};
|
|
8483
|
+
}
|
|
8484
|
+
function resolveProxyContext(url, ctx) {
|
|
8485
|
+
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8486
|
+
if (!resolvedProvider) {
|
|
8487
|
+
return null;
|
|
8488
|
+
}
|
|
8489
|
+
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8490
|
+
}
|
|
8491
|
+
var ERROR_MESSAGES, TIMING;
|
|
8492
|
+
var init_proxy_types = __esm(() => {
|
|
8493
|
+
ERROR_MESSAGES = {
|
|
8494
|
+
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8495
|
+
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8496
|
+
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8497
|
+
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8498
|
+
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8499
|
+
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8500
|
+
};
|
|
8501
|
+
TIMING = {
|
|
8502
|
+
WORKER_SHUTDOWN_DELAY: 5000
|
|
8503
|
+
};
|
|
8504
|
+
});
|
|
8505
|
+
|
|
8506
|
+
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8507
|
+
function refreshBackoffUntil(accountId, now = Date.now()) {
|
|
8508
|
+
const failure = refreshFailures.get(accountId);
|
|
8509
|
+
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8510
|
+
}
|
|
8511
|
+
function quarantineAccount(account2, ctx, reason) {
|
|
8512
|
+
account2.paused = true;
|
|
8513
|
+
account2.error_reason = reason;
|
|
8514
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
8515
|
+
}
|
|
8516
|
+
function recordRefreshFailure(account2, ctx, error) {
|
|
8517
|
+
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8518
|
+
refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
|
|
8519
|
+
const status = error?.status;
|
|
8520
|
+
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8521
|
+
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
8522
|
+
}
|
|
8523
|
+
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8524
|
+
return refreshError;
|
|
8525
|
+
}
|
|
8526
|
+
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8527
|
+
const lastFailure = refreshFailures.get(account2.id);
|
|
8528
|
+
if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
|
|
8529
|
+
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8530
|
+
throw lastFailure.error;
|
|
8531
|
+
}
|
|
8532
|
+
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8533
|
+
if (!ctx.provider.refreshToken) {
|
|
8534
|
+
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8535
|
+
}
|
|
8536
|
+
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8537
|
+
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8538
|
+
account2.access_token = result.accessToken;
|
|
8539
|
+
account2.expires_at = result.expiresAt;
|
|
8540
|
+
if (result.refreshToken) {
|
|
8541
|
+
account2.refresh_token = result.refreshToken;
|
|
8542
|
+
}
|
|
8543
|
+
account2.last_used = Date.now();
|
|
8544
|
+
refreshFailures.delete(account2.id);
|
|
8545
|
+
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8546
|
+
return result.accessToken;
|
|
8547
|
+
}).catch((error) => {
|
|
8548
|
+
throw recordRefreshFailure(account2, ctx, error);
|
|
8549
|
+
}).finally(() => {
|
|
8550
|
+
ctx.refreshInFlight.delete(account2.id);
|
|
8551
|
+
});
|
|
8552
|
+
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8553
|
+
}
|
|
8554
|
+
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8555
|
+
if (!promise) {
|
|
8556
|
+
throw new TokenRefreshError(account2.id, new Error(ERROR_MESSAGES.REFRESH_NOT_FOUND));
|
|
8557
|
+
}
|
|
8558
|
+
return promise;
|
|
8559
|
+
}
|
|
8560
|
+
async function getValidAccessToken(account2, ctx) {
|
|
8561
|
+
if (!account2.refresh_token && account2.api_key) {
|
|
8562
|
+
return "";
|
|
8563
|
+
}
|
|
8564
|
+
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8565
|
+
return account2.access_token;
|
|
8566
|
+
}
|
|
8567
|
+
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8568
|
+
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8569
|
+
return await refreshAccessTokenSafe(account2, ctx);
|
|
8570
|
+
}
|
|
8571
|
+
var log18, refreshFailures;
|
|
8572
|
+
var init_token_manager = __esm(() => {
|
|
8573
|
+
init_src2();
|
|
8574
|
+
init_src4();
|
|
8575
|
+
init_constants2();
|
|
8576
|
+
init_proxy_types();
|
|
8577
|
+
log18 = new Logger("TokenManager");
|
|
8578
|
+
refreshFailures = new Map;
|
|
8579
|
+
});
|
|
8580
|
+
|
|
8469
8581
|
// ../../packages/proxy/src/handlers/account-selector.ts
|
|
8470
8582
|
function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
|
|
8471
8583
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
@@ -8491,7 +8603,9 @@ function fleetAccounts(provider, ctx) {
|
|
|
8491
8603
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
|
|
8492
8604
|
}
|
|
8493
8605
|
function cooldownEnd(account2, now) {
|
|
8494
|
-
|
|
8606
|
+
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8607
|
+
const refreshEnd = refreshBackoffUntil(account2.id, now);
|
|
8608
|
+
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8495
8609
|
}
|
|
8496
8610
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8497
8611
|
return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
|
|
@@ -8554,8 +8668,8 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8554
8668
|
return [probe];
|
|
8555
8669
|
}
|
|
8556
8670
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8557
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
|
|
8558
8671
|
const now = Date.now();
|
|
8672
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
|
|
8559
8673
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8560
8674
|
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
8561
8675
|
const prioritized = [...candidates].sort((left, right) => {
|
|
@@ -8573,6 +8687,7 @@ var init_account_selector = __esm(() => {
|
|
|
8573
8687
|
init_src();
|
|
8574
8688
|
init_seat_usage();
|
|
8575
8689
|
init_team_router();
|
|
8690
|
+
init_token_manager();
|
|
8576
8691
|
});
|
|
8577
8692
|
|
|
8578
8693
|
// ../../packages/proxy/src/handlers/request-handler.ts
|
|
@@ -8664,101 +8779,6 @@ var init_request_handler = __esm(() => {
|
|
|
8664
8779
|
DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
8665
8780
|
});
|
|
8666
8781
|
|
|
8667
|
-
// ../../packages/proxy/src/constants.ts
|
|
8668
|
-
var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
|
|
8669
|
-
var init_constants2 = __esm(() => {
|
|
8670
|
-
TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
|
|
8671
|
-
});
|
|
8672
|
-
|
|
8673
|
-
// ../../packages/proxy/src/handlers/proxy-types.ts
|
|
8674
|
-
function createResolvedProxyContext(ctx, provider, upstreamPath) {
|
|
8675
|
-
return {
|
|
8676
|
-
...ctx,
|
|
8677
|
-
provider,
|
|
8678
|
-
providerName: provider.name,
|
|
8679
|
-
upstreamPath
|
|
8680
|
-
};
|
|
8681
|
-
}
|
|
8682
|
-
function resolveProxyContext(url, ctx) {
|
|
8683
|
-
const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
|
|
8684
|
-
if (!resolvedProvider) {
|
|
8685
|
-
return null;
|
|
8686
|
-
}
|
|
8687
|
-
return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
|
|
8688
|
-
}
|
|
8689
|
-
var ERROR_MESSAGES, TIMING;
|
|
8690
|
-
var init_proxy_types = __esm(() => {
|
|
8691
|
-
ERROR_MESSAGES = {
|
|
8692
|
-
NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
|
|
8693
|
-
PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
|
|
8694
|
-
REFRESH_NOT_FOUND: "Refresh promise not found for account",
|
|
8695
|
-
ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
|
|
8696
|
-
TOKEN_REFRESH_FAILED: "Failed to refresh access token",
|
|
8697
|
-
PROXY_REQUEST_FAILED: "Failed to proxy request with account"
|
|
8698
|
-
};
|
|
8699
|
-
TIMING = {
|
|
8700
|
-
WORKER_SHUTDOWN_DELAY: 5000
|
|
8701
|
-
};
|
|
8702
|
-
});
|
|
8703
|
-
|
|
8704
|
-
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8705
|
-
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8706
|
-
const lastFailure = refreshFailures.get(account2.id);
|
|
8707
|
-
if (lastFailure && Date.now() - lastFailure < TOKEN_REFRESH_BACKOFF_MS) {
|
|
8708
|
-
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8709
|
-
throw new ServiceUnavailableError(`Token refresh for account ${account2.name} is in backoff period after recent failure`);
|
|
8710
|
-
}
|
|
8711
|
-
if (!ctx.refreshInFlight.has(account2.id)) {
|
|
8712
|
-
if (!ctx.provider.refreshToken) {
|
|
8713
|
-
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8714
|
-
}
|
|
8715
|
-
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8716
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
|
|
8717
|
-
account2.access_token = result.accessToken;
|
|
8718
|
-
account2.expires_at = result.expiresAt;
|
|
8719
|
-
if (result.refreshToken) {
|
|
8720
|
-
account2.refresh_token = result.refreshToken;
|
|
8721
|
-
}
|
|
8722
|
-
account2.last_used = Date.now();
|
|
8723
|
-
refreshFailures.delete(account2.id);
|
|
8724
|
-
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8725
|
-
return result.accessToken;
|
|
8726
|
-
}).catch((error) => {
|
|
8727
|
-
refreshFailures.set(account2.id, Date.now());
|
|
8728
|
-
log18.error(`Token refresh failed for account ${account2.name}`, error);
|
|
8729
|
-
throw new TokenRefreshError(account2.id, error);
|
|
8730
|
-
}).finally(() => {
|
|
8731
|
-
ctx.refreshInFlight.delete(account2.id);
|
|
8732
|
-
});
|
|
8733
|
-
ctx.refreshInFlight.set(account2.id, refreshPromise);
|
|
8734
|
-
}
|
|
8735
|
-
const promise = ctx.refreshInFlight.get(account2.id);
|
|
8736
|
-
if (!promise) {
|
|
8737
|
-
throw new ServiceUnavailableError(`${ERROR_MESSAGES.REFRESH_NOT_FOUND} ${account2.id}`);
|
|
8738
|
-
}
|
|
8739
|
-
return promise;
|
|
8740
|
-
}
|
|
8741
|
-
async function getValidAccessToken(account2, ctx) {
|
|
8742
|
-
if (!account2.refresh_token && account2.api_key) {
|
|
8743
|
-
return "";
|
|
8744
|
-
}
|
|
8745
|
-
if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
|
|
8746
|
-
return account2.access_token;
|
|
8747
|
-
}
|
|
8748
|
-
const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
|
|
8749
|
-
log18.info(`Token ${reason} for account: ${account2.name}`);
|
|
8750
|
-
return await refreshAccessTokenSafe(account2, ctx);
|
|
8751
|
-
}
|
|
8752
|
-
var log18, refreshFailures;
|
|
8753
|
-
var init_token_manager = __esm(() => {
|
|
8754
|
-
init_src2();
|
|
8755
|
-
init_src4();
|
|
8756
|
-
init_constants2();
|
|
8757
|
-
init_proxy_types();
|
|
8758
|
-
log18 = new Logger("TokenManager");
|
|
8759
|
-
refreshFailures = new Map;
|
|
8760
|
-
});
|
|
8761
|
-
|
|
8762
8782
|
// ../../packages/proxy/src/outside-spend.ts
|
|
8763
8783
|
class OutsideSpendTracker {
|
|
8764
8784
|
now;
|
|
@@ -8968,7 +8988,12 @@ class TeamAdmission {
|
|
|
8968
8988
|
holdSeconds: 0,
|
|
8969
8989
|
quotaProbeSeconds: 0
|
|
8970
8990
|
});
|
|
8971
|
-
account2.
|
|
8991
|
+
if (account2.active > 0 || account2.queue.length > 0)
|
|
8992
|
+
return;
|
|
8993
|
+
const now = this.now();
|
|
8994
|
+
if (account2.switchedAt === undefined || now - account2.switchedAt >= RAMP_WINDOW_MS) {
|
|
8995
|
+
account2.switchedAt = now;
|
|
8996
|
+
}
|
|
8972
8997
|
this.scheduleRamp(accountId, account2);
|
|
8973
8998
|
}
|
|
8974
8999
|
advance() {
|
|
@@ -9660,17 +9685,6 @@ var init_stream_failure = __esm(() => {
|
|
|
9660
9685
|
});
|
|
9661
9686
|
|
|
9662
9687
|
// ../../packages/proxy/src/handlers/proxy-operations.ts
|
|
9663
|
-
function shouldQuarantineAfterRefreshFailure(error) {
|
|
9664
|
-
if (!(error instanceof TokenRefreshError))
|
|
9665
|
-
return false;
|
|
9666
|
-
const status = error.originalError?.status;
|
|
9667
|
-
return typeof status === "number" && status >= 400 && status < 500;
|
|
9668
|
-
}
|
|
9669
|
-
function quarantineAccount(account2, ctx, reason) {
|
|
9670
|
-
account2.paused = true;
|
|
9671
|
-
account2.error_reason = reason;
|
|
9672
|
-
ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
|
|
9673
|
-
}
|
|
9674
9688
|
function createUpstreamSender(input) {
|
|
9675
9689
|
const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
|
|
9676
9690
|
return async (token) => {
|
|
@@ -9703,10 +9717,7 @@ async function sendAuthorizedRequest(input, send) {
|
|
|
9703
9717
|
try {
|
|
9704
9718
|
accessToken = await refreshAccessTokenSafe(input.account, input.ctx);
|
|
9705
9719
|
upstream = await send(accessToken);
|
|
9706
|
-
} catch
|
|
9707
|
-
if (shouldQuarantineAfterRefreshFailure(error)) {
|
|
9708
|
-
quarantineAccount(input.account, input.ctx, "OAuth refresh was rejected by the upstream");
|
|
9709
|
-
}
|
|
9720
|
+
} catch {
|
|
9710
9721
|
return { kind: "failed" };
|
|
9711
9722
|
}
|
|
9712
9723
|
return upstream.response.status === 401 ? { kind: "authentication-failure" } : upstream;
|
package/package.json
CHANGED