mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-18 06:12:41 +00:00
Compare commits
2 Commits
fix/plugin
...
fix/usage-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cddfb918b | ||
|
|
90481eb9b3 |
1
changelog.d/fixes/usage-command-json-account-scope.md
Normal file
1
changelog.d/fixes/usage-command-json-account-scope.md
Normal file
@@ -0,0 +1 @@
|
||||
- Return the shared provider accounts in the usage command JSON (`?format=json`) only to keys with `self:account-quota` or a management scope, the same rule `/v1/me/status` uses; other keys get their personal quota only (thanks @Witroch4).
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
type ApiKeyUsageLimitStatus,
|
||||
} from "@/lib/usage/apiKeyUsageLimits";
|
||||
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
|
||||
import { hasManageScope } from "@/shared/constants/managementScopes";
|
||||
import { hasSelfAccountQuotaScope } from "@/shared/constants/selfServiceScopes";
|
||||
|
||||
export const INTERNAL_USAGE_COMMAND = "@@om-usage";
|
||||
export const USAGE_COMMAND_DISABLED_MESSAGE = "Usage command is disabled for this API key.";
|
||||
@@ -23,6 +25,21 @@ export interface UsageCommandApiKeyMetadata {
|
||||
dailyUsageLimitUsd?: number | null;
|
||||
weeklyUsageLimitUsd?: number | null;
|
||||
fiveHourUsageLimitUsd?: number | null;
|
||||
scopes?: string[] | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared provider accounts behind a key (plan, raw quota windows, reset
|
||||
* times, connection ids) are operator data, not the key holder's. Only a key
|
||||
* explicitly granted `self:account-quota` (the same scope that gates
|
||||
* `accountQuotas` on /v1/me/status) or a management key may read them; any other
|
||||
* key gets its own personal quota and nothing else. Missing scopes fail closed.
|
||||
*/
|
||||
export function canReadSharedAccountQuota(scopes: readonly string[] | null | undefined): boolean {
|
||||
const list = Array.isArray(scopes)
|
||||
? scopes.filter((s): s is string => typeof s === "string")
|
||||
: [];
|
||||
return hasSelfAccountQuotaScope(list) || hasManageScope(list);
|
||||
}
|
||||
|
||||
interface ProviderConnectionLike {
|
||||
@@ -547,7 +564,9 @@ function appendQuotaBlock(
|
||||
* NOTE on percentage semantics (#15530):
|
||||
* - JSON `provider.quotas` and `providers[].quotas` expose raw upstream
|
||||
* snapshots (unadjusted usage and remaining numbers/percentages), alongside
|
||||
* connection-level `quotaWindowThresholds`.
|
||||
* connection-level `quotaWindowThresholds` — ONLY to keys allowed to read the
|
||||
* shared accounts ({@link canReadSharedAccountQuota}). Every other key gets
|
||||
* `provider: null` and `providers: []`.
|
||||
* - In contrast, text output (`buildUsageCommandText` / terminal `@@om-usage`)
|
||||
* renders cutoff-adjusted remaining percentages (`NN% left`) via
|
||||
* {@link effectiveRemainingPercent}, where the configured cutoff reserve
|
||||
@@ -591,6 +610,9 @@ export async function buildUsageCommandJson(
|
||||
{ now: resolvedDeps.now }
|
||||
)
|
||||
: null;
|
||||
if (!canReadSharedAccountQuota(metadata.scopes)) {
|
||||
return { allowed: true, personal, provider: null, providers: [] };
|
||||
}
|
||||
const snapshots = await collectUsageSnapshots(metadata, resolvedDeps);
|
||||
const provider = selectUsageSnapshot(snapshots, selection);
|
||||
return { allowed: true, personal, provider, providers: snapshots };
|
||||
|
||||
@@ -32,11 +32,14 @@ function allowedDeps(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
now: () => NOW,
|
||||
isValidApiKey: async (apiKey: string) => apiKey === "sk-allowed",
|
||||
// The panel key is explicitly granted the shared-account view; a plain
|
||||
// client key (self:usage only) is covered by the tests at the bottom.
|
||||
getApiKeyMetadata: async () => ({
|
||||
id: "key-allowed",
|
||||
name: "panel key",
|
||||
allowUsageCommand: true,
|
||||
usageLimitEnabled: true,
|
||||
scopes: ["self:usage", "self:account-quota"],
|
||||
}),
|
||||
getProviderConnections: async () => [
|
||||
{ id: "conn-claude", provider: "claude", isActive: true },
|
||||
@@ -223,3 +226,75 @@ test("om-usage preserves raw quota in json while text scales remaining quota by
|
||||
assert.match(text, /Weekly/);
|
||||
assert.match(text, /20% left/);
|
||||
});
|
||||
|
||||
// A client key with the usage command could read, through ?format=json, every
|
||||
// shared provider account: connection ids, plan, raw quota and resets. Those
|
||||
// belong to the operator, not to the key holder.
|
||||
function failingProviderCollectors() {
|
||||
const fail = () => {
|
||||
throw new Error("provider accounts must not be read for this key");
|
||||
};
|
||||
return {
|
||||
getProviderConnections: async () => fail(),
|
||||
getAllProviderLimitsCache: () => fail(),
|
||||
getProviderConnectionById: async () => fail(),
|
||||
getProviderLimitsCache: () => fail(),
|
||||
};
|
||||
}
|
||||
|
||||
for (const [label, scopes] of [
|
||||
["a plain client key (self:usage only)", ["self:usage"]],
|
||||
["a key whose metadata carries no scopes", undefined],
|
||||
] as const) {
|
||||
test(`om-usage ?format=json hides the shared provider accounts from ${label}`, async () => {
|
||||
const response = await handleInternalUsageCommandHttpRequest(
|
||||
new Request("http://localhost/api/usage/om-usage?format=json", {
|
||||
headers: { Authorization: "Bearer sk-allowed" },
|
||||
}),
|
||||
allowedDeps({
|
||||
getApiKeyMetadata: async () => ({
|
||||
id: "key-client",
|
||||
name: "client key",
|
||||
allowUsageCommand: true,
|
||||
usageLimitEnabled: true,
|
||||
...(scopes ? { scopes: [...scopes] } : {}),
|
||||
}),
|
||||
...failingProviderCollectors(),
|
||||
})
|
||||
);
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
const body = (await response.json()) as {
|
||||
allowed: boolean;
|
||||
personal: { weeklySpentUsd: number } | null;
|
||||
provider: unknown;
|
||||
providers: unknown[];
|
||||
};
|
||||
assert.equal(body.allowed, true);
|
||||
assert.equal(body.personal?.weeklySpentUsd, 8);
|
||||
assert.equal(body.provider, null);
|
||||
assert.deepEqual(body.providers, []);
|
||||
assert.doesNotMatch(JSON.stringify(body), /conn-claude|conn-codex|Claude Max|Codex Pro/);
|
||||
});
|
||||
}
|
||||
|
||||
test("om-usage ?format=json still shows the shared accounts to a management key", async () => {
|
||||
const response = await handleInternalUsageCommandHttpRequest(
|
||||
new Request("http://localhost/api/usage/om-usage?format=json", {
|
||||
headers: { Authorization: "Bearer sk-allowed" },
|
||||
}),
|
||||
allowedDeps({
|
||||
getApiKeyMetadata: async () => ({
|
||||
id: "key-admin",
|
||||
name: "operator key",
|
||||
allowUsageCommand: true,
|
||||
usageLimitEnabled: false,
|
||||
scopes: ["manage", "self:usage"],
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
const body = (await response.json()) as { providers: Array<{ provider: string }> };
|
||||
assert.deepEqual(body.providers.map((s) => s.provider).sort(), ["claude", "codex"]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user