Files
raucao 4f3c4334bd Use only normal API keys for OpenRouter spend
OpenRouter now rejects management keys from the browser on both
/api/v1/keys and /api/v1/analytics/query, so the management-key flow can
no longer work in the extension. Read the configured key's own usage from
GET /api/v1/key instead, which returns UTC daily, weekly, and monthly
buckets and works from the browser.

Drop the key-type selection, key listing/selection, pagination, and the
management/analytics endpoints. Validate the key against /key before
persisting, and write a fresh record so legacy keyType/keyIds fields are
dropped. Keep the browser-block hint for anyone still storing a
management key.
2026-11-16 22:16:35 +04:00

218 lines
5.9 KiB
JavaScript

import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { isCancellation } from './http';
import {
OPENROUTER_DEFAULT_GRANULARITY,
OPENROUTER_DEFAULT_INTERVAL,
OPENROUTER_KEY_URL,
openrouterAuthorizationHeader,
openrouterNormalizeGranularity,
openrouterUsageForGranularity,
} from '../config/openrouter';
export default class OpenRouterService extends Service {
@service storage;
@service http;
@service pageLifecycle;
removeRestoreHandler = null;
@tracked enabled = false;
@tracked apiKey = null;
@tracked interval = OPENROUTER_DEFAULT_INTERVAL;
@tracked granularity = OPENROUTER_DEFAULT_GRANULARITY;
@tracked usage = null;
@tracked loading = false;
@tracked error = null;
intervalId = null;
fetching = false;
ready = null;
constructor() {
super(...arguments);
this.ready = this.load();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
// A bfcache restore may have cancelled the last usage fetch, leaving a stale
// error behind. Fetch again immediately instead of waiting for the interval.
handleRestore() {
if (this.enabled) {
this.fetchUsage();
}
}
async load() {
try {
const integration = await this.storage.get('integrations', 'openrouter');
if (integration?.status === 'active') {
this.enabled = true;
this.apiKey = integration.apiKey ?? null;
this.interval = integration.interval ?? OPENROUTER_DEFAULT_INTERVAL;
this.granularity = openrouterNormalizeGranularity(
integration.granularity
);
this.startPolling();
}
} catch (err) {
console.error('Error loading OpenRouter integration:', err);
}
}
async enable(
apiKey,
interval = OPENROUTER_DEFAULT_INTERVAL,
granularity = OPENROUTER_DEFAULT_GRANULARITY
) {
await this.ready;
await this.save(apiKey, interval, granularity);
}
async update(
apiKey = this.apiKey,
interval = this.interval,
granularity = this.granularity
) {
await this.ready;
await this.save(apiKey, interval, granularity);
}
// Validates the key before persisting so a typo shows up in the settings
// dialog instead of surfacing later on the dashboard.
async save(apiKey, interval, granularity) {
await this.fetchKeyInfo(apiKey);
this.apiKey = apiKey;
this.interval = interval;
this.granularity = granularity;
this.enabled = true;
await this.persist({ apiKey, interval, granularity });
this.startPolling();
}
async persist({ apiKey, interval, granularity }) {
const existing = await this.storage.get('integrations', 'openrouter');
// Build the record fresh. Older versions also stored keyType/keyIds for the
// removed management-key flow, and spreading `existing` would keep them.
await this.storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'active',
apiKey,
interval,
granularity,
createdAt: existing?.createdAt ?? Date.now(),
});
}
async disable() {
await this.ready;
this.stopPolling();
this.enabled = false;
this.apiKey = null;
this.interval = OPENROUTER_DEFAULT_INTERVAL;
this.granularity = OPENROUTER_DEFAULT_GRANULARITY;
this.usage = null;
this.error = null;
await this.storage.remove('integrations', 'openrouter');
}
// Reads this key's own usage from GET /api/v1/key. It is the only OpenRouter
// usage endpoint that works with a normal API key from the browser.
async fetchKeyInfo(apiKey) {
const response = await this.http.requestJson(OPENROUTER_KEY_URL, {
headers: { Authorization: openrouterAuthorizationHeader(apiKey) },
});
return response?.data ?? {};
}
async fetchUsage() {
if (this.fetching) {
return;
}
this.fetching = true;
this.loading = true;
try {
const keyData = await this.fetchKeyInfo(this.apiKey);
this.usage = openrouterUsageForGranularity(keyData, this.granularity);
this.error = null;
} catch (err) {
// A navigation or bfcache freeze cancels the request; keep the last
// known values and do not report a failure.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error('Error fetching OpenRouter usage:', err);
this.error = this.classifyError(err);
} finally {
this.fetching = false;
this.loading = false;
}
}
classifyError(err) {
if (err?.name === 'NetworkError') {
return 'Unable to reach OpenRouter';
}
// Prefer the API's own message so auth and permission failures stay
// diagnosable, falling back to a status-based summary.
const apiMessage = err?.body?.error?.message;
// OpenRouter refuses management keys that look browser-originated. A stored
// management key hits this guard; point the user at a normal API key.
if (apiMessage && /cannot be used from a browser/i.test(apiMessage)) {
return 'OpenRouter does not allow management keys from the browser. Use a normal API key instead.';
}
if (err?.status === 401) {
return apiMessage ?? 'Invalid or expired API key';
}
if (err?.status === 403) {
return apiMessage ?? 'Access denied by OpenRouter';
}
if (err?.status === 408) {
return apiMessage ?? 'OpenRouter timed out';
}
if (err?.status === 429) {
return apiMessage ?? 'Rate limited by OpenRouter';
}
return apiMessage ?? 'OpenRouter returned an error';
}
startPolling() {
this.stopPolling();
this.fetchUsage();
this.intervalId = setInterval(() => {
this.fetchUsage();
}, this.interval);
}
stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
}