Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(config): declarative first-run admin account and Premium license (#1291)

levonkc659a4c5d15d
diff --git a/.env.example b/.env.example
index aac59a1d..c261de03 100644
--- a/.env.example
+++ b/.env.example
@@ -301,9 +301,13 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# FREEAPI_DB_BACKUP_INTERVAL_MS=300000
# Optional declarative startup config. Use either inline JSON or a path to a JSON
-# file. It is applied idempotently after migrations on every boot.
+# file. It is applied idempotently after migrations on every boot — before the
+# HTTP listener starts, so an "admin" entry closes the first-run setup window
+# entirely. Optional "admin" creates the first dashboard account (only while no
+# account exists); optional "license" activates a freellmapi.co Premium key.
+# The JSON carries plaintext secrets — protect it like ENCRYPTION_KEY.
# FREEAPI_CONFIG_PATH=/app/server/data/freellmapi.config.json
-# FREEAPI_CONFIG_JSON={"keys":[{"platform":"groq","key":"gsk_...","label":"main"}],"routing":{"strategy":"balanced"}}
+# FREEAPI_CONFIG_JSON={"admin":{"email":"[email protected]","password":"change-me"},"license":"...","keys":[{"platform":"groq","key":"gsk_...","label":"main"}],"routing":{"strategy":"balanced"}}
# Context handoff on model switch. When enabled, FreeLLMAPI injects a compact
# system message into the outbound request whenever a session switches from one
diff --git a/docker/README.md b/docker/README.md
index b7411666..ca65af24 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -90,6 +90,8 @@ Example `freellmapi.config.json`:
```json
{
+ "admin": { "email": "[email protected]", "password": "change-me-min-8-chars" },
+ "license": "premium license key from freellmapi.co",
"keys": [
{ "platform": "groq", "key": "gsk_...", "label": "main" }
],
@@ -106,6 +108,12 @@ Example `freellmapi.config.json`:
}
```
+The optional `admin` entry creates the first dashboard account while no account
+exists (ignored with a warning afterwards — a claimed install can't be taken
+over by config), and `license` activates a Premium key against the license
+service in the background. Both fields are optional; the file carries plaintext
+secrets, so protect it like `ENCRYPTION_KEY`.
+
## Published Image
Images are published to GitHub Container Registry:
diff --git a/docs/en/install/01-install.md b/docs/en/install/01-install.md
index efc9f946..d0a8b884 100644
--- a/docs/en/install/01-install.md
+++ b/docs/en/install/01-install.md
@@ -167,6 +167,8 @@ instead of duplicated.
```json
{
+ "admin": { "email": "[email protected]", "password": "change-me-min-8-chars" },
+ "license": "premium license key from freellmapi.co",
"keys": [
{ "platform": "groq", "key": "gsk_...", "label": "main" },
{ "platform": "google", "key": "AIza...", "enabled": true }
@@ -193,6 +195,24 @@ instead of duplicated.
}
```
+Two optional top-level fields cover first-run provisioning:
+
+- **`admin`** creates the first dashboard account, but only while no account
+ exists — a claimed install ignores the entry with a warning, so the config
+ can never take it over. Because the config is applied before the HTTP
+ listener starts, an `admin` entry also closes the unauthenticated
+ first-run setup window entirely: no setup code is minted and
+ `POST /api/auth/setup` answers 409 from the first request on.
+- **`license`** is a Premium key from freellmapi.co. It is validated against
+ the license service before being stored — the same contract as the
+ dashboard's Premium page — then a live-tier catalog sync starts right away.
+ Activation runs in the background so an unreachable license service never
+ delays boot; a stored key identical to the configured one short-circuits
+ before any network call, and a changed key re-activates (rotation).
+
+The config carries plaintext secrets (provider keys, the admin password, the
+license key), so protect the file or env value exactly like `ENCRYPTION_KEY`.
+
If two custom endpoints serve the same model id, add `"endpoint"` to a `models`
or `fallback` entry to say which one you mean — the endpoint's URL, or the short
handle the dashboard shows next to it. Without it, an entry that matches more
diff --git a/server/src/__tests__/services/declarative-config.test.ts b/server/src/__tests__/services/declarative-config.test.ts
index 998f86c8..732321a1 100644
--- a/server/src/__tests__/services/declarative-config.test.ts
+++ b/server/src/__tests__/services/declarative-config.test.ts
@@ -1,7 +1,9 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
-import { initDb, getDb } from '../../db/index.js';
-import { applyDeclarativeConfig, applyDeclarativeConfigFromEnv } from '../../services/declarative-config.js';
+import { initDb, getDb, getSetting, setSetting } from '../../db/index.js';
+import { applyDeclarativeConfig, applyDeclarativeConfigFromEnv, activateConfiguredLicense } from '../../services/declarative-config.js';
import { getRoutingStrategy } from '../../services/router.js';
+import { userCount, verifyCredentials } from '../../services/auth.js';
+import { SETTING_LICENSE_KEY } from '../../services/catalog-sync.js';
const ORIGINAL_CONFIG_JSON = process.env.FREEAPI_CONFIG_JSON;
const ORIGINAL_CONFIG_PATH = process.env.FREEAPI_CONFIG_PATH;
@@ -280,3 +282,113 @@ describe('declarative config with two relays serving one model id', () => {
expect(rowOn(RELAY_A).display_name).toBe('Solo');
});
});
+
+// admin + license: the two declarative fields that touch the dashboard account
+// and the Premium catalog feed. The admin entry must only ever create the
+// FIRST account — once a user exists it degrades to a warning so a config
+// file can never take over a claimed install. The license entry goes through
+// the same validate-then-store contract as POST /api/premium/key.
+describe('declarative config admin', () => {
+ beforeEach(() => {
+ getDb().prepare('DELETE FROM users').run();
+ getDb().prepare('DELETE FROM sessions').run();
+ });
+
+ it('creates the first dashboard account only while no user exists', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const first = applyDeclarativeConfig({
+ admin: { email: '[email protected]', password: 'correct horse battery' },
+ });
+ expect(first.admin).toBe(true);
+ expect(userCount()).toBe(1);
+ // Email is normalized on write, password verifies via the same helpers
+ // the /api/auth routes use.
+ expect(verifyCredentials('[email protected]', 'correct horse battery')).toBeTruthy();
+
+ const second = applyDeclarativeConfig({
+ admin: { email: '[email protected]', password: 'totally different' },
+ });
+ expect(second.admin).toBe(false);
+ expect(second.warnings.some(w => w.startsWith('admin:'))).toBe(true);
+ expect(userCount()).toBe(1);
+ // The original account is untouched — the second entry changed nothing.
+ expect(verifyCredentials('[email protected]', 'correct horse battery')).toBeTruthy();
+ expect(verifyCredentials('[email protected]', 'totally different')).toBeNull();
+ warn.mockRestore();
+ });
+
+ it('rejects malformed admin entries at schema validation', () => {
+ expect(() => applyDeclarativeConfig({
+ admin: { email: 'not-an-email', password: 'long-enough-password' },
+ })).toThrow(/invalid declarative config/);
+ expect(() => applyDeclarativeConfig({
+ admin: { email: '[email protected]', password: 'short' },
+ })).toThrow(/invalid declarative config/);
+ expect(userCount()).toBe(0);
+ });
+});
+
+describe('declarative config license', () => {
+ function mockLicenseService(over: Record<string, unknown> = {}) {
+ return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (url.endsWith('/v1/license/activate')) {
+ return new Response(JSON.stringify({
+ valid: true, plan: 'premium', status: 'active', expiresAt: null, ...over,
+ }));
+ }
+ if (url.endsWith('/v1/license/check')) {
+ return new Response(JSON.stringify({ plan: 'premium', status: 'active', expiresAt: null }));
+ }
+ // /v1/latest catalog fetch from the kicked sync — fail it on purpose;
+ // syncCatalog catches, logs, and records the error without throwing.
+ return new Response('no catalog in tests', { status: 500 });
+ });
+ }
+
+ beforeEach(() => {
+ getDb().prepare("DELETE FROM settings WHERE key IN ('premium_license_key', 'premium_license_status')").run();
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it('validates and stores a configured license key, then kicks a live sync', async () => {
+ const fetchMock = mockLicenseService();
+ const result = applyDeclarativeConfig({ license: 'flk_valid_test_key' });
+ expect(result.license).toBe(true);
+ await vi.waitFor(() => expect(getSetting(SETTING_LICENSE_KEY)).toBe('flk_valid_test_key'));
+ const called = fetchMock.mock.calls.map(c => String(c[0] instanceof Request ? c[0].url : c[0]));
+ expect(called.some(u => u.endsWith('/v1/license/activate'))).toBe(true);
+ });
+
+ it('does not store a rejected license key', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ mockLicenseService({ valid: false, reason: 'unknown_key' });
+ await activateConfiguredLicense('flk_rejected_key');
+ expect(getSetting(SETTING_LICENSE_KEY)).toBeUndefined();
+ expect(warn.mock.calls.some(c => String(c[0]).includes('rejected'))).toBe(true);
+ });
+
+ it('leaves settings untouched when the license service is unreachable', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'));
+ await activateConfiguredLicense('flk_offline_key');
+ expect(getSetting(SETTING_LICENSE_KEY)).toBeUndefined();
+ expect(warn.mock.calls.some(c => String(c[0]).includes('could not reach'))).toBe(true);
+ });
+
+ it('skips activation entirely when the stored key already matches', async () => {
+ setSetting(SETTING_LICENSE_KEY, 'flk_already_stored');
+ const fetchMock = vi.spyOn(globalThis, 'fetch');
+ await activateConfiguredLicense('flk_already_stored');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('re-activates when the configured key differs from the stored one (rotation)', async () => {
+ setSetting(SETTING_LICENSE_KEY, 'flk_old_key_1');
+ mockLicenseService();
+ await activateConfiguredLicense('flk_new_key_2');
+ expect(getSetting(SETTING_LICENSE_KEY)).toBe('flk_new_key_2');
+ });
+});
diff --git a/server/src/routes/premium.ts b/server/src/routes/premium.ts
index 92eeb164..3fcea410 100644
--- a/server/src/routes/premium.ts
+++ b/server/src/routes/premium.ts
@@ -9,6 +9,7 @@ import {
getSyncState,
refreshLicenseStatus,
syncCatalog,
+ validateLicenseKey,
} from '../services/catalog-sync.js';
export const premiumRouter = Router();
@@ -48,16 +49,8 @@ premiumRouter.post('/key', async (req: Request, res: Response) => {
return;
}
- let result: { valid: boolean; plan: string | null; status: string | null; expiresAt: string | null; reason?: string };
- try {
- const r = await fetch(`${catalogBaseUrl()}/v1/license/activate`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ key }),
- signal: AbortSignal.timeout(15000),
- });
- result = (await r.json()) as typeof result;
- } catch {
+ const result = await validateLicenseKey(key, 15000);
+ if (!result) {
res.status(502).json({ error: 'Could not reach the license service. Check your connection and try again.' });
return;
}
diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.ts
index 26bf7f0e..d5f64daa 100644
--- a/server/src/services/catalog-sync.ts
+++ b/server/src/services/catalog-sync.ts
@@ -749,6 +749,35 @@ export async function syncCatalog(force = false): Promise<SyncResult> {
}
}
+/** Raw response from the catalog service's license activation endpoint. */
+export interface LicenseActivation {
+ valid: boolean;
+ plan: string | null;
+ status: string | null;
+ expiresAt: string | null;
+ reason?: string;
+}
+
+/**
+ * Validate a key with the license service. Returns null when the service is
+ * unreachable — distinguishable from a rejected key, so a transient outage can
+ * be warned about instead of reported as a bad key. Shared by the dashboard's
+ * POST /api/premium/key and declarative `license` config.
+ */
+export async function validateLicenseKey(key: string, timeoutMs = FETCH_TIMEOUT_MS): Promise<LicenseActivation | null> {
+ try {
+ const res = await fetch(`${catalogBaseUrl()}/v1/license/activate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ key }),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ return (await res.json()) as LicenseActivation;
+ } catch {
+ return null;
+ }
+}
+
/** Revalidate the stored license against the catalog service and cache the result. */
export async function refreshLicenseStatus(): Promise<LicenseStatus | null> {
const key = getSetting(SETTING_LICENSE_KEY);
diff --git a/server/src/services/declarative-config.ts b/server/src/services/declarative-config.ts
index 59c4dfbb..50fb4ce9 100644
--- a/server/src/services/declarative-config.ts
+++ b/server/src/services/declarative-config.ts
@@ -1,12 +1,19 @@
import fs from 'fs';
import { z } from 'zod';
import type { Db } from '../db/types.js';
-import { getDb } from '../db/index.js';
+import { getDb, getSetting, setSetting } from '../db/index.js';
import { encrypt } from '../lib/crypto.js';
import { resolveProvider } from '../providers/index.js';
import { setCustomWeights, setRoutingStrategy, setKeySelectionStrategy } from './router.js';
import { ensureModelInProfiles } from './profile-models.js';
import { customModelSeed } from './custom-model-seed.js';
+import { createUser, userCount } from './auth.js';
+import {
+ SETTING_LICENSE_KEY,
+ refreshLicenseStatus,
+ syncCatalog,
+ validateLicenseKey,
+} from './catalog-sync.js';
import { endpointRefMatches, endpointScopeForBaseUrl } from '../lib/endpoint-scope.js';
import {
clearCatalogModelTombstone,
@@ -77,7 +84,22 @@ const fallbackEntrySchema = z.object({
enabled: z.boolean().optional(),
});
+// First-run dashboard account. Created only while the users table is empty —
+// since declarative config is applied before the HTTP listener starts, an
+// `admin` entry closes the unauthenticated POST /api/auth/setup window
+// entirely (no setup code is even minted). Once an account exists the entry
+// degrades to a warning, so config can never take over a claimed install.
+// Minimums mirror the signup schema in routes/auth.ts.
+const adminSchema = z.object({
+ email: z.string().email(),
+ password: z.string().min(8),
+});
+
const declarativeConfigSchema = z.object({
+ admin: adminSchema.optional(),
+ // Premium license key (freellmapi.co). Same minimum as the dashboard's
+ // POST /api/premium/key length gate.
+ license: z.string().min(8).optional(),
keys: z.array(keySchema).optional(),
customProviders: z.array(customProviderSchema).optional(),
models: z.array(modelSchema).optional(),
@@ -100,6 +122,10 @@ export type DeclarativeConfig = z.infer<typeof declarativeConfigSchema>;
export interface DeclarativeConfigResult {
applied: boolean;
source?: string;
+ /** True when the `admin` entry created the first dashboard account. */
+ admin: boolean;
+ /** True when a `license` entry was handed to background activation. */
+ license: boolean;
keys: number;
customModels: number;
models: number;
@@ -447,6 +473,8 @@ export function applyDeclarativeConfig(input: unknown, source = 'inline'): Decla
const result: DeclarativeConfigResult = {
applied: true,
source,
+ admin: false,
+ license: false,
keys: 0,
customModels: 0,
models: 0,
@@ -456,6 +484,16 @@ export function applyDeclarativeConfig(input: unknown, source = 'inline'): Decla
};
const apply = db.transaction(() => {
+ if (parsed.data.admin) {
+ if (userCount() === 0) {
+ createUser(parsed.data.admin.email, parsed.data.admin.password);
+ result.admin = true;
+ } else {
+ const warning = 'admin: a dashboard account already exists — entry ignored';
+ result.warnings.push(warning);
+ console.warn(`[config] ${warning}`);
+ }
+ }
for (const key of parsed.data.keys ?? []) {
const warning = missingKeyWarning(key);
if (warning) {
@@ -486,18 +524,58 @@ export function applyDeclarativeConfig(input: unknown, source = 'inline'): Decla
}
});
apply();
+
+ // License activation needs the license service — network I/O has no place in
+ // the synchronous DB apply. It runs detached so a slow or unreachable
+ // service never delays boot; a failure logs a warning and leaves settings
+ // untouched, the same contract as the dashboard's POST /api/premium/key.
+ if (parsed.data.license) {
+ result.license = true;
+ void activateConfiguredLicense(parsed.data.license);
+ }
return result;
}
+/**
+ * Activate a Premium license key from declarative config. Idempotent across
+ * boots: a stored key identical to the configured one short-circuits before
+ * any network call, while a different key re-activates (rotation). Exported
+ * for tests.
+ */
+export async function activateConfiguredLicense(key: string): Promise<void> {
+ const trimmed = key.trim();
+ try {
+ if (getSetting(SETTING_LICENSE_KEY) === trimmed) return;
+ const result = await validateLicenseKey(trimmed);
+ if (result === null) {
+ console.warn('[config] license: could not reach the license service — key left unconfigured');
+ return;
+ }
+ if (!result.valid) {
+ console.warn(`[config] license: key rejected (${result.reason ?? 'invalid'}) — left unconfigured`);
+ return;
+ }
+ setSetting(SETTING_LICENSE_KEY, trimmed);
+ await refreshLicenseStatus();
+ // Live-tier sync kicks off right away so the upgrade is visible within
+ // seconds; its own catch-all logs failures.
+ void syncCatalog(true);
+ console.log('[config] license activated — live catalog sync started');
+ } catch (err) {
+ console.warn(`[config] license activation failed: ${err instanceof Error ? err.message : err}`);
+ }
+}
+
export function applyDeclarativeConfigFromEnv(): DeclarativeConfigResult {
const loaded = readConfigFromEnv();
if (!loaded) {
- return { applied: false, keys: 0, customModels: 0, models: 0, fallback: 0, routing: false, warnings: [] };
+ return { applied: false, admin: false, license: false, keys: 0, customModels: 0, models: 0, fallback: 0, routing: false, warnings: [] };
}
const result = applyDeclarativeConfig(loaded.value, loaded.source);
console.log(
`[config] applied ${loaded.source}: ${result.keys} keys, ${result.customModels} custom models, ` +
`${result.models} model edits, ${result.fallback} fallback rows${result.routing ? ', routing' : ''}` +
+ `${result.admin ? ', admin account created' : ''}${result.license ? ', license activation started' : ''}` +
`${result.warnings.length > 0 ? `, ${result.warnings.length} entries skipped` : ''}`,
);
return result;