FreeDeepseekAPI
@@ -177,7 +178,7 @@
FreeDeepseekAPI
Settings
Proxy
-
diff --git a/public/dashboard/media-breach.jpg b/public/dashboard/media-breach.jpg
deleted file mode 100644
index b9bfd29..0000000
Binary files a/public/dashboard/media-breach.jpg and /dev/null differ
diff --git a/public/dashboard/media-bubbles.jpg b/public/dashboard/media-bubbles.jpg
deleted file mode 100644
index 935177a..0000000
Binary files a/public/dashboard/media-bubbles.jpg and /dev/null differ
diff --git a/public/dashboard/media-caustics.jpg b/public/dashboard/media-caustics.jpg
deleted file mode 100644
index b455071..0000000
Binary files a/public/dashboard/media-caustics.jpg and /dev/null differ
diff --git a/public/dashboard/media-manta.jpg b/public/dashboard/media-manta.jpg
deleted file mode 100644
index f87b6ae..0000000
Binary files a/public/dashboard/media-manta.jpg and /dev/null differ
diff --git a/public/dashboard/media-ripples.jpg b/public/dashboard/media-ripples.jpg
deleted file mode 100644
index f601fda..0000000
Binary files a/public/dashboard/media-ripples.jpg and /dev/null differ
diff --git a/public/dashboard/media-surface.jpg b/public/dashboard/media-surface.jpg
deleted file mode 100644
index a5e1cc8..0000000
Binary files a/public/dashboard/media-surface.jpg and /dev/null differ
diff --git a/public/dashboard/media-whale-sharks.jpg b/public/dashboard/media-whale-sharks.jpg
deleted file mode 100644
index a370b16..0000000
Binary files a/public/dashboard/media-whale-sharks.jpg and /dev/null differ
diff --git a/public/dashboard/requests.js b/public/dashboard/requests.js
index ed62a97..ad4d194 100644
--- a/public/dashboard/requests.js
+++ b/public/dashboard/requests.js
@@ -42,7 +42,7 @@
st.held = null;
render();
});
- const hero = F.pageHero({ image: '/dashboard/media-caustics.jpg', label: F.t('Request log'), position: '50% 62%' });
+ const hero = F.pageHero({ label: F.t('Request log') });
root.append(hero, h('div', { class: 'view-pad' },
h('div', { class: 'filter-row' }, statusSeg, selects, h('label', { class: 'search-field search-field-inline' }, F.icon('search'), client)),
notice,
diff --git a/public/dashboard/settings.js b/public/dashboard/settings.js
index cc44f26..7a83ee1 100644
--- a/public/dashboard/settings.js
+++ b/public/dashboard/settings.js
@@ -6,10 +6,13 @@
const { h, fmt } = F;
const PREFS = {
+ theme: { key: 'fdsa.theme', attr: 'data-theme', values: ['system', 'light', 'dark'] },
material: { key: 'fdsa.material', attr: 'data-material', values: ['system', 'glass', 'solid'] },
density: { key: 'fdsa.density', attr: 'data-density', values: ['comfortable', 'compact'] },
};
+ const systemDark = window.matchMedia('(prefers-color-scheme: dark)');
+
F.prefs = {
get(name) {
const p = PREFS[name];
@@ -19,18 +22,24 @@
},
set(name, value) {
const p = PREFS[name];
- try { localStorage.setItem(p.key, value); } catch (e) { F.toast(F.t('Could not save the {name} preference: {error}', { name: F.t(name === 'material' ? 'Material' : 'Density'), error: e.name }), { tone: 'error' }); }
+ try { localStorage.setItem(p.key, value); } catch (e) { F.toast(F.t('Could not save the {name} preference: {error}', { name: F.t({ theme: 'Theme', material: 'Material', density: 'Density' }[name]), error: e.name }), { tone: 'error' }); }
F.prefs.apply(name, value);
},
apply(name, value) {
const p = PREFS[name];
const root = document.documentElement;
+ if (name === 'theme') {
+ if (value === 'dark' || (value === 'system' && systemDark.matches)) root.setAttribute(p.attr, 'dark');
+ else root.removeAttribute(p.attr);
+ return;
+ }
if (value === p.values[0] && name !== 'density') root.removeAttribute(p.attr);
else root.setAttribute(p.attr, value);
},
applyAll() { for (const name of Object.keys(PREFS)) F.prefs.apply(name, F.prefs.get(name)); },
};
F.prefs.applyAll();
+ systemDark.addEventListener('change', () => { if (F.prefs.get('theme') === 'system') F.prefs.apply('theme', 'system'); });
const st = { root: null, els: {}, health: null, healthError: null, visible: false, snippet: 'openai',
update: { status: null, error: null, channel: null, check: null, phase: 'idle', message: null } };
@@ -44,19 +53,19 @@
const appearance = h('div', { class: 'set-group' });
const chat = h('div', { class: 'set-stack' });
root.append(h('div', { class: 'view-pad settings' },
- section(F.t('Access key'), F.t('The PROXY_API_KEY this dashboard signs its requests with.'), key, 'key'),
- section(F.t('Connection'), F.t('Point any OpenAI- or Anthropic-compatible client at this proxy.'), conn, 'route'),
- section(F.t('Server'), F.t('Facts from GET /health.'), server, 'status'),
- section(F.t('Updates'), F.t('Stable gets a release once it has been checked. Latest gets every release first.'), updates, 'download'),
- section(F.t('Appearance'), null, appearance, 'settings'),
- section(F.t('Chat data'), F.t('Stored in this browser only, for {origin}. 127.0.0.1 and localhost keep separate stores.', { origin: location.origin }), chat, 'chat')));
+ section(F.t('Access key'), F.t('The PROXY_API_KEY this dashboard signs its requests with'), key),
+ section(F.t('Connection'), F.t('Point any OpenAI- or Anthropic-compatible client at this proxy'), conn),
+ section(F.t('Server'), F.t('Facts from GET /health'), server),
+ section(F.t('Updates'), F.t('Stable gets a release once it has been checked. Latest gets every release first.'), updates),
+ section(F.t('Appearance'), null, appearance),
+ section(F.t('Chat data'), F.t('Stored in this browser only, for {origin}. 127.0.0.1 and localhost keep separate stores.', { origin: location.origin }), chat)));
Object.assign(st.els, { key, conn, server, updates, appearance, chat });
F.on('accounts', () => { if (st.visible) renderServer(); });
}
- function section(title, lead, body, icon) {
+ function section(title, lead, body) {
return h('section', { class: 'settings-section' },
- h('header', { class: 'settings-head' }, h('h2', { class: 'settings-title' }, F.icon(icon, 'title-icon'), h('span', { text: title })), lead ? h('p', { class: 'settings-desc', text: lead }) : null),
+ h('header', { class: 'settings-head' }, h('h2', { class: 'settings-title' }, h('span', { text: title })), lead ? h('p', { class: 'settings-desc', text: lead }) : null),
body);
}
@@ -64,7 +73,7 @@
function row(label, hint, control, cls, icon) {
return h('div', { class: ['set-row', cls, icon && 'has-icon'] },
icon ? h('span', { class: 'set-icon', 'aria-hidden': 'true' }, F.icon(icon)) : null,
- h('div', { class: 'set-text' }, h('span', { class: 'set-label', text: label }), hint ? (hint instanceof Node ? hint : h('span', { class: 'set-hint', text: hint })) : null),
+ h('div', { class: 'set-text' }, h('span', { class: 'set-label', text: F.t(label) }), hint ? (hint instanceof Node ? hint : h('span', { class: 'set-hint', text: F.t(hint) })) : null),
control == null || control === '' ? null : h('div', { class: 'set-control' }, control instanceof Node ? control : String(control)));
}
@@ -340,9 +349,8 @@
: s.branch ? [h('span', { text: 'Branch' }), h('code', { class: 'mono-id update-branch', text: s.branch })] : [h('span', { text: 'No channel' })];
const checkBtn = F.btn(u.phase === 'checking' ? 'Checking…' : 'Check for updates', { kind: 'primary', icon: 'reload', onclick: checkUpdate });
if (busy || s.method !== 'git') checkBtn.setAttribute('aria-disabled', 'true');
- // The installed build over a humpback breaking the surface (MEDIA.md), the check on its right.
+ // The installed build, the check on its right.
const hero = h('div', { class: 'update-hero' },
- h('img', { class: 'update-hero-media', src: '/dashboard/media-breach.jpg', alt: '', decoding: 'async', 'aria-hidden': 'true' }),
h('div', { class: 'update-hero-body' },
h('p', { class: 'update-version', text: s.version ? `v${s.version}` : 'Unknown version' }),
h('p', { class: 'update-where' }, ...where, s.commit ? h('code', { class: 'mono-id', text: s.commit }) : null)),
@@ -415,7 +423,8 @@
function renderAppearance() {
const pref = (label, hint, name, options) => row(label, hint, F.segmented(label, options, F.prefs.get(name), (v) => F.prefs.set(name, v)));
st.els.appearance.replaceChildren(
- pref(F.t('Material'), F.t('System follows the reduced-transparency setting of your OS.'), 'material', [{ value: 'system', label: F.t('System') }, { value: 'glass', label: F.t('Glass'), icon: 'material' }, { value: 'solid', label: F.t('Solid') }]),
+ pref(F.t('Theme'), null, 'theme', [{ value: 'system', label: F.t('System') }, { value: 'light', label: F.t('Light') }, { value: 'dark', label: F.t('Dark') }]),
+ pref(F.t('Material'), F.t('System follows the reduced-transparency setting of your OS'), 'material', [{ value: 'system', label: F.t('System') }, { value: 'glass', label: F.t('Glass'), icon: 'material' }, { value: 'solid', label: F.t('Solid') }]),
pref(F.t('Density'), null, 'density', [{ value: 'comfortable', label: F.t('Comfortable') }, { value: 'compact', label: F.t('Compact') }]),
row(F.t('Language'), F.t('Saved in this browser. Chinese is used when the browser language is Chinese and you have not chosen.'),
F.segmented(F.t('Language'), [{ value: 'en', label: 'English' }, { value: 'zh', label: '中文' }], F.lang.get(), (v) => { if (v !== F.lang.get()) F.lang.set(v); })));
@@ -423,6 +432,7 @@
async function renderChat() {
const host = st.els.chat;
+ const size = (b) => (b >= 2 ** 30 ? `${(b / 2 ** 30).toFixed(1)} GB` : b >= 2 ** 20 ? `${Math.round(b / 2 ** 20)} MB` : `${Math.round(b / 1024)} KB`);
const info = F.chatStore ? await F.chatStore.stats() : null;
let est = null;
try { est = navigator.storage && navigator.storage.estimate ? await navigator.storage.estimate() : null; } catch (e) { est = null; }
@@ -442,9 +452,9 @@
row('Conversations', null, info ? fmt.int(info.conversations) : '—'),
row('Messages', null, info ? fmt.int(info.messages) : '—'),
row('Storage', info && info.mode === 'memory' ? 'Not saved: IndexedDB is unavailable in this browser mode.' : null,
- info && info.mode === 'memory' ? null : est ? `${fmt.compact(est.usage / 1024)} KB of about ${fmt.compact(est.quota / 1048576)} MB` : 'IndexedDB')),
+ info && info.mode === 'memory' ? null : est ? `${size(est.usage)} of about ${size(est.quota)}` : 'IndexedDB')),
h('div', { class: 'set-group' },
- row('Export all conversations', 'Downloads every conversation in this browser as one JSON file.', exportBtn),
+ row('Export all conversations', 'Downloads every conversation in this browser as one JSON file', exportBtn),
row('Delete all conversations', 'Removes them from this browser. This can\'t be undone.', delBtn)));
}
diff --git a/public/dashboard/status.js b/public/dashboard/status.js
index 35c3acc..6de5eb3 100644
--- a/public/dashboard/status.js
+++ b/public/dashboard/status.js
@@ -58,11 +58,8 @@
F.on('tick', () => { if (st.visible) tick(); });
}
- // The pool sentence over a manta ray in a shaft of light (MEDIA.md).
function hero(content) {
- const img = h('img', { class: 'hero-media', src: '/dashboard/media-manta.jpg', alt: '', decoding: 'async', 'aria-hidden': 'true' });
- img.style.setProperty('object-position', '50% 38%');
- return h('section', { class: 'hero', 'aria-label': F.t('Account pool') }, img, h('div', { class: 'hero-inner' }, content));
+ return h('section', { class: 'hero', 'aria-label': F.t('Account pool') }, h('div', { class: 'hero-inner' }, content));
}
function rowsInWindow(now) {
diff --git a/public/dashboard/usage.js b/public/dashboard/usage.js
index 02ac8db..880f9b9 100644
--- a/public/dashboard/usage.js
+++ b/public/dashboard/usage.js
@@ -48,7 +48,7 @@
breakdown),
h('div', { class: 'rule' }),
h('section', { class: 'section' }, h('div', { class: 'section-head' }, h('h3', { class: 'section-title' }, F.icon('accounts', 'title-icon'), h('span', { text: F.t('Lifetime by account') }))), lifetime));
- const hero = F.pageHero({ image: '/dashboard/media-bubbles.jpg', label: F.t('Usage'), position: '50% 30%' });
+ const hero = F.pageHero({ label: F.t('Usage') });
root.append(hero, h('div', { class: 'view-pad' },
h('div', { class: 'filter-row' }, windowSeg, accountSlot),
caveat, status, body));
diff --git a/scripts/lib/tui-menu.js b/scripts/lib/tui-menu.js
index da7c2c8..22bc903 100644
--- a/scripts/lib/tui-menu.js
+++ b/scripts/lib/tui-menu.js
@@ -67,6 +67,7 @@ const STRINGS = {
replaceDefault: 'Make DeepSeek the default model',
selectAgents: 'Select coding agents',
continueSetup: 'Continue',
+ skipSetup: 'Skip and continue',
setupComplete: 'Coding agents are configured',
setupCancelled: 'Setup cancelled. Come back anytime.',
selected: 'Selected',
@@ -151,6 +152,7 @@ const STRINGS = {
replaceDefault: 'Сделать DeepSeek моделью по умолчанию',
selectAgents: 'Выберите coding-агентов',
continueSetup: 'Продолжить',
+ skipSetup: 'Пропустить и продолжить',
setupComplete: 'Coding-агенты настроены',
setupCancelled: 'Настройка отменена. Возвращайтесь ещё.',
selected: 'Выбрано',
@@ -235,6 +237,7 @@ const STRINGS = {
replaceDefault: '将 DeepSeek 设为默认模型',
selectAgents: '选择 Coding Agent',
continueSetup: '继续',
+ skipSetup: '跳过并继续',
setupComplete: 'Coding Agent 配置完成',
setupCancelled: '设置已取消,欢迎下次再来。',
selected: '已选择',
@@ -610,6 +613,7 @@ async function runInteractiveMulti(getState, setLang, initial = [], options = {}
const items = [
...selectable.map(item => ({ ...item, checked: selected.has(item.id) })),
{ id: '__continue', label: t(snap.lang, 'continueSetup') },
+ ...(options.skipId ? [{ id: '__skip', label: t(snap.lang, 'skipSetup') }] : []),
];
index = Math.max(0, Math.min(index, items.length - 1));
const regions = renderFrame({
@@ -637,6 +641,7 @@ async function runInteractiveMulti(getState, setLang, initial = [], options = {}
if (hit.id.startsWith('item:')) {
index = Number(hit.id.slice(5));
const item = items[index];
+ if (item.id === '__skip') return { id: options.skipId, ids: [] };
if (item.id === '__continue') {
if (selected.size) return { id: 'continue', ids: [...selected] };
} else if (selected.has(item.id)) selected.delete(item.id);
@@ -657,11 +662,15 @@ async function runInteractiveMulti(getState, setLang, initial = [], options = {}
else if (key === 'lang-next' || key === 'right' || key === 'tab') setLang(cycleLang(snap.lang, 1));
else if (key === 'space') {
const item = items[index];
+ if (item.id === '__skip') return { id: options.skipId, ids: [] };
if (item.id === '__continue') {
if (selected.size) return { id: 'continue', ids: [...selected] };
} else if (selected.has(item.id)) selected.delete(item.id);
else selected.add(item.id);
- } else if (key === 'enter' && selected.size) return { id: 'continue', ids: [...selected] };
+ } else if (key === 'enter') {
+ if (items[index].id === '__skip') return { id: options.skipId, ids: [] };
+ if (selected.size) return { id: 'continue', ids: [...selected] };
+ }
}
} finally {
disableInteractive();
@@ -702,12 +711,15 @@ async function pickMany(getState, setLang, initial = [], options = {}) {
console.log(`\nFreeDeepseekAPI — ${snap.subtitle}`);
snap.items.forEach((item, i) => console.log(` ${i + 1} ${item.label}`));
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
- const answer = await new Promise(resolve => rl.question('Select numbers separated by commas: ', resolve));
+ const question = options.skipId
+ ? `Select numbers separated by commas (Enter: ${t(snap.lang, 'skipSetup')}): `
+ : 'Select numbers separated by commas: ';
+ const answer = await new Promise(resolve => rl.question(question, resolve));
rl.close();
const ids = String(answer || '').split(',')
.map(value => snap.items[Number(value.trim()) - 1]?.id)
.filter(Boolean);
- return ids.length ? { id: 'continue', ids } : { id: options.cancelId || 'quit', ids: [] };
+ return ids.length ? { id: 'continue', ids } : { id: options.skipId || options.cancelId || 'quit', ids: [] };
}
async function pause(lang) {
diff --git a/scripts/setup-agents.js b/scripts/setup-agents.js
index 259a1db..f696578 100755
--- a/scripts/setup-agents.js
+++ b/scripts/setup-agents.js
@@ -2153,8 +2153,9 @@ async function interactive(opts) {
}),
setLang,
selected,
- { cancelId: 'cancel' },
+ { cancelId: 'cancel', skipId: 'skip' },
);
+ if (chosen.id === 'skip') return null;
if (chosen.id === 'cancel') {
await pick(
() => ({
diff --git a/server.js b/server.js
index 264deb6..973102e 100755
--- a/server.js
+++ b/server.js
@@ -590,6 +590,93 @@ function clientIp(req) {
}
return raw || 'unknown';
}
+// Abuse limits for callers outside this machine. Loopback is never limited, so local agents keep
+// working. Only the socket address, or the hop a trusted proxy appended, decides who that is: the
+// left end of X-Forwarded-For is whatever the client sent.
+function socketIp(socket) {
+ const raw = String((socket && socket.remoteAddress) || '').replace(/^::ffff:/, '');
+ return raw === '::1' ? '127.0.0.1' : raw;
+}
+function guardIp(req) {
+ if (isTruthy(process.env.TRUST_PROXY)) {
+ const hops = String(req.headers['x-forwarded-for'] || '').split(',').map(hop => hop.trim()).filter(Boolean);
+ if (hops.length) return hops[hops.length - 1].replace(/^::ffff:/, '');
+ }
+ return socketIp(req.socket);
+}
+function createRemoteGuard({ perMinute = 600, authFailLimit = 10, authLockMs = 15 * 60 * 1000, perIpConnections = 64, maxTracked = 10000, now = Date.now } = {}) {
+ const clients = new Map();
+ const idle = (client, t) => client.sockets === 0 && client.lockedUntil <= t && t - client.windowStart >= 60000 && t - client.failStart >= authLockMs;
+ const prune = (t) => {
+ for (const [ip, client] of clients) if (idle(client, t)) clients.delete(ip);
+ // Still full under a flood of addresses: drop the oldest that holds no socket.
+ for (const [ip, client] of clients) {
+ if (clients.size < maxTracked) break;
+ if (client.sockets === 0) clients.delete(ip);
+ }
+ };
+ const clientFor = (ip) => {
+ let client = clients.get(ip);
+ if (client) return client;
+ const t = now();
+ if (clients.size >= maxTracked) prune(t);
+ client = { windowStart: t, count: 0, failStart: t, failures: 0, lockedUntil: 0, sockets: 0 };
+ clients.set(ip, client);
+ return client;
+ };
+ const seconds = (ms) => Math.max(1, Math.ceil(ms / 1000));
+ return {
+ // One request. Refused while the address is locked out or over its minute budget.
+ check(ip) {
+ const client = clientFor(ip);
+ const t = now();
+ if (client.lockedUntil > t) return { allowed: false, retryAfter: seconds(client.lockedUntil - t) };
+ if (!perMinute) return { allowed: true };
+ if (t - client.windowStart >= 60000) { client.windowStart = t; client.count = 0; }
+ client.count++;
+ if (client.count > perMinute) return { allowed: false, retryAfter: seconds(client.windowStart + 60000 - t) };
+ return { allowed: true };
+ },
+ // A wrong key. Enough of them inside the lock window close the door for that window.
+ failedAuth(ip) {
+ if (!authFailLimit) return;
+ const client = clientFor(ip);
+ const t = now();
+ if (t - client.failStart >= authLockMs) { client.failStart = t; client.failures = 0; }
+ client.failures++;
+ if (client.failures >= authFailLimit) { client.lockedUntil = t + authLockMs; client.failures = 0; }
+ },
+ // One TCP connection, before any HTTP is read.
+ connect(ip) {
+ const client = clientFor(ip);
+ if (client.lockedUntil > now()) return false;
+ if (perIpConnections && client.sockets >= perIpConnections) return false;
+ client.sockets++;
+ return true;
+ },
+ disconnect(ip) {
+ const client = clients.get(ip);
+ if (client && client.sockets > 0) client.sockets--;
+ },
+ size: () => clients.size,
+ };
+}
+const remoteGuard = createRemoteGuard({
+ perMinute: envNumber('PROXY_RATE_LIMIT_PER_MIN', 600),
+ authFailLimit: envNumber('PROXY_AUTH_FAIL_LIMIT', 10),
+ authLockMs: envNumber('PROXY_AUTH_LOCK_MS', 15 * 60 * 1000),
+ perIpConnections: envNumber('PROXY_MAX_CONNECTIONS_PER_IP', 64),
+});
+// Runs on every TCP connection, so a refused caller costs a close and no parsing. Without a proxy
+// key nothing outside this machine is served, so it does not get an answer either.
+function guardConnection(socket, { guard = remoteGuard, proxyKey = PROXY_API_KEY, trustProxy = isTruthy(process.env.TRUST_PROXY) } = {}) {
+ const ip = socketIp(socket);
+ if (isLoopbackHost(ip)) return;
+ if (!proxyKey) { socket.destroy(); return; }
+ if (trustProxy) return; // Every socket is the proxy's; the per-request limits see the real client.
+ if (!guard.connect(ip)) { socket.destroy(); return; }
+ socket.once('close', () => guard.disconnect(ip));
+}
// Flat estimate for every model (DeepSeek API list prices); the web path has no billing.
const USD_PER_M_INPUT = 0.22;
const USD_PER_M_OUTPUT = 0.66;
@@ -4758,6 +4845,16 @@ async function serveDashboard(req, res, pathname) {
// === HTTP Server ===
// The same handler serves HTTP, or HTTPS when both PEM files are set and readable.
async function handleRequest(req, res) {
+ const remoteIp = guardIp(req);
+ const remoteClient = !isLoopbackHost(remoteIp);
+ if (remoteClient) {
+ const gate = remoteGuard.check(remoteIp);
+ if (!gate.allowed) {
+ res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': String(gate.retryAfter), Connection: 'close' });
+ res.end(JSON.stringify({ error: { message: 'Too many requests from this address', type: 'rate_limit' } }));
+ return;
+ }
+ }
const requestOrigin = req.headers.origin;
res.setHeader('Vary', 'Origin');
if (!isBrowserOriginAllowed(requestOrigin)) {
@@ -4779,6 +4876,7 @@ async function handleRequest(req, res) {
const isPublicProbe = req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health' || url.pathname === '/readyz' || isDashboardPath(url.pathname));
if (!isPublicProbe && !isProxyAuthorized(req.headers.authorization)) {
+ if (remoteClient) remoteGuard.failedAuth(remoteIp);
res.writeHead(401, {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Bearer',
@@ -5883,6 +5981,12 @@ function createListenServer(handler) {
}
}
const server = createListenServer(handleRequest);
+// Slow or endless requests must not hold sockets open. Streamed answers are not affected: these
+// cover receiving the request only.
+server.headersTimeout = 15000;
+server.requestTimeout = 120000;
+server.maxConnections = envNumber('PROXY_MAX_CONNECTIONS', 1024);
+server.on('connection', (socket) => guardConnection(socket));
async function runAuthScript() {
const script = path.join(__dirname, 'scripts', 'deepseek_chrome_auth.js');
@@ -6159,6 +6263,9 @@ module.exports = {
clientIp,
modelCostUsd,
isProxyAuthorized,
+ createRemoteGuard,
+ guardConnection,
+ guardIp,
loadProxyApiKey,
requireProxyApiKey,
isLoopbackHost,
diff --git a/tests/agents-api.test.js b/tests/agents-api.test.js
index 87ad055..a7d7b31 100644
--- a/tests/agents-api.test.js
+++ b/tests/agents-api.test.js
@@ -497,6 +497,15 @@ function runCli(args, env) {
return spawnSync(process.execPath, ['scripts/setup-agents.js', ...args], { cwd: ROOT, encoding: 'utf8', env: { ...process.env, ...env } });
}
+test('the wizard can be skipped: it exits cleanly and writes nothing', () => {
+ const home = tmpdir();
+ const res = spawnSync(process.execPath, ['scripts/setup-agents.js'], { cwd: ROOT, encoding: 'utf8', input: '\n', env: { ...process.env, SETUP_HOME: home } });
+ assert.equal(res.status, 0, res.stderr);
+ assert.match(res.stdout, /Enter: /);
+ assert.doesNotMatch(res.stdout, /model=/);
+ assert.deepEqual(fs.readdirSync(home), []);
+});
+
test('the CLI writes a manifest, and --restore with a manifest deletes files setup created', () => {
const home = tmpdir();
put(home, '.config/opencode/opencode.json', '{"model":"openai/gpt"}\n');
diff --git a/tests/glyph-field.test.js b/tests/glyph-field.test.js
index c4d582a..9234153 100644
--- a/tests/glyph-field.test.js
+++ b/tests/glyph-field.test.js
@@ -102,7 +102,7 @@ test('glyph field: only a press starts a ripple; holding or dragging does nothin
assert.equal(presses.length, 1, 'a press on the composer or a button does not');
});
-test('settings headers, Add account, Updates and the access gate show ocean photos that ship and are credited; no video', () => {
+test('the access gate shows an ocean photo that ships and is credited; settings and Add account show none; no video', () => {
const dir = path.join(__dirname, '..', 'public', 'dashboard');
const credits = fs.readFileSync(path.join(dir, 'MEDIA.md'), 'utf8');
const used = new Set();
@@ -110,7 +110,7 @@ test('settings headers, Add account, Updates and the access gate show ocean phot
const code = fs.readFileSync(path.join(dir, file), 'utf8');
assert.doesNotMatch(code, /createElement\(['"]video['"]\)/, `${file} still plays a video`);
const photos = [...code.matchAll(/\/dashboard\/(media-[a-z0-9-]+\.jpg)/g)].map(m => m[1]);
- if (file !== 'app.css') assert.ok(photos.length, `${file} shows no photo`);
+ if (file !== 'app.css') assert.equal(photos.length, 0, `${file} still shows a photo`);
photos.forEach(p => used.add(p));
}
assert.match(fs.readFileSync(path.join(dir, 'app.css'), 'utf8'), /\.gate \{[^}]*\/dashboard\/media-[a-z0-9-]+\.jpg/, 'the access gate shows a photo');
diff --git a/tests/remote-guard.test.js b/tests/remote-guard.test.js
new file mode 100644
index 0000000..26829f7
--- /dev/null
+++ b/tests/remote-guard.test.js
@@ -0,0 +1,82 @@
+// Limits for callers outside this machine: request budget, wrong-key lockout, connection caps.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { EventEmitter } = require('node:events');
+
+const S = require('../server.js').__test;
+
+const clock = (start = 1000000) => { const c = () => c.t; c.t = start; return c; };
+const socket = (remoteAddress) => Object.assign(new EventEmitter(), { remoteAddress, destroyed: false, destroy() { this.destroyed = true; } });
+
+test('an address over its minute budget gets 429 until the minute ends', () => {
+ const now = clock();
+ const guard = S.createRemoteGuard({ perMinute: 2, now });
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+ assert.deepEqual(guard.check('203.0.113.5'), { allowed: false, retryAfter: 60 });
+ assert.equal(guard.check('203.0.113.6').allowed, true, 'another address has its own budget');
+ now.t += 60000;
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+});
+
+test('wrong keys lock the address out, even with the request budget off', () => {
+ const now = clock();
+ const guard = S.createRemoteGuard({ perMinute: 0, authFailLimit: 3, authLockMs: 1000, now });
+ guard.failedAuth('203.0.113.5');
+ guard.failedAuth('203.0.113.5');
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+ guard.failedAuth('203.0.113.5');
+ assert.deepEqual(guard.check('203.0.113.5'), { allowed: false, retryAfter: 1 });
+ assert.equal(guard.connect('203.0.113.5'), false, 'a locked address is refused at the socket');
+ now.t += 1000;
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+});
+
+test('wrong keys spread past the lock window never add up to a lockout', () => {
+ const now = clock();
+ const guard = S.createRemoteGuard({ authFailLimit: 2, authLockMs: 1000, now });
+ guard.failedAuth('203.0.113.5');
+ now.t += 1000;
+ guard.failedAuth('203.0.113.5');
+ assert.equal(guard.check('203.0.113.5').allowed, true);
+});
+
+test('the table of addresses stays bounded under a flood', () => {
+ const guard = S.createRemoteGuard({ maxTracked: 100, now: clock() });
+ for (let i = 0; i < 5000; i++) guard.check(`198.51.${i >> 8}.${i & 255}`);
+ assert.ok(guard.size() <= 100);
+});
+
+test('connections: loopback passes, keyless outsiders are closed, the cap frees on close', () => {
+ const guard = S.createRemoteGuard({ perIpConnections: 1 });
+ const local = socket('::ffff:127.0.0.1');
+ S.guardConnection(local, { guard, proxyKey: '', trustProxy: false });
+ assert.equal(local.destroyed, false);
+
+ const keyless = socket('203.0.113.5');
+ S.guardConnection(keyless, { guard, proxyKey: '', trustProxy: false });
+ assert.equal(keyless.destroyed, true);
+
+ const first = socket('203.0.113.5');
+ const second = socket('203.0.113.5');
+ S.guardConnection(first, { guard, proxyKey: 'k', trustProxy: false });
+ S.guardConnection(second, { guard, proxyKey: 'k', trustProxy: false });
+ assert.equal(first.destroyed, false);
+ assert.equal(second.destroyed, true);
+ first.emit('close');
+ const third = socket('203.0.113.5');
+ S.guardConnection(third, { guard, proxyKey: 'k', trustProxy: false });
+ assert.equal(third.destroyed, false);
+});
+
+test('a client cannot pose as loopback through X-Forwarded-For', () => {
+ const req = (forwarded) => ({ socket: { remoteAddress: '203.0.113.5' }, headers: { 'x-forwarded-for': forwarded } });
+ assert.equal(S.guardIp(req('127.0.0.1')), '203.0.113.5', 'ignored unless TRUST_PROXY is set');
+ const saved = process.env.TRUST_PROXY;
+ process.env.TRUST_PROXY = '1';
+ try {
+ assert.equal(S.guardIp(req('127.0.0.1, 198.51.100.9')), '198.51.100.9', 'the hop the proxy appended counts');
+ } finally {
+ if (saved === undefined) delete process.env.TRUST_PROXY; else process.env.TRUST_PROXY = saved;
+ }
+});
diff --git a/tests/unit.test.js b/tests/unit.test.js
index 3ccc0db..e2733e6 100644
--- a/tests/unit.test.js
+++ b/tests/unit.test.js
@@ -2018,7 +2018,7 @@ test('dashboardUrl points a browser at a reachable loopback address', () => {
test('dashboardEntry serves photos and video but never docs or paths outside the folder', () => {
const { dashboardEntry } = serverInternals;
assert.deepEqual(dashboardEntry('/dashboard/media-clip.mp4'), { file: 'media-clip.mp4', type: 'video/mp4', optional: true, media: true });
- assert.equal(dashboardEntry('/dashboard/media-manta.jpg').type, 'image/jpeg');
+ assert.equal(dashboardEntry('/dashboard/media-sea-glint.jpg').type, 'image/jpeg');
assert.equal(dashboardEntry('/dashboard/logo.png').type, 'image/png');
assert.ok(!dashboardEntry('/dashboard/app.css').media);
assert.ok(!dashboardEntry('/dashboard/core.js').media);
@@ -2064,19 +2064,19 @@ test('dashboard photos and video are not served when opened directly as a page',
await serveDashboard({ headers: dest ? { 'sec-fetch-dest': dest } : {} }, res, pathname);
return res;
};
- for (const pathname of ['/dashboard/media-manta.jpg', '/dashboard/geist.woff2', '/dashboard/logo.png']) {
+ for (const pathname of ['/dashboard/media-sea-glint.jpg', '/dashboard/geist.woff2', '/dashboard/logo.png']) {
for (const dest of ['document', 'iframe', 'embed', 'object']) {
const res = await call(pathname, dest);
assert.equal(res.status, 403, `${pathname} as ${dest}`);
assert.match(String(res.body), /media_direct_open/);
}
}
- const image = await call('/dashboard/media-manta.jpg', 'image');
+ const image = await call('/dashboard/media-sea-glint.jpg', 'image');
assert.equal(image.status, 200);
// Without this, the browser reuses the cached image for a direct open and never asks.
assert.match(String(image.headers.Vary), /Sec-Fetch-Dest/);
assert.equal((await call('/dashboard/geist.woff2', 'font')).status, 200);
- assert.equal((await call('/dashboard/media-manta.jpg')).status, 200, 'clients without Fetch Metadata still get the file');
+ assert.equal((await call('/dashboard/media-sea-glint.jpg')).status, 200, 'clients without Fetch Metadata still get the file');
assert.equal((await call('/dashboard', 'document')).status, 200, 'the page itself still opens');
});
diff --git a/tests/updater.test.js b/tests/updater.test.js
index ab920e8..4a152e7 100644
--- a/tests/updater.test.js
+++ b/tests/updater.test.js
@@ -282,4 +282,13 @@ test('with real git: check sees a new release, install fast-forwards and switche
assert.equal(JSON.parse(fs.readFileSync(path.join(user, 'package.json'), 'utf8')).version, '0.3.0');
assert.equal((await updater.status()).channel, 'latest');
assert.equal((await updater.check('latest')).upToDate, true);
+
+ // A branch ahead of the channel already has the release, so nothing is offered.
+ g(user, 'switch', '-c', 'work');
+ g(user, '-c', 'user.name=t', '-c', 'user.email=t@example.com', 'commit', '--allow-empty', '-m', 'Work in progress');
+ const ahead = await updater.check('latest');
+ assert.equal(ahead.upToDate, true);
+ assert.equal(ahead.switchOnly, false);
+ assert.equal(ahead.canInstall, false);
+ assert.deepEqual(ahead.changes, []);
});