dsh-rest-api 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +135 -2
- package/README.zh.md +150 -0
- package/cordis.patch.yml +103 -0
- package/icon.svg +9 -0
- package/lib/client.js +803 -0
- package/lib/http.js +381 -0
- package/lib/index.js +182 -0
- package/lib/runtime.js +1384 -0
- package/openapi.yaml +303 -0
- package/package.json +101 -4
package/lib/http.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rest-api HTTP 层工具函数:鉴权判定、参数解析与严格校验、SSE 帧写入、响应预算裁剪与密钥脱敏。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { timingSafeEqual } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
const ALLOWED_PROMPT_FIELDS = new Set([
|
|
8
|
+
"request_id",
|
|
9
|
+
"prompt",
|
|
10
|
+
"preset",
|
|
11
|
+
"workspace_dir",
|
|
12
|
+
"workspace_title",
|
|
13
|
+
"provider",
|
|
14
|
+
"model",
|
|
15
|
+
"webhook_url",
|
|
16
|
+
"webhook_headers",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
/** 规范化路由前缀(始终以单个 `/` 开头且无末尾 `/`)。 */
|
|
20
|
+
export function normalizePrefix(prefix) {
|
|
21
|
+
const trimmed = String(prefix ?? "/v1").trim().replace(/\/+$/, "");
|
|
22
|
+
if (trimmed === "" || trimmed === "/") return "/v1";
|
|
23
|
+
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 校验并解码单段路径参数(防止目录穿越与空段)。 */
|
|
27
|
+
export function parsePathSegment(rawSegment) {
|
|
28
|
+
let decoded;
|
|
29
|
+
try {
|
|
30
|
+
decoded = decodeURIComponent(rawSegment);
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (
|
|
35
|
+
decoded.length === 0 ||
|
|
36
|
+
decoded.length > 256 ||
|
|
37
|
+
decoded.includes("/") ||
|
|
38
|
+
decoded.includes("\\") ||
|
|
39
|
+
decoded.includes("\0") ||
|
|
40
|
+
decoded === "." ||
|
|
41
|
+
decoded === ".."
|
|
42
|
+
) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return decoded;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 判断远程 socket 地址是否属于本机回环。 */
|
|
49
|
+
export function isLoopbackAddress(remoteAddress) {
|
|
50
|
+
if (typeof remoteAddress !== "string" || remoteAddress.length === 0) return false;
|
|
51
|
+
const addr = remoteAddress.trim().toLowerCase();
|
|
52
|
+
if (addr === "::1" || addr === "127.0.0.1" || addr === "::ffff:127.0.0.1") return true;
|
|
53
|
+
if (addr.startsWith("127.")) return true;
|
|
54
|
+
if (addr.startsWith("::ffff:127.")) return true;
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 恒定时间校验 `Authorization: Bearer <token>`。 */
|
|
59
|
+
export function verifyBearerToken(authHeader, expectedKey) {
|
|
60
|
+
if (typeof authHeader !== "string" || typeof expectedKey !== "string" || expectedKey.length === 0) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const match = /^Bearer\s+(.+)$/i.exec(authHeader.trim());
|
|
64
|
+
if (!match) return false;
|
|
65
|
+
const provided = Buffer.from(match[1], "utf8");
|
|
66
|
+
const expected = Buffer.from(expectedKey, "utf8");
|
|
67
|
+
if (provided.length !== expected.length) return false;
|
|
68
|
+
return timingSafeEqual(provided, expected);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 执行插件级接入鉴权:
|
|
73
|
+
* - `none`: 放行全部请求(适用于私有内网)
|
|
74
|
+
* - `loopback`: 仅放行回环来源(适用于本机调用与前置 Pangolin/Nginx/Caddy 托管鉴权)
|
|
75
|
+
* - `bearer`: 强制校验 Bearer API Key(未配置密钥时 fail-closed 返回 503)
|
|
76
|
+
*/
|
|
77
|
+
export function authorizeRequest(req, { authMode, apiKey }) {
|
|
78
|
+
if (authMode === "none") {
|
|
79
|
+
return { ok: true };
|
|
80
|
+
}
|
|
81
|
+
if (authMode === "loopback") {
|
|
82
|
+
const remote = req.socket?.remoteAddress ?? "";
|
|
83
|
+
if (!isLoopbackAddress(remote)) {
|
|
84
|
+
return {
|
|
85
|
+
ok: false,
|
|
86
|
+
statusCode: 403,
|
|
87
|
+
error: "forbidden: loopback access only (configure authMode=bearer for direct remote access)",
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return { ok: true };
|
|
91
|
+
}
|
|
92
|
+
if (authMode === "bearer") {
|
|
93
|
+
if (!apiKey) {
|
|
94
|
+
return {
|
|
95
|
+
ok: false,
|
|
96
|
+
statusCode: 503,
|
|
97
|
+
error: "service misconfigured: authMode=bearer requires apiKey or apiKeyEnv",
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (!verifyBearerToken(req.headers?.authorization, apiKey)) {
|
|
101
|
+
return {
|
|
102
|
+
ok: false,
|
|
103
|
+
statusCode: 401,
|
|
104
|
+
error: "unauthorized",
|
|
105
|
+
headers: { "WWW-Authenticate": 'Bearer realm="dsh-rest-api"' },
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { ok: true };
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
ok: false,
|
|
112
|
+
statusCode: 500,
|
|
113
|
+
error: `unsupported authMode: ${String(authMode)}`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 收集需要脱敏的敏感字面值(上游模型密钥与插件自身 Bearer Key)。 */
|
|
118
|
+
export function collectSecretsForRedaction(apiKey = "") {
|
|
119
|
+
const secrets = new Set();
|
|
120
|
+
if (typeof apiKey === "string" && apiKey.trim().length >= 6) {
|
|
121
|
+
secrets.add(apiKey.trim());
|
|
122
|
+
}
|
|
123
|
+
for (const envName of [
|
|
124
|
+
"OPENROUTER_API_KEY",
|
|
125
|
+
"DEEPSEEK_API_KEY",
|
|
126
|
+
"ANTHROPIC_API_KEY",
|
|
127
|
+
"OPENAI_API_KEY",
|
|
128
|
+
"GEMINI_API_KEY",
|
|
129
|
+
"DSH_REST_API_KEY",
|
|
130
|
+
]) {
|
|
131
|
+
const value = process.env[envName];
|
|
132
|
+
if (typeof value === "string" && value.trim().length >= 8) {
|
|
133
|
+
secrets.add(value.trim());
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return [...secrets];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function redactSecrets(text, secrets) {
|
|
140
|
+
if (typeof text !== "string" || text.length === 0) return "";
|
|
141
|
+
let out = text;
|
|
142
|
+
for (const secret of secrets) {
|
|
143
|
+
if (secret && out.includes(secret)) {
|
|
144
|
+
out = out.split(secret).join("[REDACTED]");
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function writeJson(res, statusCode, payload, extraHeaders = {}) {
|
|
151
|
+
if (res.writableEnded || res.destroyed) return;
|
|
152
|
+
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
153
|
+
res.writeHead(statusCode, {
|
|
154
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
155
|
+
"Cache-Control": "no-store",
|
|
156
|
+
"X-Content-Type-Options": "nosniff",
|
|
157
|
+
...extraHeaders,
|
|
158
|
+
});
|
|
159
|
+
res.end(body);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 写入 SSE 响应头(禁用 gzip/代理缓冲,确保实时推送不堆积)。 */
|
|
163
|
+
export function openSseStream(res) {
|
|
164
|
+
res.writeHead(200, {
|
|
165
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
166
|
+
"Cache-Control": "no-cache, no-transform",
|
|
167
|
+
Connection: "keep-alive",
|
|
168
|
+
"X-Accel-Buffering": "no",
|
|
169
|
+
"X-Content-Type-Options": "nosniff",
|
|
170
|
+
});
|
|
171
|
+
res.flushHeaders?.();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function writeSseEvent(res, eventName, data, id) {
|
|
175
|
+
if (res.writableEnded || res.destroyed) return false;
|
|
176
|
+
let frame = "";
|
|
177
|
+
if (id !== void 0) frame += `id: ${String(id)}\n`;
|
|
178
|
+
if (eventName) frame += `event: ${eventName}\n`;
|
|
179
|
+
frame += `data: ${JSON.stringify(data)}\n\n`;
|
|
180
|
+
res.write(frame);
|
|
181
|
+
res.flush?.();
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function writeSseComment(res, comment = "ping") {
|
|
186
|
+
if (res.writableEnded || res.destroyed) return false;
|
|
187
|
+
res.write(`: ${comment}\n\n`);
|
|
188
|
+
res.flush?.();
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function readJsonBody(req, maxBytes, { allowEmpty = false } = {}) {
|
|
193
|
+
return new Promise((resolveBody, rejectBody) => {
|
|
194
|
+
const declared = req.headers?.["content-length"];
|
|
195
|
+
if (declared !== void 0 && Number(declared) > maxBytes) {
|
|
196
|
+
rejectBody(Object.assign(new Error("request body too large"), { statusCode: 413 }));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const chunks = [];
|
|
200
|
+
let received = 0;
|
|
201
|
+
let settled = false;
|
|
202
|
+
const fail = (err) => {
|
|
203
|
+
if (settled) return;
|
|
204
|
+
settled = true;
|
|
205
|
+
rejectBody(err);
|
|
206
|
+
};
|
|
207
|
+
req.on("data", (chunk) => {
|
|
208
|
+
if (settled) return;
|
|
209
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
210
|
+
received += buf.byteLength;
|
|
211
|
+
if (received > maxBytes) {
|
|
212
|
+
req.destroy?.();
|
|
213
|
+
fail(Object.assign(new Error("request body too large"), { statusCode: 413 }));
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
chunks.push(buf);
|
|
217
|
+
});
|
|
218
|
+
req.on("error", (err) => fail(err));
|
|
219
|
+
req.on("aborted", () => fail(Object.assign(new Error("client aborted request"), { statusCode: 400 })));
|
|
220
|
+
req.on("end", () => {
|
|
221
|
+
if (settled) return;
|
|
222
|
+
settled = true;
|
|
223
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
224
|
+
if (raw.length === 0 && allowEmpty) {
|
|
225
|
+
resolveBody({});
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
resolveBody(JSON.parse(raw));
|
|
230
|
+
} catch {
|
|
231
|
+
rejectBody(Object.assign(new Error("invalid JSON body"), { statusCode: 400 }));
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function validateWebhookUrl(rawUrl) {
|
|
238
|
+
if (typeof rawUrl !== "string" || rawUrl.trim().length === 0) return null;
|
|
239
|
+
let parsed;
|
|
240
|
+
try {
|
|
241
|
+
parsed = new URL(rawUrl.trim());
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
return parsed.toString();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function validateWebhookHeaders(rawHeaders) {
|
|
252
|
+
if (rawHeaders === void 0) return { ok: true, value: void 0 };
|
|
253
|
+
if (rawHeaders === null || typeof rawHeaders !== "object" || Array.isArray(rawHeaders)) {
|
|
254
|
+
return { ok: false, error: "webhook_headers must be a string map" };
|
|
255
|
+
}
|
|
256
|
+
const out = {};
|
|
257
|
+
const entries = Object.entries(rawHeaders);
|
|
258
|
+
if (entries.length > 20) {
|
|
259
|
+
return { ok: false, error: "webhook_headers supports at most 20 headers" };
|
|
260
|
+
}
|
|
261
|
+
for (const [k, v] of entries) {
|
|
262
|
+
if (!/^[a-zA-Z0-9-]+$/.test(k) || k.length > 64) {
|
|
263
|
+
return { ok: false, error: `invalid webhook header name: ${k}` };
|
|
264
|
+
}
|
|
265
|
+
if (typeof v !== "string" || /[\r\n\0]/.test(v) || v.length > 2048) {
|
|
266
|
+
return { ok: false, error: `invalid webhook header value for: ${k}` };
|
|
267
|
+
}
|
|
268
|
+
out[k] = v;
|
|
269
|
+
}
|
|
270
|
+
return { ok: true, value: out };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 校验任务提交请求体(适用于 `/messages` 和 `/runs`)。
|
|
275
|
+
*/
|
|
276
|
+
export function validatePromptPayload(
|
|
277
|
+
body,
|
|
278
|
+
{ allowRequestOverrides = true, allowCustomWorkspaceDir = false } = {},
|
|
279
|
+
) {
|
|
280
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
281
|
+
return { ok: false, error: "request body must be a JSON object" };
|
|
282
|
+
}
|
|
283
|
+
for (const key of Object.keys(body)) {
|
|
284
|
+
if (!ALLOWED_PROMPT_FIELDS.has(key)) {
|
|
285
|
+
return { ok: false, error: `unknown request field: ${key}` };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (typeof body.request_id !== "string" || body.request_id.trim().length === 0 || body.request_id.length > 256) {
|
|
289
|
+
return { ok: false, error: "request_id must be a non-empty string (<= 256 chars)" };
|
|
290
|
+
}
|
|
291
|
+
if (typeof body.prompt !== "string" || body.prompt.trim().length === 0) {
|
|
292
|
+
return { ok: false, error: "prompt must be a non-empty string" };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const overrides = {};
|
|
296
|
+
const overrideFields = ["preset", "workspace_title", "workspace_dir", "provider", "model"];
|
|
297
|
+
for (const field of overrideFields) {
|
|
298
|
+
if (body[field] === void 0) continue;
|
|
299
|
+
if (!allowRequestOverrides) {
|
|
300
|
+
return { ok: false, error: `per-request override "${field}" is disabled by server configuration` };
|
|
301
|
+
}
|
|
302
|
+
if (field === "workspace_dir" && !allowCustomWorkspaceDir) {
|
|
303
|
+
return {
|
|
304
|
+
ok: false,
|
|
305
|
+
error: 'per-request "workspace_dir" override is disabled (set allowCustomWorkspaceDir: true to enable)',
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
if (typeof body[field] !== "string" || body[field].trim().length === 0 || body[field].length > 256) {
|
|
309
|
+
return { ok: false, error: `${field} must be a non-empty string (<= 256 chars)` };
|
|
310
|
+
}
|
|
311
|
+
overrides[field] = body[field].trim();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
let webhookUrl;
|
|
315
|
+
if (body.webhook_url !== void 0) {
|
|
316
|
+
webhookUrl = validateWebhookUrl(body.webhook_url);
|
|
317
|
+
if (webhookUrl === null) {
|
|
318
|
+
return { ok: false, error: "webhook_url must be a valid http:// or https:// URL" };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const headersResult = validateWebhookHeaders(body.webhook_headers);
|
|
322
|
+
if (!headersResult.ok) return headersResult;
|
|
323
|
+
|
|
324
|
+
return {
|
|
325
|
+
ok: true,
|
|
326
|
+
requestId: body.request_id,
|
|
327
|
+
prompt: body.prompt,
|
|
328
|
+
overrides,
|
|
329
|
+
webhookUrl,
|
|
330
|
+
webhookHeaders: headersResult.value,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function parseWaitSeconds(rawValue, defaultValue, maxValue) {
|
|
335
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "") return defaultValue;
|
|
336
|
+
const num = Number(rawValue);
|
|
337
|
+
if (!Number.isFinite(num) || num < 0) return defaultValue;
|
|
338
|
+
return Math.min(num, maxValue);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** 按 UTF-8 字节上限安全裁剪文本,确保单个 JSON 响应严格不超过 maxBytes。 */
|
|
342
|
+
export function enforceTextBudget(payloadBuilder, text, maxBytes) {
|
|
343
|
+
const check = (candidate) => Buffer.byteLength(JSON.stringify(payloadBuilder(candidate)), "utf8");
|
|
344
|
+
if (check(text) <= maxBytes) return text;
|
|
345
|
+
const suffix = "\n\n[Truncated to fit response size limit; inspect workspace artifacts for full output.]";
|
|
346
|
+
let low = 0;
|
|
347
|
+
let high = text.length;
|
|
348
|
+
while (low < high) {
|
|
349
|
+
const mid = Math.ceil((low + high) / 2);
|
|
350
|
+
if (check(text.slice(0, mid) + suffix) <= maxBytes) {
|
|
351
|
+
low = mid;
|
|
352
|
+
} else {
|
|
353
|
+
high = mid - 1;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return text.slice(0, low) + suffix;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function waitWithTimeoutAndAbort(promise, timeoutMs, abortSignal) {
|
|
360
|
+
if (timeoutMs <= 0) return Promise.resolve();
|
|
361
|
+
return new Promise((resolveWait) => {
|
|
362
|
+
let done = false;
|
|
363
|
+
const finish = () => {
|
|
364
|
+
if (done) return;
|
|
365
|
+
done = true;
|
|
366
|
+
clearTimeout(timer);
|
|
367
|
+
if (abortSignal) abortSignal.removeEventListener("abort", finish);
|
|
368
|
+
resolveWait();
|
|
369
|
+
};
|
|
370
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
371
|
+
timer.unref?.();
|
|
372
|
+
if (abortSignal) {
|
|
373
|
+
if (abortSignal.aborted) {
|
|
374
|
+
finish();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
abortSignal.addEventListener("abort", finish, { once: true });
|
|
378
|
+
}
|
|
379
|
+
promise.then(finish, finish);
|
|
380
|
+
});
|
|
381
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rest-api — DeepSeek Harness Web 通用 REST API 插件入口。
|
|
3
|
+
*
|
|
4
|
+
* 将标准 HTTP REST API 直接挂载在 dsh web 同进程端口下,所有任务会话实时可见于 Web UI。
|
|
5
|
+
* 所有配置项均通过 Schemastery 声明,可直接在 dsh Web 插件设置页可视化编辑并热生效。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import z from "@deepseek-ai/schemastery";
|
|
9
|
+
import { writeJson } from "./http.js";
|
|
10
|
+
import { RestApiRuntime } from "./runtime.js";
|
|
11
|
+
|
|
12
|
+
export const name = "rest-api";
|
|
13
|
+
|
|
14
|
+
export const inject = [
|
|
15
|
+
"webServer",
|
|
16
|
+
"agents",
|
|
17
|
+
"sessions",
|
|
18
|
+
"agentPresets",
|
|
19
|
+
"workspaceRegistry",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
export const Config = z.object({
|
|
23
|
+
routePrefix: z
|
|
24
|
+
.string()
|
|
25
|
+
.default("/v1")
|
|
26
|
+
.description("HTTP route prefix mounted on the dsh web server (e.g. /v1)."),
|
|
27
|
+
presetId: z
|
|
28
|
+
.string()
|
|
29
|
+
.default("headless-task")
|
|
30
|
+
.description("Default Agent Preset ID for API-created sessions. Leave empty to use the host default preset.")
|
|
31
|
+
.volatile(),
|
|
32
|
+
provider: z
|
|
33
|
+
.string()
|
|
34
|
+
.default("")
|
|
35
|
+
.description("Optional default LLM provider override for API sessions. Leave empty to inherit dsh default model.")
|
|
36
|
+
.volatile(),
|
|
37
|
+
model: z
|
|
38
|
+
.string()
|
|
39
|
+
.default("")
|
|
40
|
+
.description("Optional default LLM model override for API sessions. Leave empty to inherit dsh default model.")
|
|
41
|
+
.volatile(),
|
|
42
|
+
workspaceTitle: z
|
|
43
|
+
.string()
|
|
44
|
+
.default("API Tasks")
|
|
45
|
+
.description("Sidebar workspace group title where API sessions appear.")
|
|
46
|
+
.volatile(),
|
|
47
|
+
workspaceDir: z
|
|
48
|
+
.string()
|
|
49
|
+
.default("")
|
|
50
|
+
.description("Workspace directory for API sessions (supports ~). Leave empty for ~/.dsh/rest-api-workspace.")
|
|
51
|
+
.volatile(),
|
|
52
|
+
authMode: z
|
|
53
|
+
.union(["loopback", "bearer", "none"])
|
|
54
|
+
.default("loopback")
|
|
55
|
+
.description(
|
|
56
|
+
"Access control mode: loopback (local & reverse-proxy only, default), bearer (Authorization: Bearer token), or none (private network).",
|
|
57
|
+
)
|
|
58
|
+
.volatile(),
|
|
59
|
+
apiKey: z
|
|
60
|
+
.string()
|
|
61
|
+
.role("secret")
|
|
62
|
+
.description("Bearer token literal used when authMode=bearer (takes precedence over apiKeyEnv).")
|
|
63
|
+
.volatile(),
|
|
64
|
+
apiKeyEnv: z
|
|
65
|
+
.string()
|
|
66
|
+
.default("DSH_REST_API_KEY")
|
|
67
|
+
.description("Environment variable name holding the Bearer token when authMode=bearer.")
|
|
68
|
+
.volatile(),
|
|
69
|
+
sandboxMode: z
|
|
70
|
+
.union(["read-only", "workspace-write", "danger-full-access"])
|
|
71
|
+
.default("workspace-write")
|
|
72
|
+
.description("Default filesystem sandbox mode applied to newly created API sessions.")
|
|
73
|
+
.volatile(),
|
|
74
|
+
approvalPolicy: z
|
|
75
|
+
.union(["ask", "never"])
|
|
76
|
+
.default("never")
|
|
77
|
+
.description("Default tool approval policy for API sessions (use never for unattended execution).")
|
|
78
|
+
.volatile(),
|
|
79
|
+
allowRequestOverrides: z
|
|
80
|
+
.boolean()
|
|
81
|
+
.default(true)
|
|
82
|
+
.description("Allow callers to override preset, workspace_title, provider, or model per request.")
|
|
83
|
+
.volatile(),
|
|
84
|
+
allowCustomWorkspaceDir: z
|
|
85
|
+
.boolean()
|
|
86
|
+
.default(false)
|
|
87
|
+
.description("Allow callers to specify an arbitrary workspace_dir per request (disabled by default for safety).")
|
|
88
|
+
.volatile(),
|
|
89
|
+
defaultWebhookUrl: z
|
|
90
|
+
.string()
|
|
91
|
+
.default("")
|
|
92
|
+
.description("Optional global webhook URL receiving POST callbacks when runs reach terminal states.")
|
|
93
|
+
.volatile(),
|
|
94
|
+
webhookTimeoutMs: z
|
|
95
|
+
.number()
|
|
96
|
+
.default(10_000)
|
|
97
|
+
.description("Timeout in milliseconds for each webhook HTTP delivery attempt.")
|
|
98
|
+
.volatile(),
|
|
99
|
+
requestTimeoutMs: z
|
|
100
|
+
.number()
|
|
101
|
+
.default(960_000)
|
|
102
|
+
.description("Node HTTP server requestTimeout override (ms) to support long synchronous tasks.")
|
|
103
|
+
.volatile(),
|
|
104
|
+
runRetentionMs: z
|
|
105
|
+
.number()
|
|
106
|
+
.default(86_400_000)
|
|
107
|
+
.description("How long completed/cancelled/failed run records stay queryable in memory (ms).")
|
|
108
|
+
.volatile(),
|
|
109
|
+
maxRequestBytes: z
|
|
110
|
+
.number()
|
|
111
|
+
.default(1 * 1024 * 1024)
|
|
112
|
+
.description("Maximum accepted HTTP request body size in bytes.")
|
|
113
|
+
.volatile(),
|
|
114
|
+
maxResponseBytes: z
|
|
115
|
+
.number()
|
|
116
|
+
.default(2 * 1024 * 1024)
|
|
117
|
+
.description("Maximum JSON response size in bytes; longer text is safely truncated.")
|
|
118
|
+
.volatile(),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
export function apply(ctx, config) {
|
|
122
|
+
const runtime = new RestApiRuntime(ctx, config);
|
|
123
|
+
const initialConfig = runtime.config;
|
|
124
|
+
|
|
125
|
+
// 0. 声明本插件自带 Web 配置页(避免未来客户端重复自动生成表单)
|
|
126
|
+
ctx.inject?.(["settings"], (sctx) => {
|
|
127
|
+
sctx.effect(() => sctx.settings.configure({ auto: false }, ctx.fiber));
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// 1. 提升底层 WebServer 的 requestTimeout,支持同步长任务与 SSE 长连接
|
|
131
|
+
ctx.effect(() => {
|
|
132
|
+
const server = ctx.webServer?.server;
|
|
133
|
+
if (!server) return;
|
|
134
|
+
const previous = server.requestTimeout;
|
|
135
|
+
server.requestTimeout = initialConfig.requestTimeoutMs;
|
|
136
|
+
ctx.logger.info(
|
|
137
|
+
"[dsh-rest-api] updated webServer.server.requestTimeout: %dms -> %dms",
|
|
138
|
+
previous,
|
|
139
|
+
server.requestTimeout,
|
|
140
|
+
);
|
|
141
|
+
return () => {
|
|
142
|
+
server.requestTimeout = previous;
|
|
143
|
+
};
|
|
144
|
+
}, "dsh-rest-api.webserver-timeout");
|
|
145
|
+
|
|
146
|
+
// 2. 启动时初始化默认侧边栏 Workspace 分组,确保 API 会话整洁归类而非进入「未分组」
|
|
147
|
+
ctx.effect(() => {
|
|
148
|
+
void runtime.ensureWorkspace().catch((error) => {
|
|
149
|
+
ctx.logger.warn(
|
|
150
|
+
"[dsh-rest-api] failed to initialize default workspace group: %s",
|
|
151
|
+
error instanceof Error ? error.message : String(error),
|
|
152
|
+
);
|
|
153
|
+
});
|
|
154
|
+
}, "dsh-rest-api.workspace-group");
|
|
155
|
+
|
|
156
|
+
// 3. 挂载独立 REST 前缀路由(绕过浏览器端 BrowserAuth,按 authMode 执行接入控制)
|
|
157
|
+
ctx.effect(() => {
|
|
158
|
+
const disposeRoute = ctx.webServer.register({
|
|
159
|
+
kind: "prefix",
|
|
160
|
+
path: runtime.prefix,
|
|
161
|
+
handler: async (req, res) => {
|
|
162
|
+
try {
|
|
163
|
+
await runtime.handleHttp(req, res);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
ctx.logger.error("[dsh-rest-api] unhandled route error: %s", String(error));
|
|
166
|
+
writeJson(res, 500, { error: "internal server error" });
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
ctx.logger.info(
|
|
171
|
+
"[dsh-rest-api] mounted on %s (auth=%s, preset=%s, group=%s)",
|
|
172
|
+
runtime.prefix,
|
|
173
|
+
initialConfig.authMode,
|
|
174
|
+
initialConfig.presetId || "default",
|
|
175
|
+
initialConfig.workspaceTitle,
|
|
176
|
+
);
|
|
177
|
+
return () => {
|
|
178
|
+
disposeRoute();
|
|
179
|
+
runtime.dispose();
|
|
180
|
+
};
|
|
181
|
+
}, "dsh-rest-api.http-route");
|
|
182
|
+
}
|