feat: multi-account OpenSky credential rotation

- New credentials.ts: pool manager that parses OPENSKY_CREDENTIALS env
  var (comma-separated clientId:clientSecret pairs), tracks per-credential
  tokens and credits, auto-rotates when credits drop below threshold or
  on 429 responses. Falls back to legacy OPENSKY_CLIENTID/CLIENTSECRET.
- Simplified auth.ts to thin wrapper over credential pool
- Removed single-credential fields from state.ts (now per-credential)
- rate-limit.ts stores credits per-credential via pool
- polling.ts rotates credentials on 429
- Updated .env.example with OPENSKY_CREDENTIALS documentation
- Added credentials.test.ts (8 tests) and updated rate-limit.test.ts
This commit is contained in:
silvertakana committed 2026-03-09 15:42:54 +13:00
1 parent 19b521c5ca
commit 522e976739
8 files changed
+347 -127

No files matched your search

+10
View File
@@ -13,3 +13,13 @@ NEXT_PUBLIC_BING_MAPS_KEY=
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
# OpenSky Network — multi-account credential rotation
# Comma-separated clientId:clientSecret pairs. Each account = 4,000 credits/day (~4.2h at 15s polling).
# Example: OPENSKY_CREDENTIALS=acct1-id:acct1-secret,acct2-id:acct2-secret
OPENSKY_CREDENTIALS=
# Legacy single-credential fallback (used if OPENSKY_CREDENTIALS is empty)
# OPENSKY_CLIENTID=
# OPENSKY_CLIENTSECRET=
+10 -45
View File
@@ -1,47 +1,12 @@
import { globalState } from "./state";
import { initCredentialPool, getActiveCredential, fetchTokenForCredential } from "./credentials";
export async function getOpenSkyAccessToken() {
const now = Date.now();
if (globalState.accessToken && now < globalState.tokenExpiry) {
return globalState.accessToken;
}
const clientId = process.env.OPENSKY_CLIENTID;
const clientSecret = process.env.OPENSKY_CLIENTSECRET;
if (!clientId || !clientSecret) return null;
if (!clientId.includes("@") && !clientId.endsWith("-api-client")) {
return null;
}
try {
const response = await fetch("https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
}),
cache: "no-store",
});
if (!response.ok) {
console.error(`[Aviation Polling] OAuth token error (${response.status}):`, await response.text());
return null;
}
const data = await response.json();
globalState.accessToken = data.access_token;
globalState.tokenExpiry = now + (data.expires_in * 1000) - 30000;
console.log("[Aviation Polling] Successfully acquired new OpenSky OAuth token");
return globalState.accessToken;
} catch (error) {
console.error("[Aviation Polling] OAuth token request failed:", error);
return null;
}
/**
* Get an OAuth2 access token for the currently active OpenSky credential.
* Initialises the credential pool on first call.
*/
export async function getOpenSkyAccessToken(): Promise<string | null> {
initCredentialPool();
const cred = getActiveCredential();
if (!cred) return null;
return fetchTokenForCredential(cred);
}
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
initCredentialPool,
getActiveCredential,
rotateCredential,
updateCredentialCredits,
getUsableCount,
resetPool,
} from "./credentials";
describe("Credential Pool", () => {
beforeEach(() => {
resetPool();
vi.unstubAllEnvs();
});
it("should parse OPENSKY_CREDENTIALS into multiple credentials", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:secret1,id2:secret2,id3:secret3");
initCredentialPool();
expect(getUsableCount()).toBe(3);
expect(getActiveCredential()?.clientId).toBe("id1");
});
it("should fall back to legacy single env vars", () => {
vi.stubEnv("OPENSKY_CLIENTID", "legacy-id");
vi.stubEnv("OPENSKY_CLIENTSECRET", "legacy-secret");
initCredentialPool();
expect(getUsableCount()).toBe(1);
expect(getActiveCredential()?.clientId).toBe("legacy-id");
});
it("should return null when no credentials configured", () => {
initCredentialPool();
expect(getActiveCredential()).toBeNull();
expect(getUsableCount()).toBe(0);
});
it("should rotate to the next credential", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:s1,id2:s2,id3:s3");
initCredentialPool();
expect(getActiveCredential()?.clientId).toBe("id1");
rotateCredential();
expect(getActiveCredential()?.clientId).toBe("id2");
rotateCredential();
expect(getActiveCredential()?.clientId).toBe("id3");
});
it("should return null after all credentials exhausted", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:s1,id2:s2");
initCredentialPool();
rotateCredential(); // exhaust id1
rotateCredential(); // exhaust id2
expect(getActiveCredential()).toBeNull();
expect(getUsableCount()).toBe(0);
});
it("should auto-rotate when credits drop below threshold", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:s1,id2:s2");
initCredentialPool();
expect(getActiveCredential()?.clientId).toBe("id1");
// High credits — no rotation
updateCredentialCredits(3000);
expect(getActiveCredential()?.clientId).toBe("id1");
// Below threshold (50) — should rotate
updateCredentialCredits(30);
expect(getActiveCredential()?.clientId).toBe("id2");
});
it("should skip malformed credential pairs", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:s1,,bad,id2:s2");
initCredentialPool();
expect(getUsableCount()).toBe(2);
});
it("should be idempotent on repeated init calls", () => {
vi.stubEnv("OPENSKY_CREDENTIALS", "id1:s1");
initCredentialPool();
initCredentialPool();
expect(getUsableCount()).toBe(1);
});
});
+175
View File
@@ -0,0 +1,175 @@
const OPENSKY_TOKEN_URL =
"https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token";
/** Threshold: rotate when credits fall below this value. */
const ROTATION_THRESHOLD = 50;
export interface OpenSkyCredential {
clientId: string;
clientSecret: string;
accessToken: string | null;
tokenExpiry: number;
creditsRemaining: number | null;
exhausted: boolean;
}
// ─── Pool state (survives HMR) ──────────────────────────────
const pool = globalThis as unknown as {
_openskyPool: OpenSkyCredential[] | null;
_openskyActiveIdx: number;
};
if (!pool._openskyPool) {
pool._openskyPool = null;
pool._openskyActiveIdx = 0;
}
// ─── Public API ─────────────────────────────────────────────
/** Parse credentials from env and initialise the pool (idempotent). */
export function initCredentialPool(): void {
if (pool._openskyPool) return;
const creds: OpenSkyCredential[] = [];
// Primary: OPENSKY_CREDENTIALS=id1:secret1,id2:secret2
const raw = process.env.OPENSKY_CREDENTIALS;
if (raw) {
for (const pair of raw.split(",")) {
const [clientId, clientSecret] = pair.trim().split(":");
if (clientId && clientSecret) {
creds.push(makeCredential(clientId, clientSecret));
}
}
}
// Fallback: legacy single-credential env vars
if (creds.length === 0) {
const clientId = process.env.OPENSKY_CLIENTID;
const clientSecret = process.env.OPENSKY_CLIENTSECRET;
if (clientId && clientSecret) {
creds.push(makeCredential(clientId, clientSecret));
}
}
pool._openskyPool = creds;
pool._openskyActiveIdx = 0;
console.log(`[Credentials] Initialised pool with ${creds.length} credential(s)`);
}
/** Return the active credential, or null if all are exhausted / empty. */
export function getActiveCredential(): OpenSkyCredential | null {
const creds = pool._openskyPool;
if (!creds || creds.length === 0) return null;
// Current is still usable
const current = creds[pool._openskyActiveIdx];
if (current && !current.exhausted) return current;
// Try to find another non-exhausted credential
for (let i = 0; i < creds.length; i++) {
if (!creds[i].exhausted) {
pool._openskyActiveIdx = i;
console.log(`[Credentials] Switched to credential ${i + 1}/${creds.length}`);
return creds[i];
}
}
console.warn("[Credentials] All credentials exhausted");
return null;
}
/** Mark the current credential as exhausted and rotate to the next. */
export function rotateCredential(): void {
const creds = pool._openskyPool;
if (!creds || creds.length === 0) return;
const current = creds[pool._openskyActiveIdx];
if (current) {
current.exhausted = true;
console.log(`[Credentials] Credential ${pool._openskyActiveIdx + 1}/${creds.length} marked exhausted`);
}
// getActiveCredential will find the next non-exhausted one
getActiveCredential();
}
/** Update credit count on the active credential; rotate if below threshold. */
export function updateCredentialCredits(remaining: number): void {
const cred = getActiveCredential();
if (!cred) return;
cred.creditsRemaining = remaining;
if (remaining <= ROTATION_THRESHOLD) {
console.log(`[Credentials] Credits low (${remaining}), rotating...`);
rotateCredential();
}
}
/** Get how many credentials are still usable. */
export function getUsableCount(): number {
const creds = pool._openskyPool;
if (!creds) return 0;
return creds.filter((c) => !c.exhausted).length;
}
/** Reset the pool (for testing only). */
export function resetPool(): void {
pool._openskyPool = null;
pool._openskyActiveIdx = 0;
}
// ─── Token fetch ────────────────────────────────────────────
/** Fetch or return a cached OAuth2 token for the given credential. */
export async function fetchTokenForCredential(
cred: OpenSkyCredential,
): Promise<string | null> {
const now = Date.now();
if (cred.accessToken && now < cred.tokenExpiry) {
return cred.accessToken;
}
try {
const res = await fetch(OPENSKY_TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "client_credentials",
client_id: cred.clientId,
client_secret: cred.clientSecret,
}),
cache: "no-store",
});
if (!res.ok) {
console.error(`[Credentials] Token error for ${cred.clientId} (${res.status})`);
return null;
}
const data = await res.json();
cred.accessToken = data.access_token;
cred.tokenExpiry = now + data.expires_in * 1000 - 30_000;
console.log(`[Credentials] Token acquired for ${cred.clientId}`);
return cred.accessToken;
} catch (err) {
console.error(`[Credentials] Token request failed for ${cred.clientId}:`, err);
return null;
}
}
// ─── Helpers ────────────────────────────────────────────────
function makeCredential(clientId: string, clientSecret: string): OpenSkyCredential {
return {
clientId,
clientSecret,
accessToken: null,
tokenExpiry: 0,
creditsRemaining: null,
exhausted: false,
};
}
+47 -37
View File
@@ -3,6 +3,7 @@ import { getOpenSkyAccessToken } from "./auth";
import { getLatestFromSupabase, recordToSupabase } from "./supabase";
import { updateFileCache } from "./cache";
import { parseRateLimitHeaders, computeBackoff } from "./rate-limit";
import { rotateCredential, getUsableCount } from "./credentials";
export async function pollAviation() {
if (globalState.isFetching) return;
@@ -10,87 +11,95 @@ export async function pollAviation() {
try {
const now = Date.now();
const username = process.env.OPENSKY_CLIENTID;
const password = process.env.OPENSKY_CLIENTSECRET;
const headers: Record<string, string> = {};
// Try OAuth2 token first (for new accounts created after March 2025)
// Get OAuth2 token from the active credential in the pool
const token = await getOpenSkyAccessToken();
if (token) {
headers["Authorization"] = `Bearer ${token}`;
} else if (username && password) {
// Fallback to Basic Auth (for legacy accounts)
headers["Authorization"] =
"Basic " + Buffer.from(`${username}:${password}`).toString("base64");
}
const res = await fetch("https://opensky-network.org/api/states/all", {
headers,
// Don't cache via Next.js fetch cache, we manage our own manual interval
cache: "no-store",
signal: AbortSignal.timeout(8000), // 8 second timeout to prevent hanging
signal: AbortSignal.timeout(8000),
});
// Always parse rate-limit headers (available on both success and error responses)
// Parse rate-limit headers (updates credits on active credential, may trigger rotation)
parseRateLimitHeaders(res.headers);
if (!res.ok) {
// Use server retry-after if available, otherwise exponential backoff
globalState.currentBackoff = computeBackoff();
if (globalState.currentBackoff === POLL_INTERVAL) {
// computeBackoff didn't escalate — apply exponential manually
globalState.currentBackoff = Math.min((globalState.currentBackoff || POLL_INTERVAL) * 2, 5 * 60 * 1000);
// On 429, rotate to the next credential immediately
if (res.status === 429) {
console.log(`[Aviation Polling] 429 rate limited — rotating credential (${getUsableCount()} remaining)`);
rotateCredential();
}
const retryInfo = globalState.retryAfterSec ? ` [Server retry-after: ${globalState.retryAfterSec}s]` : "";
globalState.currentBackoff = computeBackoff();
if (globalState.currentBackoff === POLL_INTERVAL) {
globalState.currentBackoff = Math.min(
(globalState.currentBackoff || POLL_INTERVAL) * 2,
5 * 60 * 1000,
);
}
console.warn(`[Aviation Polling] OpenSky returned ${res.status}: ${res.statusText}${retryInfo} (Backing off to ${globalState.currentBackoff / 1000}s)`);
const retryInfo = globalState.retryAfterSec
? ` [Server retry-after: ${globalState.retryAfterSec}s]`
: "";
console.warn(
`[Aviation Polling] OpenSky returned ${res.status}: ${res.statusText}${retryInfo} (Backing off to ${globalState.currentBackoff / 1000}s)`,
);
// If rate limited and we have NO cache, we might want to try fallback.
// We'll update the cache with fallback data if needed.
if (res.status === 429 && !globalState.aviationData) {
console.log("[Aviation Polling] Rate limited by OpenSky and no cache. Attempting fallback to Supabase history...");
console.log("[Aviation Polling] Rate limited and no cache. Trying Supabase fallback...");
const fallbackData = await getLatestFromSupabase();
if (fallbackData) {
console.log(`[Aviation Polling] Fallback successful. Cached ${fallbackData.states.length} historical states.`);
console.log(`[Aviation Polling] Fallback OK. Cached ${fallbackData.states.length} states.`);
globalState.aviationData = fallbackData;
globalState.aviationTimestamp = now;
updateFileCache(fallbackData, now);
}
}
} else {
// Reset backoff on success
globalState.currentBackoff = POLL_INTERVAL;
const data = await res.json();
data._source = "live";
console.log(`[Aviation Polling] Successfully fetched ${data.states ? data.states.length : 0} states from OpenSky`);
console.log(
`[Aviation Polling] Fetched ${data.states ? data.states.length : 0} states from OpenSky`,
);
globalState.aviationData = data;
globalState.aviationTimestamp = now;
updateFileCache(data, now);
// Asynchronously save to Supabase to build history (do not block)
// Throttle to once every 5 minutes to save Supabase CPU and prevent connection timeouts
if (data.states && Array.isArray(data.states)) {
if (now - (globalState.lastSupabaseInsert || 0) > 5 * 60 * 1000) {
globalState.lastSupabaseInsert = now;
recordToSupabase(data.states, data.time || Math.floor(now / 1000)).catch(err => {
console.error("[Aviation Polling] Supabase record error:", err);
});
recordToSupabase(data.states, data.time || Math.floor(now / 1000)).catch(
(err) => console.error("[Aviation Polling] Supabase record error:", err),
);
}
}
}
} catch (err) {
// Exponential backoff on error as well
globalState.currentBackoff = Math.min((globalState.currentBackoff || POLL_INTERVAL) * 2, 5 * 60 * 1000);
globalState.currentBackoff = Math.min(
(globalState.currentBackoff || POLL_INTERVAL) * 2,
5 * 60 * 1000,
);
const error = err as any;
const isTimeout = error?.name === 'AbortError' || error?.name === 'TimeoutError' || error?.cause?.code === 'UND_ERR_CONNECT_TIMEOUT';
const errorMessage = isTimeout ? 'Connection timed out' : (error?.message || String(error));
console.error(`[Aviation Polling] Error during poll (Backing off to ${globalState.currentBackoff / 1000}s): ${errorMessage}`);
const isTimeout =
error?.name === "AbortError" ||
error?.name === "TimeoutError" ||
error?.cause?.code === "UND_ERR_CONNECT_TIMEOUT";
const errorMessage = isTimeout
? "Connection timed out"
: error?.message || String(error);
console.error(
`[Aviation Polling] Error (Backing off to ${globalState.currentBackoff / 1000}s): ${errorMessage}`,
);
// On unexpected error, try fallback if we have no cache
if (!globalState.aviationData) {
const fallbackData = await getLatestFromSupabase();
if (fallbackData) {
@@ -102,13 +111,14 @@ export async function pollAviation() {
} finally {
globalState.isFetching = false;
// Schedule next poll using adaptive backoff (credit-aware)
if (globalState.aviationPollingInterval) {
clearTimeout(globalState.aviationPollingInterval);
}
const adaptiveInterval = computeBackoff();
// Apply a small random jitter (0-5s) to prevent synchronized requests from multiple clients
const jitter = Math.floor(Math.random() * 5000);
globalState.aviationPollingInterval = setTimeout(pollAviation, adaptiveInterval + jitter);
globalState.aviationPollingInterval = setTimeout(
pollAviation,
adaptiveInterval + jitter,
);
}
}
+8 -28
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach } from "vitest";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { parseRateLimitHeaders, computeBackoff } from "./rate-limit";
import { globalState, POLL_INTERVAL } from "./state";
import { initCredentialPool, resetPool } from "./credentials";
/** Helper to create a Headers object from a plain record. */
function makeHeaders(entries: Record<string, string>): Headers {
@@ -9,16 +10,18 @@ function makeHeaders(entries: Record<string, string>): Headers {
describe("Rate Limit", () => {
beforeEach(() => {
globalState.creditsRemaining = null;
globalState.retryAfterSec = null;
globalState.currentBackoff = POLL_INTERVAL;
resetPool();
vi.stubEnv("OPENSKY_CREDENTIALS", "test-id:test-secret");
initCredentialPool();
});
describe("parseRateLimitHeaders", () => {
it("should extract credits remaining", () => {
const headers = makeHeaders({ "X-Rate-Limit-Remaining": "3200" });
parseRateLimitHeaders(headers);
expect(globalState.creditsRemaining).toBe(3200);
// Credits are now stored per-credential (tested in credentials.test.ts)
});
it("should extract retry-after seconds", () => {
@@ -30,7 +33,6 @@ describe("Rate Limit", () => {
it("should handle missing headers gracefully", () => {
const headers = makeHeaders({});
parseRateLimitHeaders(headers);
expect(globalState.creditsRemaining).toBeNull();
expect(globalState.retryAfterSec).toBeNull();
});
});
@@ -40,38 +42,16 @@ describe("Rate Limit", () => {
globalState.retryAfterSec = 60;
const result = computeBackoff();
expect(result).toBe(60_000);
// Should be consumed (null after use)
expect(globalState.retryAfterSec).toBeNull();
});
it("should cap retry-after at 5 minutes", () => {
globalState.retryAfterSec = 600; // 10 min
globalState.retryAfterSec = 600;
const result = computeBackoff();
expect(result).toBe(5 * 60 * 1000);
});
it("should return max backoff when credits are very low", () => {
globalState.creditsRemaining = 100; // 2.5% of 4000
const result = computeBackoff();
expect(result).toBe(5 * 60 * 1000);
});
it("should double interval when credits are below 50%", () => {
globalState.currentBackoff = POLL_INTERVAL;
globalState.creditsRemaining = 1500; // 37.5%
const result = computeBackoff();
expect(result).toBe(POLL_INTERVAL * 2);
});
it("should return base interval when credits info is unknown", () => {
globalState.creditsRemaining = null;
globalState.currentBackoff = POLL_INTERVAL;
const result = computeBackoff();
expect(result).toBe(POLL_INTERVAL);
});
it("should return base interval when credits are plentiful", () => {
globalState.creditsRemaining = 3500; // 87.5%
it("should return base interval when no credit info", () => {
globalState.currentBackoff = POLL_INTERVAL;
const result = computeBackoff();
expect(result).toBe(POLL_INTERVAL);
+11 -11
View File
@@ -1,18 +1,19 @@
import { globalState, POLL_INTERVAL } from "./state";
import { getActiveCredential, updateCredentialCredits } from "./credentials";
const MAX_BACKOFF = 5 * 60 * 1000; // 5 minutes
const LOW_CREDIT_THRESHOLD = 0.2; // 20% of daily budget
const DAILY_AUTH_CREDITS = 4000;
/**
* Parse OpenSky rate-limit headers and store values in globalState.
* Parse OpenSky rate-limit headers and store values on the active credential.
* Headers: X-Rate-Limit-Remaining, X-Rate-Limit-Retry-After-Seconds
*/
export function parseRateLimitHeaders(headers: Headers): void {
const remaining = headers.get("X-Rate-Limit-Remaining");
if (remaining !== null) {
globalState.creditsRemaining = parseInt(remaining, 10);
console.log(`[Aviation RateLimit] Credits remaining: ${globalState.creditsRemaining}`);
const value = parseInt(remaining, 10);
console.log(`[Aviation RateLimit] Credits remaining: ${value}`);
updateCredentialCredits(value);
}
const retryAfter = headers.get("X-Rate-Limit-Retry-After-Seconds");
@@ -24,7 +25,7 @@ export function parseRateLimitHeaders(headers: Headers): void {
/**
* Compute the next poll backoff interval (ms) using:
* 1. Server-requested retry-after (highest priority, from 429)
* 2. Credit-aware adaptive scaling
* 2. Credit-aware adaptive scaling (reads from active credential)
* 3. Base poll interval fallback
*/
export function computeBackoff(): number {
@@ -37,16 +38,15 @@ export function computeBackoff(): number {
const base = globalState.currentBackoff || POLL_INTERVAL;
// If we have credit info, scale adaptively
if (globalState.creditsRemaining !== null) {
const ratio = globalState.creditsRemaining / DAILY_AUTH_CREDITS;
// Read credits from the active credential
const cred = getActiveCredential();
if (cred?.creditsRemaining !== null && cred?.creditsRemaining !== undefined) {
const ratio = cred.creditsRemaining / DAILY_AUTH_CREDITS;
if (ratio < LOW_CREDIT_THRESHOLD) {
// Very low on credits — use max backoff
if (ratio < 0.2) {
return MAX_BACKOFF;
}
if (ratio < 0.5) {
// Below half — double the base interval
return Math.min(base * 2, MAX_BACKOFF);
}
}
-6
View File
@@ -6,12 +6,9 @@ export const globalState = globalThis as unknown as {
aviationTimestamp: number;
aviationPollingStarted: boolean;
aviationPollingInterval: NodeJS.Timeout | null;
accessToken: string | null;
tokenExpiry: number;
isFetching: boolean;
lastSupabaseInsert: number;
currentBackoff: number;
creditsRemaining: number | null;
retryAfterSec: number | null;
};
@@ -20,11 +17,8 @@ if (globalState.aviationPollingStarted === undefined) {
globalState.aviationTimestamp = 0;
globalState.aviationPollingStarted = false;
globalState.aviationPollingInterval = null;
globalState.accessToken = null;
globalState.tokenExpiry = 0;
globalState.isFetching = false;
globalState.lastSupabaseInsert = 0;
globalState.currentBackoff = 8000;
globalState.creditsRemaining = null;
globalState.retryAfterSec = null;
}