@goodandready/dsh-ollama-cloud-provider 0.1.38 → 0.1.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.39 — 2026-11-15
4
+
5
+ - Security: loopback Host detection now requires an IP literal, so a DNS-rebinding page can no longer pass the read host gate or the update endpoint (#135).
6
+ - Security: endpoint URLs (`apiBase`, `openAiBase`, `usageUrl`, `balanceUrl`) must be absolute `http(s)` without embedded credentials or fragments; link-local and metadata addresses are refused, and an unsafe value falls back to the default (#136).
7
+ - Security: update status requires a local Host and same-origin Origin, while refresh, model refresh, connection test and endpoint discovery are single-flight and rate-limited; `/status` is cached for 10 seconds (#137).
8
+ - Reliability: HTTP 504/408 responses now rotate to the next account instead of failing the turn, matching the exception path (#138).
9
+ - Reliability: request-log compaction writes through a temporary file and renames it, so a concurrent reader never sees an empty or partial log (#142).
10
+ - Tooling: `deploy.sh install` works again (`local` outside a function aborted it), and `verify` fails instead of warning when `/health` is not 200 (#143).
11
+ - Documentation: added a Security section to all three READMEs and fixed the escaped version ranges in Requirements.
12
+
13
+ 175 tests.
14
+
3
15
  ## 0.1.38 — 2026-11-12
4
16
 
5
17
  - Architecture & Contracts: established canonical `docs/design/DESIGN.md` (following `project-design-contract`), `AGENTS.md`, `index.md`, `deploy.sh`, and `docs/deployment/DEPLOYMENT.md` (#127).
package/README.md CHANGED
@@ -111,8 +111,8 @@ graph LR
111
111
 
112
112
  ## Requirements
113
113
 
114
- - **DeepSeek Harness**: \0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0\ (desktop and web profiles).
115
- - **Node.js**: \>=22.0.0\.
114
+ - **DeepSeek Harness**: `0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0` (desktop and web profiles).
115
+ - **Node.js**: `>=22.0.0`.
116
116
  - **Ollama Cloud Account**: one or more active API keys from Ollama Cloud or a compatible proxy endpoint.
117
117
 
118
118
  ## Install
@@ -128,17 +128,17 @@ npm pack
128
128
  Install the published package:
129
129
 
130
130
  ```bash
131
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.38
131
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
132
132
  # DSH Desktop:
133
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.38
133
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
134
134
  ```
135
135
 
136
136
  Or install the packed tarball into a profile:
137
137
 
138
138
  ```bash
139
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
139
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
140
140
  # DSH Desktop:
141
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
141
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
142
142
  ```
143
143
 
144
144
  Restart dsh (or DSH Desktop), then pick **Ollama Cloud** in the model picker.
@@ -263,6 +263,13 @@ The Ollama Cloud settings page in DSH Desktop (dark theme): configured credentia
263
263
 
264
264
  ![Ollama Cloud settings](media/visual-verification.png)
265
265
 
266
+ ## Security
267
+
268
+ - Write routes require a loopback socket, a same-origin `Origin`/`Referer` and the host authentication check; a DNS name is never treated as loopback.
269
+ - API keys are resolved through the DSH credential service; the browser only learns whether a key is configured, never its value.
270
+ - Custom endpoint URLs must be absolute `http(s)` without embedded credentials or fragments; link-local and metadata addresses are refused.
271
+ - `/status` is cached for 10 seconds, while refresh, test and endpoint-discovery routes are single-flight and rate-limited.
272
+
266
273
  ## Limitations
267
274
 
268
275
  - **Cloud only.** Local `http://localhost:11434` is not registered as a route.
package/README.ru.md CHANGED
@@ -93,8 +93,8 @@ graph LR
93
93
 
94
94
  ## Requirements / Требования
95
95
 
96
- - **DeepSeek Harness**: \0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0\ (профили desktop и web).
97
- - **Node.js**: \>=22.0.0\.
96
+ - **DeepSeek Harness**: `0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0` (профили desktop и web).
97
+ - **Node.js**: `>=22.0.0`.
98
98
  - **Аккаунт Ollama Cloud**: один или несколько действующих API-ключей Ollama Cloud или совместимого прокси.
99
99
 
100
100
  ## Установка
@@ -110,17 +110,17 @@ npm pack
110
110
  Установка опубликованного пакета из npm:
111
111
 
112
112
  ```bash
113
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.38
113
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
114
114
  # DSH Desktop:
115
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.38
115
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
116
116
  ```
117
117
 
118
118
  Либо установка из упакованного tarball:
119
119
 
120
120
  ```bash
121
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
121
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
122
122
  # DSH Desktop:
123
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
123
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
124
124
  ```
125
125
 
126
126
  После установки перезапустите dsh (или DSH Desktop) и выберите **Ollama Cloud** в списке моделей.
@@ -216,6 +216,13 @@ modelAccountRules:
216
216
  - Нативный `/api/chat` передает NDJSON с подробной статистикой токенов в финальном объекте.
217
217
  - Совместимый эндпоинт OpenAI `/v1/chat/completions` поддерживает стриминг, инструменты, зрение (vision) и `reasoning_effort`.
218
218
 
219
+ ## Безопасность
220
+
221
+ - Write-маршруты требуют loopback-сокет, same-origin `Origin`/`Referer` и проверку подлинности хоста; DNS-имя никогда не считается loopback.
222
+ - Ключи читаются через сервис учётных данных DSH; браузер узнаёт только факт наличия ключа, но не его значение.
223
+ - Собственные адреса эндпоинтов должны быть абсолютными `http(s)` без встроенных учётных данных и фрагментов; link-local и metadata-адреса отклоняются.
224
+ - `/status` кэшируется на 10 секунд, а маршруты обновления, теста и поиска эндпоинтов ограничены по частоте и выполняются в единственном экземпляре.
225
+
219
226
  ## Ограничения
220
227
 
221
228
  - Только Ollama Cloud; локальный сервис `http://localhost:11434` данным плагином не регистрируется.
package/README.zh.md CHANGED
@@ -92,8 +92,8 @@ graph LR
92
92
 
93
93
  ## Requirements / 系统要求
94
94
 
95
- - **DeepSeek Harness**: \0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0\(桌面版与 Web 配置文件)。
96
- - **Node.js**: \>=22.0.0\。
95
+ - **DeepSeek Harness**: `0.2.0-rc.2 || >=0.2.1-rc.2 <0.2.3-0 || >=0.2.2-0 <0.2.3-0`(桌面版与 Web 配置文件)。
96
+ - **Node.js**: `>=22.0.0`。
97
97
  - **Ollama Cloud 账户**: 一个或多个有效的 Ollama Cloud API Key 或兼容的代理端点。
98
98
 
99
99
  ## 安装指南
@@ -109,17 +109,17 @@ npm pack
109
109
  从 npm 安装已发布版本:
110
110
 
111
111
  ```bash
112
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.38
112
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
113
113
  # DSH 桌面端:
114
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.38
114
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
115
115
  ```
116
116
 
117
117
  或通过打包文件安装:
118
118
 
119
119
  ```bash
120
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
120
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
121
121
  # DSH 桌面端:
122
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.38.tgz
122
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
123
123
  ```
124
124
 
125
125
  安装完成后重启 dsh 或 DSH 桌面端,在模型列表中选择 **Ollama Cloud** 即可。
@@ -186,6 +186,13 @@ DSH Desktop(暗黑主题)中的 Ollama Cloud 设置与用量面板:
186
186
  /ollama test [model] # 发送连通性测试请求
187
187
  ```
188
188
 
189
+ ## 安全说明
190
+
191
+ - 写入路由要求 loopback 套接字、同源 `Origin`/`Referer` 以及宿主机认证;DNS 名称永远不会被视为 loopback。
192
+ - API 密钥通过 DSH 凭据服务解析;浏览器只能获知是否已配置,无法读取密钥值。
193
+ - 自定义端点必须是完整的 `http(s)` 地址,不得包含账号密码或片段;link-local 与 metadata 地址会被拒绝。
194
+ - `/status` 缓存 10 秒;刷新、测试与端点发现路由为单飞并限流。
195
+
189
196
  ## 限制与注意事项
190
197
 
191
198
  - 仅支持 Ollama Cloud 云端模型;不会注册本地 `http://localhost:11434` 路由。
package/lib/adapter.js CHANGED
@@ -220,7 +220,7 @@ var OllamaCloudAdapter = class extends LlmAdapter {
220
220
  if (canRotate) continue;
221
221
  throw error;
222
222
  }
223
- const retryable = error.code === "INVALID_CREDENTIAL" || error.code === "RATE_LIMIT" || error.code === "QUOTA" || error.code === "SERVER";
223
+ const retryable = this.isTransient(error) || error.code === "INVALID_CREDENTIAL";
224
224
  const credentialOrQuota = error.code === "INVALID_CREDENTIAL" || error.code === "RATE_LIMIT" || error.code === "QUOTA";
225
225
  if (retryable) {
226
226
  if (canRotate || credentialOrQuota) this.markCooldown(entry.key, response.status, response.headers, error.code);
package/lib/config.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { endpointOr } from "./endpoints.js";
1
2
  import z from "@deepseek-ai/schemastery";
2
3
  // src/config.ts
3
4
  const NS = "llm-ollama-cloud";
@@ -6,7 +7,7 @@ const DEFAULT_API_BASE = "https://ollama.com";
6
7
  const DEFAULT_OPENAI_BASE = "https://ollama.com/v1";
7
8
  const DEFAULT_USAGE_URL = "https://ollama.com/api/usage";
8
9
  const DEFAULT_BALANCE_URL = "https://ollama.com/api/balance";
9
- const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.38";
10
+ const DEFAULT_USER_AGENT = "dsh-ollama-cloud-provider/0.1.39";
10
11
  const DEFAULT_CONTEXT_WINDOW = 131072;
11
12
  const DEFAULT_MAX_TOKENS = 32768;
12
13
  const DEFAULT_GENERATE_MAX_TOKENS = 131072;
@@ -229,10 +230,10 @@ function resolveConfig(config) {
229
230
  return {
230
231
  apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv.trim() !== "" ? config.apiKeyEnv.trim() : DEFAULT_API_KEY_ENV,
231
232
  ...apiKey === void 0 ? {} : { apiKey },
232
- apiBase: typeof config.apiBase === "string" && config.apiBase !== "" ? config.apiBase : DEFAULT_API_BASE,
233
- openAiBase: typeof config.openAiBase === "string" && config.openAiBase !== "" ? config.openAiBase : DEFAULT_OPENAI_BASE,
234
- usageUrl: typeof config.usageUrl === "string" && config.usageUrl !== "" ? config.usageUrl : DEFAULT_USAGE_URL,
235
- balanceUrl: typeof config.balanceUrl === "string" && config.balanceUrl !== "" ? config.balanceUrl : DEFAULT_BALANCE_URL,
233
+ apiBase: endpointOr(config.apiBase, "apiBase", DEFAULT_API_BASE),
234
+ openAiBase: endpointOr(config.openAiBase, "openAiBase", DEFAULT_OPENAI_BASE),
235
+ usageUrl: endpointOr(config.usageUrl, "usageUrl", DEFAULT_USAGE_URL),
236
+ balanceUrl: endpointOr(config.balanceUrl, "balanceUrl", DEFAULT_BALANCE_URL),
236
237
  transport: config.transport === "openai-chat" ? "openai-chat" : "native",
237
238
  modelTransports: transportRecord(config.modelTransports),
238
239
  requestTimeoutMs: positiveInt(config.requestTimeoutMs, 3e5),
package/lib/discovery.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { sanitizeUrl } from "./sanitize.js";
2
- import { lookup } from "node:dns/promises";
3
2
  import { isIP } from "node:net";
3
+ import { lookup } from "node:dns/promises";
4
4
  // src/discovery.ts
5
5
  const DISCOVERY_TIMEOUT_MS = 15e3;
6
6
  var DiscoveryError = class extends Error {
@@ -0,0 +1,58 @@
1
+ import { isIP } from "node:net";
2
+ // src/endpoints.ts
3
+ function isLinkLocalHost(hostname) {
4
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
5
+ if (host === "0.0.0.0" || host === "::") return true;
6
+ const family = isIP(host);
7
+ if (family === 4) return host.startsWith("169.254.");
8
+ if (family === 6) return /^fe[89ab]/.test(host);
9
+ return false;
10
+ }
11
+ /**
12
+ * Endpoint URLs carry the API key, so only an absolute http(s) URL without
13
+ * embedded credentials or a fragment is accepted, and link-local/metadata
14
+ * addresses are refused.
15
+ */
16
+ function checkEndpoint(field, value) {
17
+ if (typeof value !== "string" || value.trim() === "") return {
18
+ ok: false,
19
+ error: `${field} must be a non-empty URL`
20
+ };
21
+ const candidate = value.trim();
22
+ let url;
23
+ try {
24
+ url = new URL(candidate);
25
+ } catch {
26
+ return {
27
+ ok: false,
28
+ error: `${field} must be an absolute URL`
29
+ };
30
+ }
31
+ if (url.protocol !== "http:" && url.protocol !== "https:") return {
32
+ ok: false,
33
+ error: `${field} must use http or https`
34
+ };
35
+ if (url.username !== "" || url.password !== "") return {
36
+ ok: false,
37
+ error: `${field} must not embed credentials`
38
+ };
39
+ if (url.hash !== "") return {
40
+ ok: false,
41
+ error: `${field} must not contain a fragment`
42
+ };
43
+ if (isLinkLocalHost(url.hostname)) return {
44
+ ok: false,
45
+ error: `${field} must not target a link-local address`
46
+ };
47
+ return {
48
+ ok: true,
49
+ value: candidate
50
+ };
51
+ }
52
+ function endpointOr(value, field, fallback) {
53
+ const checked = checkEndpoint(field, value);
54
+ return checked.ok ? checked.value ?? fallback : fallback;
55
+ }
56
+ export { checkEndpoint, endpointOr };
57
+
58
+ //# sourceMappingURL=endpoints.js.map
package/lib/local-host.js CHANGED
@@ -1,18 +1,27 @@
1
1
  import { networkInterfaces } from "node:os";
2
2
  import { isIP } from "node:net";
3
3
  // src/local-host.ts
4
- const LOOPBACK = /* @__PURE__ */ new Set([
5
- "localhost",
6
- "localhost.",
7
- "::1",
8
- "[::1]"
9
- ]);
4
+ const LOOPBACK_NAMES = /* @__PURE__ */ new Set(["localhost", "localhost."]);
10
5
  function normalize(value) {
11
6
  return value.toLowerCase().replace(/^\[|\]$/g, "").replace(/%.+$/, "");
12
7
  }
8
+ /**
9
+ * A DNS name is never loopback: only a literal IPv4/IPv6 loopback address is.
10
+ * Prefix matching on the raw string would accept `127.0.0.1.attacker.example`,
11
+ * which is exactly the host a DNS-rebinding page presents.
12
+ */
13
+ function isLoopbackAddress(value) {
14
+ if (value === void 0) return false;
15
+ const address = normalize(value);
16
+ const family = isIP(address);
17
+ if (family === 4) return address.startsWith("127.");
18
+ if (family === 6) return address === "::1" || address.startsWith("::ffff:127.");
19
+ return false;
20
+ }
13
21
  function isLoopbackHostname(value) {
14
22
  const hostname = normalize(value);
15
- return LOOPBACK.has(hostname) || hostname.startsWith("127.") || hostname.startsWith("::ffff:127.");
23
+ if (LOOPBACK_NAMES.has(hostname)) return true;
24
+ return isLoopbackAddress(hostname);
16
25
  }
17
26
  function localAddresses() {
18
27
  const addresses = /* @__PURE__ */ new Set();
@@ -33,6 +42,6 @@ function authorityHostname(value) {
33
42
  return;
34
43
  }
35
44
  }
36
- export { authorityHostname, isLocalHostname, isLoopbackHostname };
45
+ export { authorityHostname, isLocalHostname, isLoopbackAddress, isLoopbackHostname };
37
46
 
38
47
  //# sourceMappingURL=local-host.js.map
@@ -1,4 +1,5 @@
1
1
  import { bestEffortFailed } from "./best-effort.js";
2
+ import { authorityHostname, isLocalHostname, isLoopbackAddress, isLoopbackHostname } from "./local-host.js";
2
3
  import { existsSync, readFileSync, statSync } from "node:fs";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
@@ -14,13 +15,9 @@ function header(request, name) {
14
15
  const value = request.headers?.[name];
15
16
  return Array.isArray(value) ? value[0] : value;
16
17
  }
17
- function isLoopback(value) {
18
- const address = value?.toLowerCase().replace(/^\[|\]$/g, "");
19
- return address === "localhost" || address === "localhost." || address === "::1" || address?.startsWith("127.") === true || address?.startsWith("::ffff:127.") === true;
20
- }
21
18
  function isTrustedUpdateRequest(request) {
22
19
  if (header(request, UPDATE_HEADER) !== "1") return false;
23
- if (!isLoopback(request.socket?.remoteAddress)) return false;
20
+ if (!isLoopbackAddress(request.socket?.remoteAddress)) return false;
24
21
  const site = header(request, "sec-fetch-site");
25
22
  if (site !== void 0 && site !== "same-origin") return false;
26
23
  const origin = header(request, "origin");
@@ -28,7 +25,25 @@ function isTrustedUpdateRequest(request) {
28
25
  if (origin === void 0 || host === void 0) return false;
29
26
  try {
30
27
  const url = new URL(origin);
31
- return (url.protocol === "http:" || url.protocol === "https:") && isLoopback(url.hostname) && url.host === host;
28
+ return (url.protocol === "http:" || url.protocol === "https:") && isLoopbackHostname(url.hostname) && url.host === host;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+ /**
34
+ * Read-only status must also come from the local UI: a remote page that reaches
35
+ * the port through DNS rebinding presents its own host name and is refused.
36
+ */
37
+ function isTrustedReadRequest(request) {
38
+ const host = header(request, "host");
39
+ if (host === void 0 || host === "") return false;
40
+ const hostname = authorityHostname(host);
41
+ if (hostname === void 0 || !isLocalHostname(hostname)) return false;
42
+ const origin = header(request, "origin");
43
+ if (origin === void 0 || origin === "") return true;
44
+ try {
45
+ const url = new URL(origin);
46
+ return (url.protocol === "http:" || url.protocol === "https:") && url.host === host && isLocalHostname(url.hostname);
32
47
  } catch {
33
48
  return false;
34
49
  }
@@ -84,13 +99,16 @@ function profileFromArgv(argv) {
84
99
  };
85
100
  }
86
101
  }
102
+ const RUNTIME_CACHE_MS = 3e4;
103
+ let runtimeCache;
87
104
  function runtime() {
105
+ if (runtimeCache !== void 0 && Date.now() - runtimeCache.at < RUNTIME_CACHE_MS) return runtimeCache.value;
88
106
  const fromArgv = profileFromArgv(process.argv);
89
107
  const profileDir = resolve(process.env.DSH_PROFILE_DIR ?? fromArgv?.dir ?? resolve(homedir(), ".dsh", "profiles", "web"));
90
108
  const selected = process.env.DSH_PROFILE_NAME ?? profileNameFromArgv(process.argv) ?? fromArgv?.name;
91
109
  const profileName = validProfileName(selected) ? selected : validProfileName(basename(profileDir)) ? basename(profileDir) : "web";
92
110
  const cliEntry = findDshCliEntry();
93
- return cliEntry === void 0 ? {
111
+ const value = cliEntry === void 0 ? {
94
112
  profileName,
95
113
  profileDir
96
114
  } : {
@@ -98,6 +116,11 @@ function runtime() {
98
116
  profileDir,
99
117
  cliEntry
100
118
  };
119
+ runtimeCache = {
120
+ at: Date.now(),
121
+ value
122
+ };
123
+ return value;
101
124
  }
102
125
  function parseSemver(value) {
103
126
  const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
@@ -240,6 +263,10 @@ function registerPluginUpdater(ctx, options) {
240
263
  try {
241
264
  const target = runtime();
242
265
  if (request.method === "GET" || request.method === "HEAD") {
266
+ if (!isTrustedReadRequest(request)) {
267
+ json(response, 403, { error: "Rejected non-local update status request." });
268
+ return;
269
+ }
243
270
  const payload = await status(options, target);
244
271
  response.writeHead(200, {
245
272
  "content-type": "application/json; charset=utf-8",
@@ -288,6 +315,6 @@ function registerPluginUpdater(ctx, options) {
288
315
  }
289
316
  });
290
317
  }
291
- export { isNewerVersion, isTrustedUpdateRequest, registerPluginUpdater };
318
+ export { isNewerVersion, isTrustedReadRequest, isTrustedUpdateRequest, registerPluginUpdater };
292
319
 
293
320
  //# sourceMappingURL=plugin-updater.js.map
@@ -1,5 +1,5 @@
1
1
  import { bestEffortFailed } from "./best-effort.js";
2
- import { appendFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  // src/request-log.ts
@@ -57,7 +57,16 @@ async function compactRequestLog(maxBytes = MAX_LOG_BYTES, keepLines = KEEP_LINE
57
57
  if ((await stat(path)).size <= maxBytes) return;
58
58
  const lines = (await readFile(path, "utf8")).split("\n").filter((line) => line !== "");
59
59
  if (lines.length <= keepLines) return;
60
- await writeFile(path, `${lines.slice(-keepLines).join("\n")}\n`, "utf8");
60
+ const temporary = `${path}.tmp`;
61
+ try {
62
+ await writeFile(temporary, `${lines.slice(-keepLines).join("\n")}\n`, "utf8");
63
+ await rename(temporary, path);
64
+ } catch (error) {
65
+ await rm(temporary, { force: true }).catch((caught) => {
66
+ bestEffortFailed("request log compaction cleanup failed", caught);
67
+ });
68
+ throw error;
69
+ }
61
70
  } catch (error) {
62
71
  bestEffortFailed("request log compaction failed", error);
63
72
  }
@@ -0,0 +1,25 @@
1
+ // src/route-guard.ts
2
+ /**
3
+ * Serialises one expensive route: at most one request in flight, and no more
4
+ * than one start per `minIntervalMs`.
5
+ */
6
+ function createRouteGuard(minIntervalMs, now = Date.now) {
7
+ let last = Number.NEGATIVE_INFINITY;
8
+ let inflight = false;
9
+ return {
10
+ begin() {
11
+ if (inflight) return "busy";
12
+ const at = now();
13
+ if (at - last < minIntervalMs) return "rate";
14
+ last = at;
15
+ inflight = true;
16
+ return "ok";
17
+ },
18
+ end() {
19
+ inflight = false;
20
+ }
21
+ };
22
+ }
23
+ export { createRouteGuard };
24
+
25
+ //# sourceMappingURL=route-guard.js.map
package/lib/routes.js CHANGED
@@ -3,11 +3,13 @@ import { readModelAnalytics } from "./analytics.js";
3
3
  import { clearCatalogCache, effectiveModel, modelAvailable, modelVisible, refreshCatalog } from "./catalog.js";
4
4
  import { NS } from "./config.js";
5
5
  import { discoverModels } from "./discovery.js";
6
+ import { checkEndpoint } from "./endpoints.js";
6
7
  import { priceFor } from "./pricing.js";
7
8
  import { authorityHostname, isLocalHostname } from "./local-host.js";
8
9
  import { PROVIDER } from "./provider-ids.js";
10
+ import { createRouteGuard } from "./route-guard.js";
9
11
  import { publicConfig } from "./routes-public.js";
10
- import { probeService } from "./status.js";
12
+ import { clearStatusCache, probeServiceCached } from "./status.js";
11
13
  import { cleanAccounts, cleanBooleanRecord, cleanManualModels, cleanModelAccountRules, cleanModelOverrides, cleanNumberRecord, cleanPrices, cleanStringArray, cleanTransports, isCredentialRef, normalizeCredentialRef } from "./routes-values.js";
12
14
  import { safeErrorMessage } from "./sanitize.js";
13
15
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
@@ -213,10 +215,22 @@ function configOps(patch) {
213
215
  set("apiKeyEnv", ref);
214
216
  }
215
217
  }
216
- if ("apiBase" in patch) set("apiBase", patch.apiBase);
217
- if ("openAiBase" in patch) set("openAiBase", patch.openAiBase);
218
- if ("usageUrl" in patch) set("usageUrl", patch.usageUrl);
219
- if ("balanceUrl" in patch) set("balanceUrl", patch.balanceUrl);
218
+ for (const field of [
219
+ "apiBase",
220
+ "openAiBase",
221
+ "usageUrl",
222
+ "balanceUrl"
223
+ ]) {
224
+ if (!(field in patch)) continue;
225
+ const raw = patch[field];
226
+ if (raw === null || raw === void 0 || typeof raw === "string" && raw.trim() === "") {
227
+ set(field, void 0);
228
+ continue;
229
+ }
230
+ const checked = checkEndpoint(field, raw);
231
+ if (!checked.ok) throw new Error(checked.error);
232
+ set(field, checked.value);
233
+ }
220
234
  if ("transport" in patch) set("transport", patch.transport);
221
235
  if ("modelTransports" in patch) set("modelTransports", cleanTransports(patch.modelTransports));
222
236
  if ("requestTimeoutMs" in patch) set("requestTimeoutMs", patch.requestTimeoutMs);
@@ -389,6 +403,10 @@ function applyRoutes(ctx, web, deps) {
389
403
  handler
390
404
  }));
391
405
  };
406
+ const refreshGuard = createRouteGuard(2e3);
407
+ const modelsGuard = createRouteGuard(2e3);
408
+ const discoverGuard = createRouteGuard(1e3);
409
+ const testGuard = createRouteGuard(2e3);
392
410
  const readOnly = (req, res) => {
393
411
  if (req.method !== "GET") {
394
412
  json(res, 405, { error: "GET required" });
@@ -440,7 +458,7 @@ function applyRoutes(ctx, web, deps) {
440
458
  route("/dsh-ollama/status", async (req, res) => {
441
459
  if (!readOnly(req, res)) return;
442
460
  try {
443
- json(res, 200, await probeService(deps.config(), fetch));
461
+ json(res, 200, await probeServiceCached(deps.config(), fetch));
444
462
  } catch (error) {
445
463
  json(res, 200, {
446
464
  ok: false,
@@ -582,90 +600,128 @@ function applyRoutes(ctx, web, deps) {
582
600
  });
583
601
  route("/dsh-ollama/refresh", async (req, res) => {
584
602
  if (!await requirePost(req, res, verifyHost)) return;
585
- deps.usage.clear();
586
- await refreshAndState(ctx, deps, res);
603
+ const gate = refreshGuard.begin();
604
+ if (gate !== "ok") {
605
+ json(res, 429, { error: gate === "busy" ? "request already in progress" : "rate limited; retry shortly" });
606
+ return;
607
+ }
608
+ try {
609
+ clearStatusCache();
610
+ deps.usage.clear();
611
+ await refreshAndState(ctx, deps, res);
612
+ } finally {
613
+ refreshGuard.end();
614
+ }
587
615
  });
588
616
  route("/dsh-ollama/models/refresh", async (req, res) => {
589
617
  if (!await requirePost(req, res, verifyHost)) return;
590
- clearCatalogCache();
591
- deps.usage.clear();
618
+ const gate = modelsGuard.begin();
619
+ if (gate !== "ok") {
620
+ json(res, 429, { error: gate === "busy" ? "request already in progress" : "rate limited; retry shortly" });
621
+ return;
622
+ }
592
623
  try {
593
- await refreshCatalog(deps.config(), fetch, true);
594
- } catch (error) {
595
- bestEffortFailed("catalog refresh failed", error);
624
+ clearCatalogCache();
625
+ clearStatusCache();
626
+ deps.usage.clear();
627
+ try {
628
+ await refreshCatalog(deps.config(), fetch, true);
629
+ } catch (error) {
630
+ bestEffortFailed("catalog refresh failed", error);
631
+ }
632
+ await refreshAndState(ctx, deps, res);
633
+ } finally {
634
+ modelsGuard.end();
596
635
  }
597
- await refreshAndState(ctx, deps, res);
598
636
  });
599
637
  route("/dsh-ollama/discover", async (req, res) => {
600
638
  if (!await requirePost(req, res, verifyHost)) return;
601
- let body;
602
- try {
603
- body = await readJson(req);
604
- } catch (error) {
605
- json(res, 400, { error: error instanceof Error ? error.message : "invalid body" });
639
+ const gate = discoverGuard.begin();
640
+ if (gate !== "ok") {
641
+ json(res, 429, { error: gate === "busy" ? "request already in progress" : "rate limited; retry shortly" });
606
642
  return;
607
643
  }
608
- const apiBase = typeof body.apiBase === "string" ? body.apiBase : "";
609
- const apiKey = typeof body.apiKey === "string" ? body.apiKey : "";
610
644
  try {
611
- json(res, 200, await discoverModels(apiBase, apiKey, deps.discoveryFetch));
612
- } catch (error) {
613
- json(res, 400, { error: error instanceof Error ? error.message : "discovery failed" });
645
+ let body;
646
+ try {
647
+ body = await readJson(req);
648
+ } catch (error) {
649
+ json(res, 400, { error: error instanceof Error ? error.message : "invalid body" });
650
+ return;
651
+ }
652
+ const apiBase = typeof body.apiBase === "string" ? body.apiBase : "";
653
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey : "";
654
+ try {
655
+ json(res, 200, await discoverModels(apiBase, apiKey, deps.discoveryFetch));
656
+ } catch (error) {
657
+ json(res, 400, { error: error instanceof Error ? error.message : "discovery failed" });
658
+ }
659
+ } finally {
660
+ discoverGuard.end();
614
661
  }
615
662
  });
616
663
  route("/dsh-ollama/test", async (req, res) => {
617
664
  if (!await requirePost(req, res, verifyHost)) return;
618
- let body;
619
- try {
620
- body = await readJson(req);
621
- } catch (error) {
622
- json(res, 400, { error: error instanceof Error ? error.message : "invalid body" });
665
+ const gate = testGuard.begin();
666
+ if (gate !== "ok") {
667
+ json(res, 429, { error: gate === "busy" ? "request already in progress" : "rate limited; retry shortly" });
623
668
  return;
624
669
  }
625
- const model = typeof body.model === "string" && body.model !== "" ? body.model : "gpt-oss:120b";
626
- const started = Date.now();
627
- const controller = new AbortController();
628
- const timer = setTimeout(() => controller.abort(), 6e4);
629
- let text = "";
630
- let finish;
631
670
  try {
632
- const options = {
633
- provider: PROVIDER,
634
- model,
635
- messages: [{
636
- role: "user",
637
- content: [{
638
- type: "text",
639
- text: "Reply with exactly: OK"
640
- }]
641
- }],
642
- reasoningEffort: ReasoningEffortId("off"),
643
- maxTokens: 64,
644
- signal: controller.signal
645
- };
646
- let reasoning = "";
647
- for await (const chunk of deps.adapter.stream(options)) if (chunk.type === "text-delta") text += chunk.text;
648
- else if (chunk.type === "reasoning-delta") reasoning += chunk.text;
649
- else if (chunk.type === "finish") finish = chunk.reason;
650
- const reply = text === "" ? reasoning : text;
651
- json(res, 200, {
652
- ok: true,
653
- model,
654
- provider: PROVIDER,
655
- latencyMs: Date.now() - started,
656
- text: reply.slice(0, 200),
657
- finish
658
- });
659
- } catch (error) {
660
- json(res, 200, {
661
- ok: false,
662
- model,
663
- provider: PROVIDER,
664
- latencyMs: Date.now() - started,
665
- error: controller.signal.aborted ? "timeout" : error instanceof Error ? error.message : "test failed"
666
- });
671
+ let body;
672
+ try {
673
+ body = await readJson(req);
674
+ } catch (error) {
675
+ json(res, 400, { error: error instanceof Error ? error.message : "invalid body" });
676
+ return;
677
+ }
678
+ const model = typeof body.model === "string" && body.model !== "" ? body.model : "gpt-oss:120b";
679
+ const started = Date.now();
680
+ const controller = new AbortController();
681
+ const timer = setTimeout(() => controller.abort(), 6e4);
682
+ let text = "";
683
+ let finish;
684
+ try {
685
+ const options = {
686
+ provider: PROVIDER,
687
+ model,
688
+ messages: [{
689
+ role: "user",
690
+ content: [{
691
+ type: "text",
692
+ text: "Reply with exactly: OK"
693
+ }]
694
+ }],
695
+ reasoningEffort: ReasoningEffortId("off"),
696
+ maxTokens: 64,
697
+ signal: controller.signal
698
+ };
699
+ let reasoning = "";
700
+ for await (const chunk of deps.adapter.stream(options)) if (chunk.type === "text-delta") text += chunk.text;
701
+ else if (chunk.type === "reasoning-delta") reasoning += chunk.text;
702
+ else if (chunk.type === "finish") finish = chunk.reason;
703
+ const reply = text === "" ? reasoning : text;
704
+ json(res, 200, {
705
+ ok: true,
706
+ model,
707
+ provider: PROVIDER,
708
+ latencyMs: Date.now() - started,
709
+ text: reply.slice(0, 200),
710
+ finish
711
+ });
712
+ } catch (error) {
713
+ json(res, 200, {
714
+ ok: false,
715
+ model,
716
+ provider: PROVIDER,
717
+ latencyMs: Date.now() - started,
718
+ error: controller.signal.aborted ? "timeout" : error instanceof Error ? error.message : "test failed"
719
+ });
720
+ } finally {
721
+ clearTimeout(timer);
722
+ }
667
723
  } finally {
668
- clearTimeout(timer);
724
+ testGuard.end();
669
725
  }
670
726
  });
671
727
  ctx.effect(() => () => {
package/lib/status.js CHANGED
@@ -37,6 +37,24 @@ async function probeService(config, fetchImpl = fetch) {
37
37
  clearTimeout(timer);
38
38
  }
39
39
  }
40
- export { probeService };
40
+ const STATUS_CACHE_MS = 1e4;
41
+ let cached;
42
+ function clearStatusCache() {
43
+ cached = void 0;
44
+ }
45
+ /** Cached probe: repeated UI polls must not fan out external requests. */
46
+ async function probeServiceCached(config, fetchImpl = fetch, now = Date.now) {
47
+ const key = tagsUrlFor(config);
48
+ const at = now();
49
+ if (cached !== void 0 && cached.key === key && at - cached.at < STATUS_CACHE_MS) return cached.value;
50
+ const value = await probeService(config, fetchImpl);
51
+ cached = {
52
+ key,
53
+ at,
54
+ value
55
+ };
56
+ return value;
57
+ }
58
+ export { clearStatusCache, probeService, probeServiceCached };
41
59
 
42
60
  //# sourceMappingURL=status.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-ollama-cloud-provider",
3
- "version": "0.1.38",
3
+ "version": "0.1.39",
4
4
  "description": "Ollama Cloud LLM provider plugin for DeepSeek Harness (dsh).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -73,7 +73,7 @@
73
73
  "build": "tsdown",
74
74
  "prepare": "tsdown 1>&2",
75
75
  "typecheck": "tsc --noEmit",
76
- "test": "node --import tsx --test --test-concurrency=1 tests/core.test.ts tests/usage.test.ts tests/adapter.test.ts tests/routes.test.ts tests/native.test.ts tests/openai-chat.test.ts tests/commands.test.ts tests/tui-settings.test.ts tests/analytics.test.ts tests/apply.test.ts tests/account-rules.test.ts tests/request-log.test.ts tests/image-budget.test.ts tests/tool-schema.test.ts tests/tools.test.ts tests/plugin-updater.test.ts tests/compat.test.ts tests/status.test.ts tests/settings-draft.test.ts tests/update-state.test.ts tests/ui-render.test.tsx tests/update-card-view.test.tsx tests/web.test.ts tests/mock-ollama.test.ts tests/reasoning.test.ts tests/catalog-cache.test.ts tests/attempt.test.ts tests/model-groups.test.tsx tests/discovery.test.ts tests/sanitize.test.ts tests/retry.test.ts tests/provider-card.test.tsx tests/host-verification.test.ts tests/ui-actions.test.tsx tests/tool-call-id.test.ts",
76
+ "test": "node --import tsx --test --test-concurrency=1 tests/core.test.ts tests/usage.test.ts tests/adapter.test.ts tests/routes.test.ts tests/native.test.ts tests/openai-chat.test.ts tests/commands.test.ts tests/tui-settings.test.ts tests/analytics.test.ts tests/apply.test.ts tests/account-rules.test.ts tests/request-log.test.ts tests/image-budget.test.ts tests/tool-schema.test.ts tests/tools.test.ts tests/plugin-updater.test.ts tests/compat.test.ts tests/status.test.ts tests/settings-draft.test.ts tests/update-state.test.ts tests/ui-render.test.tsx tests/update-card-view.test.tsx tests/web.test.ts tests/mock-ollama.test.ts tests/reasoning.test.ts tests/catalog-cache.test.ts tests/attempt.test.ts tests/model-groups.test.tsx tests/discovery.test.ts tests/sanitize.test.ts tests/retry.test.ts tests/provider-card.test.tsx tests/host-verification.test.ts tests/ui-actions.test.tsx tests/tool-call-id.test.ts tests/deploy-script.test.ts tests/endpoints.test.ts tests/route-guard.test.ts",
77
77
  "check": "npm run typecheck && npm test && npm run build && npm run pack:check",
78
78
  "release": "npm run check && mkdir -p dist && npm pack --pack-destination dist",
79
79
  "sync:models": "node scripts/sync-models.mjs",