@solomonneas/adguard-mcp 0.3.1 → 0.3.2
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/README.md +116 -1
- package/dist/cli.js +1214 -260
- package/dist/index.js +786 -129
- package/dist/mcp-bin.js +2018 -584
- package/dist/mcp-server.js +1994 -571
- package/openclaw.plugin.json +1 -1
- package/package.json +7 -9
package/dist/index.js
CHANGED
|
@@ -2,9 +2,437 @@
|
|
|
2
2
|
|
|
3
3
|
// index.ts
|
|
4
4
|
import { Buffer as Buffer2 } from "buffer";
|
|
5
|
+
|
|
6
|
+
// node_modules/@lidless-labs/effect-operator-kit/dist/index.js
|
|
7
|
+
import { Data } from "effect";
|
|
8
|
+
import { Effect } from "effect";
|
|
9
|
+
import { Effect as Effect2 } from "effect";
|
|
10
|
+
import { Duration, Effect as Effect3, Schedule } from "effect";
|
|
11
|
+
import { Cause, Effect as Effect4, Exit } from "effect";
|
|
12
|
+
import { Cause as Cause2, Effect as Effect5 } from "effect";
|
|
13
|
+
var ConfigError = class extends Data.TaggedError("ConfigError") {
|
|
14
|
+
};
|
|
15
|
+
var AuthError = class extends Data.TaggedError("AuthError") {
|
|
16
|
+
};
|
|
17
|
+
var ForbiddenError = class extends Data.TaggedError("ForbiddenError") {
|
|
18
|
+
};
|
|
19
|
+
var NotFoundError = class extends Data.TaggedError("NotFoundError") {
|
|
20
|
+
};
|
|
21
|
+
var TimeoutError = class extends Data.TaggedError("TimeoutError") {
|
|
22
|
+
};
|
|
23
|
+
var TransportError = class extends Data.TaggedError("TransportError") {
|
|
24
|
+
};
|
|
25
|
+
var ParseError = class extends Data.TaggedError("ParseError") {
|
|
26
|
+
};
|
|
27
|
+
var UnexpectedStatusError = class extends Data.TaggedError("UnexpectedStatusError") {
|
|
28
|
+
};
|
|
29
|
+
var fromProcessEnv = (env) => ({
|
|
30
|
+
get: (key) => (env ?? process.env)[key]
|
|
31
|
+
});
|
|
32
|
+
var isBlank = (raw) => raw === void 0 || raw.trim() === "";
|
|
33
|
+
var failConfig = (partial) => Effect.fail(new ConfigError(partial));
|
|
34
|
+
var readRaw = (env, key) => env.get(key);
|
|
35
|
+
var parseTimeoutEnv = (env, key, opts) => {
|
|
36
|
+
const raw = readRaw(env, key);
|
|
37
|
+
if (isBlank(raw)) {
|
|
38
|
+
return Effect.succeed(opts.fallbackMs);
|
|
39
|
+
}
|
|
40
|
+
const parsed = Number(raw.trim());
|
|
41
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
42
|
+
return failConfig({
|
|
43
|
+
key,
|
|
44
|
+
value: raw,
|
|
45
|
+
message: `${key} must be a positive timeout`
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const unit = opts.unit ?? "s";
|
|
49
|
+
const ms = unit === "ms" ? parsed : parsed * 1e3;
|
|
50
|
+
if (opts.minMs !== void 0 && ms < opts.minMs) {
|
|
51
|
+
return failConfig({
|
|
52
|
+
key,
|
|
53
|
+
value: raw,
|
|
54
|
+
message: `${key} must be at least ${opts.minMs}ms`
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (opts.maxMs !== void 0 && ms > opts.maxMs) {
|
|
58
|
+
return failConfig({
|
|
59
|
+
key,
|
|
60
|
+
value: raw,
|
|
61
|
+
message: `${key} must be at most ${opts.maxMs}ms`
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return Effect.succeed(ms);
|
|
65
|
+
};
|
|
66
|
+
var SECRET_PATTERNS = [
|
|
67
|
+
/(authorization:\s*)(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
68
|
+
/\b(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
69
|
+
/(authorization:\s*)(?:token|digest|hawk|oauth|apikey)\s+\S+/gi,
|
|
70
|
+
/(x-n8n-api-key|x-auth-token|x-emby-token|x-api-key)\s*:\s*\S+/gi,
|
|
71
|
+
/(https?:\/\/)([^@\s/]+)@/gi,
|
|
72
|
+
/([?&](?:access_token|refresh_token|client_secret|id_token|x-api-key|\w+_(?:token|secret)|password|token|secret|api[_-]?key|key)=)[^&\s]+/gi,
|
|
73
|
+
/\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g
|
|
74
|
+
];
|
|
75
|
+
var MAX_LENGTH = 500;
|
|
76
|
+
var redactString = (message, secrets = []) => {
|
|
77
|
+
let sanitized = message;
|
|
78
|
+
for (const secret of secrets) {
|
|
79
|
+
if (secret) {
|
|
80
|
+
sanitized = sanitized.split(secret).join("[REDACTED]");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
sanitized = sanitized.replace(SECRET_PATTERNS[0], "$1$2 [REDACTED]").replace(SECRET_PATTERNS[1], "$1 [REDACTED]").replace(SECRET_PATTERNS[2], "$1[REDACTED]").replace(SECRET_PATTERNS[3], "$1: [REDACTED]").replace(SECRET_PATTERNS[4], "$1[REDACTED]@").replace(SECRET_PATTERNS[5], "$1[REDACTED]").replace(SECRET_PATTERNS[6], "[REDACTED]");
|
|
84
|
+
return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}...` : sanitized;
|
|
85
|
+
};
|
|
86
|
+
var defaultRedact = (value) => redactString(value);
|
|
87
|
+
var DEFAULT_SUCCESS_STATUSES = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
88
|
+
function redactBody(text, redact2) {
|
|
89
|
+
return (redact2 ?? defaultRedact)(text);
|
|
90
|
+
}
|
|
91
|
+
function mergeHeaders(...sources) {
|
|
92
|
+
const merged = new Headers();
|
|
93
|
+
for (const source of sources) {
|
|
94
|
+
if (!source) continue;
|
|
95
|
+
const headers = new Headers(source);
|
|
96
|
+
headers.forEach((value, key) => merged.set(key, value));
|
|
97
|
+
}
|
|
98
|
+
return merged;
|
|
99
|
+
}
|
|
100
|
+
function resolveExpectedStatuses(req) {
|
|
101
|
+
return req.expectedStatuses ?? DEFAULT_SUCCESS_STATUSES;
|
|
102
|
+
}
|
|
103
|
+
function isExpectedStatus(status, expected) {
|
|
104
|
+
return expected.includes(status);
|
|
105
|
+
}
|
|
106
|
+
function resolveBodyEncoding(req) {
|
|
107
|
+
if (req.bodyEncoding !== void 0) return req.bodyEncoding;
|
|
108
|
+
return req.body !== void 0 ? "json" : "none";
|
|
109
|
+
}
|
|
110
|
+
function setContentTypeIfAbsent(headers, contentType) {
|
|
111
|
+
if (!headers.has("content-type")) {
|
|
112
|
+
headers.set("content-type", contentType);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function buildRequestBody(req, headers) {
|
|
116
|
+
const encoding = resolveBodyEncoding(req);
|
|
117
|
+
switch (encoding) {
|
|
118
|
+
case "none":
|
|
119
|
+
return void 0;
|
|
120
|
+
case "json":
|
|
121
|
+
setContentTypeIfAbsent(headers, "application/json");
|
|
122
|
+
return JSON.stringify(req.body);
|
|
123
|
+
case "text":
|
|
124
|
+
setContentTypeIfAbsent(headers, "text/plain");
|
|
125
|
+
return String(req.body);
|
|
126
|
+
case "form": {
|
|
127
|
+
setContentTypeIfAbsent(
|
|
128
|
+
headers,
|
|
129
|
+
"application/x-www-form-urlencoded"
|
|
130
|
+
);
|
|
131
|
+
const params = new URLSearchParams();
|
|
132
|
+
if (req.body && typeof req.body === "object") {
|
|
133
|
+
for (const [key, value] of Object.entries(
|
|
134
|
+
req.body
|
|
135
|
+
)) {
|
|
136
|
+
params.set(key, String(value));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return params.toString();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function mapUnexpectedStatus(req, status, bodyText, expectedStatuses, redact2) {
|
|
144
|
+
const redacted = redactBody(bodyText, redact2);
|
|
145
|
+
const mapperInput = {
|
|
146
|
+
status,
|
|
147
|
+
method: req.method,
|
|
148
|
+
path: req.path,
|
|
149
|
+
bodyText: redacted,
|
|
150
|
+
expectedStatuses
|
|
151
|
+
};
|
|
152
|
+
if (req.statusMapper) {
|
|
153
|
+
const custom = req.statusMapper(mapperInput);
|
|
154
|
+
if (custom !== null) return custom;
|
|
155
|
+
}
|
|
156
|
+
const base = {
|
|
157
|
+
method: req.method,
|
|
158
|
+
path: req.path,
|
|
159
|
+
status,
|
|
160
|
+
body: redacted
|
|
161
|
+
};
|
|
162
|
+
switch (status) {
|
|
163
|
+
case 401:
|
|
164
|
+
return new AuthError(base);
|
|
165
|
+
case 403:
|
|
166
|
+
return new ForbiddenError(base);
|
|
167
|
+
case 404:
|
|
168
|
+
return new NotFoundError(base);
|
|
169
|
+
default:
|
|
170
|
+
return new UnexpectedStatusError({
|
|
171
|
+
method: req.method,
|
|
172
|
+
path: req.path,
|
|
173
|
+
status,
|
|
174
|
+
body: redacted,
|
|
175
|
+
expected: expectedStatuses
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function parseResponseBody(req, bodyText, redact2) {
|
|
180
|
+
const responseType = req.responseType ?? "json";
|
|
181
|
+
if (responseType === "none") {
|
|
182
|
+
return Effect2.succeed(void 0);
|
|
183
|
+
}
|
|
184
|
+
if (responseType === "text") {
|
|
185
|
+
return Effect2.succeed(bodyText);
|
|
186
|
+
}
|
|
187
|
+
if (bodyText.length === 0) {
|
|
188
|
+
return Effect2.succeed(void 0);
|
|
189
|
+
}
|
|
190
|
+
return Effect2.try({
|
|
191
|
+
try: () => JSON.parse(bodyText),
|
|
192
|
+
catch: (cause) => new ParseError({
|
|
193
|
+
path: req.path,
|
|
194
|
+
body: redactBody(bodyText, redact2),
|
|
195
|
+
message: "Failed to parse JSON response",
|
|
196
|
+
cause
|
|
197
|
+
})
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
function fetchWithTimeout(ctx, url, init, timeoutMs, method, path) {
|
|
201
|
+
const fetchImpl = ctx.fetch ?? globalThis.fetch;
|
|
202
|
+
return Effect2.async((resume) => {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
205
|
+
const finish = (effect) => {
|
|
206
|
+
clearTimeout(timeoutId);
|
|
207
|
+
resume(effect);
|
|
208
|
+
};
|
|
209
|
+
void fetchImpl(url, { ...init, signal: controller.signal }).then((response) => finish(Effect2.succeed(response))).catch((cause) => {
|
|
210
|
+
if (cause instanceof Error && cause.name === "AbortError") {
|
|
211
|
+
finish(
|
|
212
|
+
Effect2.fail(new TimeoutError({ method, path, timeoutMs }))
|
|
213
|
+
);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
finish(
|
|
217
|
+
Effect2.fail(new TransportError({ method, path, cause }))
|
|
218
|
+
);
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
var buildUrl = (baseUrl, path, query) => {
|
|
223
|
+
if (path.includes("\\")) {
|
|
224
|
+
throw new TypeError("buildUrl: path must not contain backslash");
|
|
225
|
+
}
|
|
226
|
+
const url = new URL(path, baseUrl);
|
|
227
|
+
if (url.username || url.password) {
|
|
228
|
+
throw new TypeError("buildUrl: path must not contain URL userinfo");
|
|
229
|
+
}
|
|
230
|
+
if (url.origin !== baseUrl.origin) {
|
|
231
|
+
throw new TypeError(
|
|
232
|
+
`buildUrl: path "${path}" resolves to a different origin (${url.origin}) than baseUrl (${baseUrl.origin})`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
if (query) {
|
|
236
|
+
for (const [key, value] of Object.entries(query)) {
|
|
237
|
+
if (value === null || value === void 0) continue;
|
|
238
|
+
if (Array.isArray(value)) {
|
|
239
|
+
for (const item of value) {
|
|
240
|
+
if (item === null || item === void 0) continue;
|
|
241
|
+
url.searchParams.append(key, String(item));
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
url.searchParams.set(key, String(value));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return url;
|
|
249
|
+
};
|
|
250
|
+
function buildHeaders(ctx, req) {
|
|
251
|
+
const auth = ctx.auth;
|
|
252
|
+
if (!auth) {
|
|
253
|
+
return Effect2.succeed(mergeHeaders(ctx.defaultHeaders, req.headers));
|
|
254
|
+
}
|
|
255
|
+
return Effect2.gen(function* () {
|
|
256
|
+
let headers = mergeHeaders(ctx.defaultHeaders);
|
|
257
|
+
headers = yield* auth.apply(headers);
|
|
258
|
+
return mergeHeaders(headers, req.headers);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
var sendRequest = (ctx, req) => {
|
|
262
|
+
const url = buildUrl(ctx.baseUrl, req.path, req.query);
|
|
263
|
+
const timeoutMs = req.timeoutMs ?? ctx.timeoutMs;
|
|
264
|
+
const expectedStatuses = resolveExpectedStatuses(req);
|
|
265
|
+
return buildHeaders(ctx, req).pipe(
|
|
266
|
+
Effect2.flatMap((headers) => {
|
|
267
|
+
const body = buildRequestBody(req, headers);
|
|
268
|
+
const init = {
|
|
269
|
+
method: req.method,
|
|
270
|
+
headers,
|
|
271
|
+
...body !== void 0 ? { body } : {}
|
|
272
|
+
};
|
|
273
|
+
return fetchWithTimeout(
|
|
274
|
+
ctx,
|
|
275
|
+
url,
|
|
276
|
+
init,
|
|
277
|
+
timeoutMs,
|
|
278
|
+
req.method,
|
|
279
|
+
req.path
|
|
280
|
+
).pipe(
|
|
281
|
+
Effect2.flatMap(
|
|
282
|
+
(response) => Effect2.tryPromise({
|
|
283
|
+
try: () => response.text(),
|
|
284
|
+
catch: (cause) => new TransportError({
|
|
285
|
+
method: req.method,
|
|
286
|
+
path: req.path,
|
|
287
|
+
cause
|
|
288
|
+
})
|
|
289
|
+
}).pipe(
|
|
290
|
+
Effect2.flatMap((bodyText) => {
|
|
291
|
+
if (!isExpectedStatus(response.status, expectedStatuses)) {
|
|
292
|
+
return Effect2.fail(
|
|
293
|
+
mapUnexpectedStatus(
|
|
294
|
+
req,
|
|
295
|
+
response.status,
|
|
296
|
+
bodyText,
|
|
297
|
+
expectedStatuses,
|
|
298
|
+
ctx.redact
|
|
299
|
+
)
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
return parseResponseBody(req, bodyText, ctx.redact).pipe(
|
|
303
|
+
Effect2.map((parsedBody) => ({
|
|
304
|
+
status: response.status,
|
|
305
|
+
headers: response.headers,
|
|
306
|
+
bodyText,
|
|
307
|
+
body: parsedBody
|
|
308
|
+
}))
|
|
309
|
+
);
|
|
310
|
+
})
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
);
|
|
314
|
+
})
|
|
315
|
+
);
|
|
316
|
+
};
|
|
317
|
+
var defaultShouldRetry = (error) => {
|
|
318
|
+
switch (error._tag) {
|
|
319
|
+
case "TransportError":
|
|
320
|
+
case "TimeoutError":
|
|
321
|
+
return true;
|
|
322
|
+
case "UnexpectedStatusError":
|
|
323
|
+
return error.status >= 500;
|
|
324
|
+
default:
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
var DEFAULT_POLICY_FIELDS = {
|
|
329
|
+
maxAttempts: 3,
|
|
330
|
+
initialDelayMs: 100,
|
|
331
|
+
maxDelayMs: 5e3,
|
|
332
|
+
factor: 2,
|
|
333
|
+
jitter: true,
|
|
334
|
+
shouldRetry: defaultShouldRetry
|
|
335
|
+
};
|
|
336
|
+
var noRetry = {
|
|
337
|
+
enabled: false,
|
|
338
|
+
...DEFAULT_POLICY_FIELDS,
|
|
339
|
+
shouldRetry: () => false
|
|
340
|
+
};
|
|
341
|
+
var exponentialRetry = (opts) => ({
|
|
342
|
+
enabled: opts.enabled ?? true,
|
|
343
|
+
maxAttempts: opts.maxAttempts ?? DEFAULT_POLICY_FIELDS.maxAttempts,
|
|
344
|
+
initialDelayMs: opts.initialDelayMs ?? DEFAULT_POLICY_FIELDS.initialDelayMs,
|
|
345
|
+
maxDelayMs: opts.maxDelayMs ?? DEFAULT_POLICY_FIELDS.maxDelayMs,
|
|
346
|
+
factor: opts.factor ?? DEFAULT_POLICY_FIELDS.factor,
|
|
347
|
+
jitter: opts.jitter ?? DEFAULT_POLICY_FIELDS.jitter,
|
|
348
|
+
shouldRetry: opts.shouldRetry ?? DEFAULT_POLICY_FIELDS.shouldRetry
|
|
349
|
+
});
|
|
350
|
+
var buildSchedule = (policy) => {
|
|
351
|
+
const base = Schedule.exponential(`${policy.initialDelayMs} millis`, policy.factor);
|
|
352
|
+
const withJitter = policy.jitter ? base.pipe(Schedule.jittered) : base;
|
|
353
|
+
const capped = withJitter.pipe(
|
|
354
|
+
Schedule.modifyDelay((_out, duration) => {
|
|
355
|
+
const ms = Duration.toMillis(duration);
|
|
356
|
+
return ms > policy.maxDelayMs ? `${policy.maxDelayMs} millis` : duration;
|
|
357
|
+
})
|
|
358
|
+
);
|
|
359
|
+
return capped.pipe(Schedule.whileInput((error) => policy.shouldRetry(error)));
|
|
360
|
+
};
|
|
361
|
+
var withRetry = (effect, policy = noRetry) => {
|
|
362
|
+
if (!policy.enabled || policy.maxAttempts <= 1) {
|
|
363
|
+
return effect;
|
|
364
|
+
}
|
|
365
|
+
const retries = Math.max(0, policy.maxAttempts - 1);
|
|
366
|
+
return Effect3.retry(effect, {
|
|
367
|
+
times: retries,
|
|
368
|
+
while: (error) => policy.shouldRetry(error),
|
|
369
|
+
schedule: buildSchedule(policy)
|
|
370
|
+
});
|
|
371
|
+
};
|
|
372
|
+
var ok = (details) => ({
|
|
373
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
374
|
+
details
|
|
375
|
+
});
|
|
376
|
+
var fail = (message, details) => {
|
|
377
|
+
const result = {
|
|
378
|
+
content: [
|
|
379
|
+
{
|
|
380
|
+
type: "text",
|
|
381
|
+
text: JSON.stringify({ error: message }, null, 2)
|
|
382
|
+
}
|
|
383
|
+
],
|
|
384
|
+
isError: true
|
|
385
|
+
};
|
|
386
|
+
if (details !== void 0) {
|
|
387
|
+
result.details = details;
|
|
388
|
+
}
|
|
389
|
+
return result;
|
|
390
|
+
};
|
|
391
|
+
var refuseUnconfirmed = (operation) => fail(
|
|
392
|
+
`Refusing to ${operation} without explicit confirmation. Re-call this tool with confirm: true to proceed.`
|
|
393
|
+
);
|
|
394
|
+
var operatorErrorMessage = (error) => {
|
|
395
|
+
if (isTaggedShape(error)) {
|
|
396
|
+
if (typeof error.message === "string" && error.message.length > 0 && error.message !== error._tag) {
|
|
397
|
+
return error.message;
|
|
398
|
+
}
|
|
399
|
+
return formatTaggedThin(error);
|
|
400
|
+
}
|
|
401
|
+
if (error instanceof Error && error.message.length > 0) {
|
|
402
|
+
return error.message;
|
|
403
|
+
}
|
|
404
|
+
return String(error);
|
|
405
|
+
};
|
|
406
|
+
function isTaggedShape(error) {
|
|
407
|
+
return error !== null && typeof error === "object" && "_tag" in error && typeof error._tag === "string";
|
|
408
|
+
}
|
|
409
|
+
function formatTaggedThin(error) {
|
|
410
|
+
switch (error._tag) {
|
|
411
|
+
case "ConfigError":
|
|
412
|
+
return error.key ? `ConfigError: ${error.key}${error.message ? `: ${error.message}` : ""}` : error.message || "ConfigError";
|
|
413
|
+
case "TimeoutError":
|
|
414
|
+
return `TimeoutError: ${error.method ?? "?"} ${error.path ?? "?"} after ${error.timeoutMs ?? "?"}ms`;
|
|
415
|
+
case "AuthError":
|
|
416
|
+
case "ForbiddenError":
|
|
417
|
+
case "NotFoundError":
|
|
418
|
+
case "UnexpectedStatusError":
|
|
419
|
+
return `${error._tag}: ${error.method ?? "?"} ${error.path ?? "?"}${error.status !== void 0 ? ` (${error.status})` : ""}`;
|
|
420
|
+
case "TransportError":
|
|
421
|
+
return `TransportError: ${error.method ?? "?"} ${error.path ?? "?"}`;
|
|
422
|
+
case "ParseError":
|
|
423
|
+
return error.message || `ParseError${error.path ? `: ${error.path}` : ""}`;
|
|
424
|
+
default:
|
|
425
|
+
return error.message || error._tag;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// index.ts
|
|
5
430
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
6
431
|
|
|
7
432
|
// src/config.ts
|
|
433
|
+
import { Effect as Effect6 } from "effect";
|
|
434
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
435
|
+
var MIN_REQUEST_TIMEOUT_MS = 1e3;
|
|
8
436
|
var NoInstancesError = class extends Error {
|
|
9
437
|
constructor() {
|
|
10
438
|
super("No AdGuard instances configured. Set ADGUARD_<NAME>_URL/USERNAME/PASSWORD for at least one instance.");
|
|
@@ -47,7 +475,32 @@ var PartialSyncConfigError = class extends Error {
|
|
|
47
475
|
this.name = "PartialSyncConfigError";
|
|
48
476
|
}
|
|
49
477
|
};
|
|
478
|
+
function presentEnvValue(env, key) {
|
|
479
|
+
const raw = env.get(key);
|
|
480
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
481
|
+
return raw;
|
|
482
|
+
}
|
|
483
|
+
function firstPresentAlias(env, keys) {
|
|
484
|
+
for (const key of keys) {
|
|
485
|
+
const value = presentEnvValue(env, key);
|
|
486
|
+
if (value !== void 0) return value;
|
|
487
|
+
}
|
|
488
|
+
return void 0;
|
|
489
|
+
}
|
|
490
|
+
function readDefaultInstance(env) {
|
|
491
|
+
const raw = env.get("ADGUARD_DEFAULT_INSTANCE");
|
|
492
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
493
|
+
return raw.toLowerCase();
|
|
494
|
+
}
|
|
495
|
+
function readRequiredInstanceField(env, key) {
|
|
496
|
+
const raw = env.get(key);
|
|
497
|
+
if (raw === void 0 || raw === "") {
|
|
498
|
+
throw new Error(`${key} is required`);
|
|
499
|
+
}
|
|
500
|
+
return raw;
|
|
501
|
+
}
|
|
50
502
|
function resolveInstances(env) {
|
|
503
|
+
const reader = fromProcessEnv(env);
|
|
51
504
|
const instances = {};
|
|
52
505
|
const candidateNames = /* @__PURE__ */ new Set();
|
|
53
506
|
const SUFFIX_RE = /^ADGUARD_([A-Z0-9_]+)_(URL|USERNAME|PASSWORD)$/;
|
|
@@ -60,9 +513,9 @@ function resolveInstances(env) {
|
|
|
60
513
|
}
|
|
61
514
|
for (const upperName of candidateNames) {
|
|
62
515
|
const name = upperName.toLowerCase();
|
|
63
|
-
const url =
|
|
64
|
-
const username =
|
|
65
|
-
const password =
|
|
516
|
+
const url = presentEnvValue(reader, `ADGUARD_${upperName}_URL`);
|
|
517
|
+
const username = presentEnvValue(reader, `ADGUARD_${upperName}_USERNAME`);
|
|
518
|
+
const password = presentEnvValue(reader, `ADGUARD_${upperName}_PASSWORD`);
|
|
66
519
|
const missing = [];
|
|
67
520
|
if (!url) missing.push("URL");
|
|
68
521
|
if (!username) missing.push("USERNAME");
|
|
@@ -70,10 +523,14 @@ function resolveInstances(env) {
|
|
|
70
523
|
if (missing.length > 0) {
|
|
71
524
|
throw new PartialInstanceConfigError(name, missing);
|
|
72
525
|
}
|
|
73
|
-
instances[name] = {
|
|
526
|
+
instances[name] = {
|
|
527
|
+
url: readRequiredInstanceField(reader, `ADGUARD_${upperName}_URL`),
|
|
528
|
+
username: readRequiredInstanceField(reader, `ADGUARD_${upperName}_USERNAME`),
|
|
529
|
+
password: readRequiredInstanceField(reader, `ADGUARD_${upperName}_PASSWORD`)
|
|
530
|
+
};
|
|
74
531
|
}
|
|
75
532
|
if (Object.keys(instances).length === 0) throw new NoInstancesError();
|
|
76
|
-
const explicitDefault =
|
|
533
|
+
const explicitDefault = readDefaultInstance(reader);
|
|
77
534
|
if (explicitDefault) {
|
|
78
535
|
if (!instances[explicitDefault]) {
|
|
79
536
|
throw new UnknownDefaultInstanceError(explicitDefault, Object.keys(instances));
|
|
@@ -84,9 +541,10 @@ function resolveInstances(env) {
|
|
|
84
541
|
return { instances, defaultInstance };
|
|
85
542
|
}
|
|
86
543
|
function resolveSyncConfig(env) {
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
const
|
|
544
|
+
const reader = fromProcessEnv(env);
|
|
545
|
+
const url = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_URL", "ADGUARD_SYNC_URL"]);
|
|
546
|
+
const username = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_USERNAME", "ADGUARD_SYNC_USERNAME"]);
|
|
547
|
+
const password = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_PASSWORD", "ADGUARD_SYNC_PASSWORD"]);
|
|
90
548
|
const missing = [];
|
|
91
549
|
if (!url && (username || password)) missing.push("URL");
|
|
92
550
|
if (username && !password) missing.push("PASSWORD");
|
|
@@ -105,6 +563,57 @@ function getSyncConfig(cfg) {
|
|
|
105
563
|
if (!cfg) throw new NoSyncServerError();
|
|
106
564
|
return cfg;
|
|
107
565
|
}
|
|
566
|
+
function resolveRequestTimeoutMs(env) {
|
|
567
|
+
const reader = fromProcessEnv(env);
|
|
568
|
+
return Effect6.runSync(
|
|
569
|
+
parseTimeoutEnv(reader, "ADGUARD_REQUEST_TIMEOUT_MS", {
|
|
570
|
+
fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
|
|
571
|
+
minMs: MIN_REQUEST_TIMEOUT_MS,
|
|
572
|
+
unit: "ms"
|
|
573
|
+
})
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// src/adguard-client.ts
|
|
578
|
+
import { Effect as Effect7 } from "effect";
|
|
579
|
+
|
|
580
|
+
// src/security.ts
|
|
581
|
+
import { createHash, timingSafeEqual } from "crypto";
|
|
582
|
+
var SECRETS = /* @__PURE__ */ new Set();
|
|
583
|
+
function registerSecret(s) {
|
|
584
|
+
if (!s || s.length === 0) return;
|
|
585
|
+
SECRETS.add(s);
|
|
586
|
+
}
|
|
587
|
+
var BASE64_TOKEN = /[A-Za-z0-9+/]{12,}={0,2}/g;
|
|
588
|
+
function maskBase64Tokens(input) {
|
|
589
|
+
return input.replace(BASE64_TOKEN, (match) => {
|
|
590
|
+
let decoded;
|
|
591
|
+
try {
|
|
592
|
+
decoded = Buffer.from(match, "base64").toString("utf8");
|
|
593
|
+
} catch {
|
|
594
|
+
return match;
|
|
595
|
+
}
|
|
596
|
+
for (const secret of SECRETS) {
|
|
597
|
+
if (decoded.includes(secret)) return "REDACTED";
|
|
598
|
+
}
|
|
599
|
+
return match;
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
function redact(value) {
|
|
603
|
+
if (typeof value === "string") {
|
|
604
|
+
let out = value;
|
|
605
|
+
for (const secret of SECRETS) out = out.split(secret).join("REDACTED");
|
|
606
|
+
out = maskBase64Tokens(out);
|
|
607
|
+
return out;
|
|
608
|
+
}
|
|
609
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
610
|
+
if (value && typeof value === "object") {
|
|
611
|
+
const out = {};
|
|
612
|
+
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
613
|
+
return out;
|
|
614
|
+
}
|
|
615
|
+
return value;
|
|
616
|
+
}
|
|
108
617
|
|
|
109
618
|
// src/adguard-client.ts
|
|
110
619
|
var AdGuardClientError = class extends Error {
|
|
@@ -113,7 +622,6 @@ var AdGuardClientError = class extends Error {
|
|
|
113
622
|
this.status = status;
|
|
114
623
|
this.name = "AdGuardClientError";
|
|
115
624
|
}
|
|
116
|
-
status;
|
|
117
625
|
};
|
|
118
626
|
var AdGuardUnreachableError = class extends Error {
|
|
119
627
|
constructor(cause) {
|
|
@@ -125,11 +633,23 @@ var AdGuardClient = class {
|
|
|
125
633
|
constructor(cfg, opts = {}) {
|
|
126
634
|
this.cfg = cfg;
|
|
127
635
|
this.authHeader = "Basic " + Buffer.from(`${cfg.username}:${cfg.password}`).toString("base64");
|
|
636
|
+
registerSecret(cfg.password);
|
|
637
|
+
registerSecret(this.authHeader);
|
|
128
638
|
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
639
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
640
|
+
this.baseUrl = baseUrlForConcat(cfg.url);
|
|
641
|
+
this.auth = {
|
|
642
|
+
apply: (headers) => {
|
|
643
|
+
headers.set("authorization", this.authHeader);
|
|
644
|
+
return Effect7.succeed(headers);
|
|
645
|
+
}
|
|
646
|
+
};
|
|
129
647
|
}
|
|
130
|
-
cfg;
|
|
131
648
|
authHeader;
|
|
132
649
|
retryDelayMs;
|
|
650
|
+
timeoutMs;
|
|
651
|
+
baseUrl;
|
|
652
|
+
auth;
|
|
133
653
|
async get(path) {
|
|
134
654
|
return this.request("GET", path);
|
|
135
655
|
}
|
|
@@ -140,42 +660,117 @@ var AdGuardClient = class {
|
|
|
140
660
|
return this.request("PUT", path, body);
|
|
141
661
|
}
|
|
142
662
|
async request(method, path, body) {
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
-
let bodyStr;
|
|
146
|
-
if (body !== void 0) {
|
|
147
|
-
headers["content-type"] = "application/json";
|
|
148
|
-
bodyStr = JSON.stringify(body);
|
|
149
|
-
}
|
|
150
|
-
let lastErr;
|
|
151
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
663
|
+
const reqPath = pathForConcat(path);
|
|
664
|
+
const httpEffect = (() => {
|
|
152
665
|
try {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
} catch (
|
|
171
|
-
|
|
172
|
-
lastErr = new AdGuardUnreachableError(e.message);
|
|
173
|
-
if (attempt === 0) await sleep(this.retryDelayMs);
|
|
666
|
+
return sendRequest(
|
|
667
|
+
{
|
|
668
|
+
baseUrl: this.baseUrl,
|
|
669
|
+
auth: this.auth,
|
|
670
|
+
timeoutMs: this.timeoutMs,
|
|
671
|
+
fetch: fetchWithPlainHeaders,
|
|
672
|
+
redact: identityRedact
|
|
673
|
+
},
|
|
674
|
+
{
|
|
675
|
+
method,
|
|
676
|
+
path: reqPath,
|
|
677
|
+
body,
|
|
678
|
+
responseType: "text",
|
|
679
|
+
expectedStatuses: successStatuses,
|
|
680
|
+
statusMapper: ({ status, method: method2, path: path2, bodyText, expectedStatuses }) => new UnexpectedStatusError({ status, method: method2, path: path2, body: bodyText, expected: expectedStatuses })
|
|
681
|
+
}
|
|
682
|
+
);
|
|
683
|
+
} catch (error) {
|
|
684
|
+
throw new AdGuardUnreachableError(errorMessage(error));
|
|
174
685
|
}
|
|
175
|
-
}
|
|
176
|
-
|
|
686
|
+
})();
|
|
687
|
+
const effect = withRetry(
|
|
688
|
+
httpEffect,
|
|
689
|
+
exponentialRetry({
|
|
690
|
+
maxAttempts: 2,
|
|
691
|
+
initialDelayMs: this.retryDelayMs,
|
|
692
|
+
maxDelayMs: this.retryDelayMs,
|
|
693
|
+
jitter: false,
|
|
694
|
+
shouldRetry: (error) => error._tag === "TransportError" || error._tag === "TimeoutError" || error._tag === "UnexpectedStatusError" && error.status >= 500
|
|
695
|
+
})
|
|
696
|
+
).pipe(
|
|
697
|
+
Effect7.map((res) => parseSuccessBody(res.bodyText)),
|
|
698
|
+
Effect7.mapError((error) => toAdGuardError(error))
|
|
699
|
+
);
|
|
700
|
+
return Effect7.runPromise(Effect7.either(effect)).then((result) => {
|
|
701
|
+
if (result._tag === "Right") return result.right;
|
|
702
|
+
throw result.left;
|
|
703
|
+
});
|
|
177
704
|
}
|
|
178
705
|
};
|
|
706
|
+
var successStatuses = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
707
|
+
function toAdGuardError(error) {
|
|
708
|
+
if (error._tag === "UnexpectedStatusError") {
|
|
709
|
+
if (error.status >= 500) return new AdGuardUnreachableError(`HTTP ${error.status}`);
|
|
710
|
+
return new AdGuardClientError(error.status, extractErrorMessage(error.body));
|
|
711
|
+
}
|
|
712
|
+
if (error._tag === "TransportError") {
|
|
713
|
+
return new AdGuardUnreachableError(errorMessage(error.cause));
|
|
714
|
+
}
|
|
715
|
+
if (error._tag === "TimeoutError") return new AdGuardUnreachableError("The operation was aborted.");
|
|
716
|
+
if (error._tag === "ParseError") return new AdGuardUnreachableError(error.message);
|
|
717
|
+
return new AdGuardUnreachableError(String(error));
|
|
718
|
+
}
|
|
719
|
+
function extractErrorMessage(text) {
|
|
720
|
+
let msg = text;
|
|
721
|
+
try {
|
|
722
|
+
msg = JSON.parse(text).message ?? text;
|
|
723
|
+
} catch {
|
|
724
|
+
}
|
|
725
|
+
return redact(msg);
|
|
726
|
+
}
|
|
727
|
+
function errorMessage(error) {
|
|
728
|
+
return error instanceof Error ? error.message : String(error);
|
|
729
|
+
}
|
|
730
|
+
function identityRedact(value) {
|
|
731
|
+
return value;
|
|
732
|
+
}
|
|
733
|
+
function baseUrlForConcat(raw) {
|
|
734
|
+
return new URL(raw.replace(/\/+$/, "") + "/");
|
|
735
|
+
}
|
|
736
|
+
function pathForConcat(path) {
|
|
737
|
+
return path.replace(/^\/+/, "");
|
|
738
|
+
}
|
|
739
|
+
async function fetchWithPlainHeaders(input, init) {
|
|
740
|
+
const headers = init?.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init?.headers;
|
|
741
|
+
const signal = init?.signal;
|
|
742
|
+
const response = await fetch(input.toString(), { ...init, headers });
|
|
743
|
+
const bodyText = await new Promise((resolve, reject) => {
|
|
744
|
+
const abortError = () => Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
|
|
745
|
+
if (signal?.aborted) {
|
|
746
|
+
void response.body?.cancel().catch(() => {
|
|
747
|
+
});
|
|
748
|
+
reject(abortError());
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
const onAbort = () => {
|
|
752
|
+
void response.body?.cancel().catch(() => {
|
|
753
|
+
});
|
|
754
|
+
reject(abortError());
|
|
755
|
+
};
|
|
756
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
757
|
+
response.text().then(
|
|
758
|
+
(text) => {
|
|
759
|
+
signal?.removeEventListener("abort", onAbort);
|
|
760
|
+
resolve(text);
|
|
761
|
+
},
|
|
762
|
+
(err) => {
|
|
763
|
+
signal?.removeEventListener("abort", onAbort);
|
|
764
|
+
reject(err);
|
|
765
|
+
}
|
|
766
|
+
);
|
|
767
|
+
});
|
|
768
|
+
return new Response(bodyText, {
|
|
769
|
+
status: response.status,
|
|
770
|
+
statusText: response.statusText,
|
|
771
|
+
headers: response.headers
|
|
772
|
+
});
|
|
773
|
+
}
|
|
179
774
|
function parseSuccessBody(text) {
|
|
180
775
|
if (!text) return void 0;
|
|
181
776
|
try {
|
|
@@ -184,18 +779,15 @@ function parseSuccessBody(text) {
|
|
|
184
779
|
return text;
|
|
185
780
|
}
|
|
186
781
|
}
|
|
187
|
-
function sleep(ms) {
|
|
188
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
189
|
-
}
|
|
190
782
|
|
|
191
783
|
// src/adguard-sync-client.ts
|
|
784
|
+
import { Effect as Effect8 } from "effect";
|
|
192
785
|
var AdGuardSyncClientError = class extends Error {
|
|
193
786
|
constructor(status, message) {
|
|
194
787
|
super(`AdGuardHome Sync ${status}: ${message}`);
|
|
195
788
|
this.status = status;
|
|
196
789
|
this.name = "AdGuardSyncClientError";
|
|
197
790
|
}
|
|
198
|
-
status;
|
|
199
791
|
};
|
|
200
792
|
var AdGuardSyncUnreachableError = class extends Error {
|
|
201
793
|
constructor(cause) {
|
|
@@ -208,12 +800,24 @@ var AdGuardSyncClient = class {
|
|
|
208
800
|
this.cfg = cfg;
|
|
209
801
|
if (cfg.username && cfg.password) {
|
|
210
802
|
this.authHeader = "Basic " + Buffer.from(`${cfg.username}:${cfg.password}`).toString("base64");
|
|
803
|
+
registerSecret(cfg.password);
|
|
804
|
+
registerSecret(this.authHeader);
|
|
805
|
+
this.auth = {
|
|
806
|
+
apply: (headers) => {
|
|
807
|
+
headers.set("authorization", this.authHeader);
|
|
808
|
+
return Effect8.succeed(headers);
|
|
809
|
+
}
|
|
810
|
+
};
|
|
211
811
|
}
|
|
212
812
|
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
813
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
814
|
+
this.baseUrl = baseUrlForConcat2(cfg.url);
|
|
213
815
|
}
|
|
214
|
-
cfg;
|
|
215
816
|
authHeader;
|
|
216
817
|
retryDelayMs;
|
|
818
|
+
timeoutMs;
|
|
819
|
+
baseUrl;
|
|
820
|
+
auth;
|
|
217
821
|
async get(path) {
|
|
218
822
|
return this.request("GET", path);
|
|
219
823
|
}
|
|
@@ -225,91 +829,124 @@ var AdGuardSyncClient = class {
|
|
|
225
829
|
return { ok: true };
|
|
226
830
|
}
|
|
227
831
|
async request(method, path, body) {
|
|
228
|
-
const
|
|
229
|
-
const
|
|
230
|
-
if (this.authHeader) headers.authorization = this.authHeader;
|
|
231
|
-
let bodyStr;
|
|
232
|
-
if (body !== void 0) {
|
|
233
|
-
headers["content-type"] = "application/json";
|
|
234
|
-
bodyStr = JSON.stringify(body);
|
|
235
|
-
}
|
|
236
|
-
let lastErr;
|
|
237
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
832
|
+
const reqPath = pathForConcat2(path);
|
|
833
|
+
const httpEffect = (() => {
|
|
238
834
|
try {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (e instanceof AdGuardSyncClientError) throw e;
|
|
259
|
-
lastErr = new AdGuardSyncUnreachableError(e.message);
|
|
260
|
-
if (attempt === 0) await sleep2(this.retryDelayMs);
|
|
835
|
+
return sendRequest(
|
|
836
|
+
{
|
|
837
|
+
baseUrl: this.baseUrl,
|
|
838
|
+
auth: this.auth,
|
|
839
|
+
timeoutMs: this.timeoutMs,
|
|
840
|
+
fetch: fetchWithPlainHeaders2,
|
|
841
|
+
redact: identityRedact2
|
|
842
|
+
},
|
|
843
|
+
{
|
|
844
|
+
method,
|
|
845
|
+
path: reqPath,
|
|
846
|
+
body,
|
|
847
|
+
responseType: method === "HEAD" ? "none" : "text",
|
|
848
|
+
expectedStatuses: successStatuses2,
|
|
849
|
+
statusMapper: ({ status, method: method2, path: path2, bodyText, expectedStatuses }) => new UnexpectedStatusError({ status, method: method2, path: path2, body: bodyText, expected: expectedStatuses })
|
|
850
|
+
}
|
|
851
|
+
);
|
|
852
|
+
} catch (error) {
|
|
853
|
+
throw new AdGuardSyncUnreachableError(errorMessage2(error));
|
|
261
854
|
}
|
|
262
|
-
}
|
|
263
|
-
|
|
855
|
+
})();
|
|
856
|
+
const effect = withRetry(
|
|
857
|
+
httpEffect,
|
|
858
|
+
exponentialRetry({
|
|
859
|
+
maxAttempts: 2,
|
|
860
|
+
initialDelayMs: this.retryDelayMs,
|
|
861
|
+
maxDelayMs: this.retryDelayMs,
|
|
862
|
+
jitter: false,
|
|
863
|
+
shouldRetry: (error) => error._tag === "TransportError" || error._tag === "TimeoutError" || error._tag === "UnexpectedStatusError" && error.status >= 500
|
|
864
|
+
})
|
|
865
|
+
).pipe(
|
|
866
|
+
Effect8.map((res) => method === "HEAD" ? void 0 : parseSuccessBody2(res.bodyText)),
|
|
867
|
+
Effect8.mapError((error) => toSyncError(error))
|
|
868
|
+
);
|
|
869
|
+
return Effect8.runPromise(Effect8.either(effect)).then((result) => {
|
|
870
|
+
if (result._tag === "Right") return result.right;
|
|
871
|
+
throw result.left;
|
|
872
|
+
});
|
|
264
873
|
}
|
|
265
874
|
};
|
|
266
|
-
|
|
267
|
-
|
|
875
|
+
var successStatuses2 = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
876
|
+
function toSyncError(error) {
|
|
877
|
+
if (error._tag === "UnexpectedStatusError") {
|
|
878
|
+
if (error.status >= 500) return new AdGuardSyncUnreachableError(`HTTP ${error.status}`);
|
|
879
|
+
return new AdGuardSyncClientError(error.status, extractErrorMessage2(error.body));
|
|
880
|
+
}
|
|
881
|
+
if (error._tag === "TransportError") {
|
|
882
|
+
return new AdGuardSyncUnreachableError(errorMessage2(error.cause));
|
|
883
|
+
}
|
|
884
|
+
if (error._tag === "TimeoutError") return new AdGuardSyncUnreachableError("The operation was aborted.");
|
|
885
|
+
if (error._tag === "ParseError") return new AdGuardSyncUnreachableError(error.message);
|
|
886
|
+
return new AdGuardSyncUnreachableError(String(error));
|
|
887
|
+
}
|
|
888
|
+
function extractErrorMessage2(text) {
|
|
889
|
+
let msg = text;
|
|
268
890
|
try {
|
|
269
|
-
|
|
891
|
+
msg = JSON.parse(text).message ?? text;
|
|
270
892
|
} catch {
|
|
271
|
-
return text;
|
|
272
893
|
}
|
|
894
|
+
return redact(msg);
|
|
273
895
|
}
|
|
274
|
-
function
|
|
275
|
-
return
|
|
896
|
+
function errorMessage2(error) {
|
|
897
|
+
return error instanceof Error ? error.message : String(error);
|
|
276
898
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
var SECRETS = /* @__PURE__ */ new Set();
|
|
280
|
-
function registerSecret(s) {
|
|
281
|
-
if (!s || s.length === 0) return;
|
|
282
|
-
SECRETS.add(s);
|
|
899
|
+
function identityRedact2(value) {
|
|
900
|
+
return value;
|
|
283
901
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
902
|
+
function baseUrlForConcat2(raw) {
|
|
903
|
+
return new URL(raw.replace(/\/+$/, "") + "/");
|
|
904
|
+
}
|
|
905
|
+
function pathForConcat2(path) {
|
|
906
|
+
return path.replace(/^\/+/, "");
|
|
907
|
+
}
|
|
908
|
+
async function fetchWithPlainHeaders2(input, init) {
|
|
909
|
+
const headers = init?.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init?.headers;
|
|
910
|
+
const signal = init?.signal;
|
|
911
|
+
const response = await fetch(input.toString(), { ...init, headers });
|
|
912
|
+
const bodyText = await new Promise((resolve, reject) => {
|
|
913
|
+
const abortError = () => Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
|
|
914
|
+
if (signal?.aborted) {
|
|
915
|
+
void response.body?.cancel().catch(() => {
|
|
916
|
+
});
|
|
917
|
+
reject(abortError());
|
|
918
|
+
return;
|
|
292
919
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
920
|
+
const onAbort = () => {
|
|
921
|
+
void response.body?.cancel().catch(() => {
|
|
922
|
+
});
|
|
923
|
+
reject(abortError());
|
|
924
|
+
};
|
|
925
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
926
|
+
response.text().then(
|
|
927
|
+
(text) => {
|
|
928
|
+
signal?.removeEventListener("abort", onAbort);
|
|
929
|
+
resolve(text);
|
|
930
|
+
},
|
|
931
|
+
(err) => {
|
|
932
|
+
signal?.removeEventListener("abort", onAbort);
|
|
933
|
+
reject(err);
|
|
934
|
+
}
|
|
935
|
+
);
|
|
936
|
+
});
|
|
937
|
+
return new Response(bodyText, {
|
|
938
|
+
status: response.status,
|
|
939
|
+
statusText: response.statusText,
|
|
940
|
+
headers: response.headers
|
|
297
941
|
});
|
|
298
942
|
}
|
|
299
|
-
function
|
|
300
|
-
if (
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
return
|
|
305
|
-
}
|
|
306
|
-
if (Array.isArray(value)) return value.map(redact);
|
|
307
|
-
if (value && typeof value === "object") {
|
|
308
|
-
const out = {};
|
|
309
|
-
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
310
|
-
return out;
|
|
943
|
+
function parseSuccessBody2(text) {
|
|
944
|
+
if (!text) return void 0;
|
|
945
|
+
try {
|
|
946
|
+
return JSON.parse(text);
|
|
947
|
+
} catch {
|
|
948
|
+
return text;
|
|
311
949
|
}
|
|
312
|
-
return value;
|
|
313
950
|
}
|
|
314
951
|
|
|
315
952
|
// src/tools/adguard_status.ts
|
|
@@ -321,8 +958,9 @@ var InstanceArg = Type.Optional(Type.String({
|
|
|
321
958
|
description: "Named instance to target (e.g. 'primary', 'secondary'). Default: the configured default instance."
|
|
322
959
|
}));
|
|
323
960
|
function jsonToolResult(payload) {
|
|
961
|
+
const kitResult = ok(payload);
|
|
324
962
|
return {
|
|
325
|
-
content:
|
|
963
|
+
content: kitResult.content
|
|
326
964
|
};
|
|
327
965
|
}
|
|
328
966
|
function hhmmToMs(value) {
|
|
@@ -513,16 +1151,28 @@ var WriteGateError = class extends Error {
|
|
|
513
1151
|
this.name = "WriteGateError";
|
|
514
1152
|
}
|
|
515
1153
|
};
|
|
1154
|
+
function throwGateRefusal(message) {
|
|
1155
|
+
const kitResult = fail(message);
|
|
1156
|
+
let extracted = message;
|
|
1157
|
+
try {
|
|
1158
|
+
const parsed = JSON.parse(kitResult.content[0]?.text ?? "");
|
|
1159
|
+
if (typeof parsed.error === "string") extracted = parsed.error;
|
|
1160
|
+
} catch {
|
|
1161
|
+
}
|
|
1162
|
+
throw new WriteGateError(extracted);
|
|
1163
|
+
}
|
|
516
1164
|
function assertConfirmedWrite(args, toolName) {
|
|
517
1165
|
if (args.confirm !== true) {
|
|
518
|
-
|
|
1166
|
+
void refuseUnconfirmed(toolName);
|
|
1167
|
+
throwGateRefusal(
|
|
519
1168
|
`${toolName} is a write operation. Pass {"confirm": true} to proceed.`
|
|
520
1169
|
);
|
|
521
1170
|
}
|
|
522
1171
|
}
|
|
523
1172
|
function assertDestructive(args, toolName) {
|
|
524
1173
|
if (args.confirm !== true || args.destructive !== true) {
|
|
525
|
-
|
|
1174
|
+
void refuseUnconfirmed(toolName);
|
|
1175
|
+
throwGateRefusal(
|
|
526
1176
|
`${toolName} is a destructive operation. Pass {"confirm": true, "destructive": true} to proceed.`
|
|
527
1177
|
);
|
|
528
1178
|
}
|
|
@@ -1703,6 +2353,13 @@ function buildAllTools(getClient, getSyncClient) {
|
|
|
1703
2353
|
}
|
|
1704
2354
|
|
|
1705
2355
|
// index.ts
|
|
2356
|
+
function mcpToolError(message) {
|
|
2357
|
+
const failed = fail(message);
|
|
2358
|
+
return {
|
|
2359
|
+
content: [{ type: "text", text: JSON.stringify({ error: message }) }],
|
|
2360
|
+
isError: failed.isError
|
|
2361
|
+
};
|
|
2362
|
+
}
|
|
1706
2363
|
function withRedactedErrors(tool) {
|
|
1707
2364
|
const orig = tool.execute.bind(tool);
|
|
1708
2365
|
return {
|
|
@@ -1711,13 +2368,12 @@ function withRedactedErrors(tool) {
|
|
|
1711
2368
|
try {
|
|
1712
2369
|
return await orig(id, args);
|
|
1713
2370
|
} catch (e) {
|
|
1714
|
-
|
|
1715
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
2371
|
+
return mcpToolError(redact(operatorErrorMessage(e)));
|
|
1716
2372
|
}
|
|
1717
2373
|
}
|
|
1718
2374
|
};
|
|
1719
2375
|
}
|
|
1720
|
-
function makeFactory(cfg) {
|
|
2376
|
+
function makeFactory(cfg, timeoutMs) {
|
|
1721
2377
|
for (const inst of Object.values(cfg.instances)) {
|
|
1722
2378
|
registerSecret(inst.password);
|
|
1723
2379
|
const basicValue = "Basic " + Buffer2.from(`${inst.username}:${inst.password}`).toString("base64");
|
|
@@ -1725,7 +2381,7 @@ function makeFactory(cfg) {
|
|
|
1725
2381
|
}
|
|
1726
2382
|
return (name) => {
|
|
1727
2383
|
const ic = getInstanceConfig(cfg, name);
|
|
1728
|
-
return new AdGuardClient(ic);
|
|
2384
|
+
return new AdGuardClient(ic, { timeoutMs });
|
|
1729
2385
|
};
|
|
1730
2386
|
}
|
|
1731
2387
|
function registerSyncSecrets(syncCfg) {
|
|
@@ -1736,9 +2392,9 @@ function registerSyncSecrets(syncCfg) {
|
|
|
1736
2392
|
registerSecret(basicValue);
|
|
1737
2393
|
}
|
|
1738
2394
|
}
|
|
1739
|
-
function makeSyncFactory(syncCfg) {
|
|
2395
|
+
function makeSyncFactory(syncCfg, timeoutMs) {
|
|
1740
2396
|
registerSyncSecrets(syncCfg);
|
|
1741
|
-
return () => new AdGuardSyncClient(getSyncConfig(syncCfg));
|
|
2397
|
+
return () => new AdGuardSyncClient(getSyncConfig(syncCfg), { timeoutMs });
|
|
1742
2398
|
}
|
|
1743
2399
|
var index_default = definePluginEntry({
|
|
1744
2400
|
id: "adguard",
|
|
@@ -1748,8 +2404,9 @@ var index_default = definePluginEntry({
|
|
|
1748
2404
|
if (api.registrationMode !== "full") return;
|
|
1749
2405
|
const cfg = resolveInstances(process.env);
|
|
1750
2406
|
const syncCfg = resolveSyncConfig(process.env);
|
|
1751
|
-
const
|
|
1752
|
-
const
|
|
2407
|
+
const timeoutMs = resolveRequestTimeoutMs(process.env);
|
|
2408
|
+
const getClient = makeFactory(cfg, timeoutMs);
|
|
2409
|
+
const getSyncClient = makeSyncFactory(syncCfg, timeoutMs);
|
|
1753
2410
|
const register = (t) => api.registerTool(withRedactedErrors(t));
|
|
1754
2411
|
for (const t of buildAllTools(getClient, getSyncClient)) register(t);
|
|
1755
2412
|
}
|