@nite07/websearch-mcp 0.1.4 → 0.2.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/README.md +46 -0
- package/README.zh.md +38 -0
- package/dist/live.d.ts +21 -0
- package/dist/live.js +52 -0
- package/dist/main.js +217 -37
- package/dist/sdk.d.ts +21 -0
- package/dist/sdk.js +88 -0
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +20 -4
- package/dist/ui/embedded.d.ts +20 -0
- package/dist/ui/embedded.js +14 -0
- package/dist/ui/page.d.ts +2 -0
- package/dist/ui/page.html +694 -0
- package/dist/ui/page.js +15 -0
- package/dist/ui/server.d.ts +21 -0
- package/dist/ui/server.js +243 -0
- package/dist/ui/session.d.ts +38 -0
- package/dist/ui/session.js +111 -0
- package/dist/ui/state.d.ts +62 -0
- package/dist/ui/state.js +256 -0
- package/dist/ui/token.d.ts +23 -0
- package/dist/ui/token.js +23 -0
- package/package.json +3 -2
- package/dist/protocol.d.ts +0 -19
- package/dist/protocol.js +0 -125
package/dist/ui/page.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
const asset = fileURLToPath(new URL('./page.html', import.meta.url));
|
|
4
|
+
let cache;
|
|
5
|
+
/** The page is a build asset, not a template: it ships beside the compiled server and is read once. */
|
|
6
|
+
export async function renderPage() {
|
|
7
|
+
const info = await stat(asset).catch(() => undefined);
|
|
8
|
+
if (!info)
|
|
9
|
+
throw new Error(`The settings page asset is missing at ${asset}; run npm run build.`);
|
|
10
|
+
if (cache && cache.mtimeMs === info.mtimeMs)
|
|
11
|
+
return cache.body;
|
|
12
|
+
const body = await readFile(asset, 'utf8');
|
|
13
|
+
cache = { mtimeMs: info.mtimeMs, body };
|
|
14
|
+
return body;
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { SessionStore } from './session.js';
|
|
2
|
+
export interface UiOptions {
|
|
3
|
+
configPath: string;
|
|
4
|
+
host: string;
|
|
5
|
+
port: number;
|
|
6
|
+
/** Absent means no authentication: whoever can reach the port can rewrite the configuration. */
|
|
7
|
+
token?: string;
|
|
8
|
+
version: string;
|
|
9
|
+
log: (message: string) => void;
|
|
10
|
+
}
|
|
11
|
+
export interface UiHandle {
|
|
12
|
+
port: number;
|
|
13
|
+
urls: string[];
|
|
14
|
+
token?: string;
|
|
15
|
+
sessions?: SessionStore;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export declare function displayHosts(host: string): string[];
|
|
19
|
+
export declare function baseUrls(host: string, port: number): string[];
|
|
20
|
+
export declare function tokenUrls(host: string, port: number, token?: string): string[];
|
|
21
|
+
export declare function startUi(options: UiOptions): Promise<UiHandle>;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { networkInterfaces } from 'node:os';
|
|
3
|
+
import { catalog, SearchEngine } from '@nite07/search-core';
|
|
4
|
+
import { credentialResolver, loadConfig } from '../config.js';
|
|
5
|
+
import { renderPage } from './page.js';
|
|
6
|
+
import { FailureLimiter, SessionStore, SESSION_COOKIE, cookieValue, sessionCookie } from './session.js';
|
|
7
|
+
import { SettingsError, saveConfig, saveCredential, snapshot } from './state.js';
|
|
8
|
+
const MAX_BODY = 1024 * 1024;
|
|
9
|
+
const SECURITY_HEADERS = {
|
|
10
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
11
|
+
'Referrer-Policy': 'no-referrer',
|
|
12
|
+
'X-Content-Type-Options': 'nosniff',
|
|
13
|
+
'X-Frame-Options': 'DENY',
|
|
14
|
+
};
|
|
15
|
+
export function displayHosts(host) {
|
|
16
|
+
if (host === '0.0.0.0' || host === '::' || host === '') {
|
|
17
|
+
const external = Object.values(networkInterfaces())
|
|
18
|
+
.flat()
|
|
19
|
+
.filter((entry) => Boolean(entry) && entry.family === 'IPv4' && !entry.internal)
|
|
20
|
+
.map(entry => entry.address);
|
|
21
|
+
return ['127.0.0.1', ...new Set(external)];
|
|
22
|
+
}
|
|
23
|
+
return [host];
|
|
24
|
+
}
|
|
25
|
+
const withBrackets = (host) => (host.includes(':') ? `[${host}]` : host);
|
|
26
|
+
export function baseUrls(host, port) {
|
|
27
|
+
return displayHosts(host).map(item => `http://${withBrackets(item)}:${port}`);
|
|
28
|
+
}
|
|
29
|
+
export function tokenUrls(host, port, token) {
|
|
30
|
+
return baseUrls(host, port).map(base => (token ? `${base}/?token=${encodeURIComponent(token)}` : base));
|
|
31
|
+
}
|
|
32
|
+
export async function startUi(options) {
|
|
33
|
+
let actualPort = options.port;
|
|
34
|
+
const token = options.token;
|
|
35
|
+
const sessions = token === undefined ? undefined : new SessionStore(token);
|
|
36
|
+
const limiter = new FailureLimiter();
|
|
37
|
+
const server = createServer((request, response) => {
|
|
38
|
+
handle(request, response).catch(error => {
|
|
39
|
+
options.log(`request failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
40
|
+
if (!response.headersSent)
|
|
41
|
+
json(response, 500, { error: 'Internal error.' });
|
|
42
|
+
else
|
|
43
|
+
response.end();
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
const prune = setInterval(() => sessions?.prune(), 60_000);
|
|
47
|
+
prune.unref?.();
|
|
48
|
+
await new Promise((resolve, reject) => {
|
|
49
|
+
const onError = (error) => {
|
|
50
|
+
server.off('listening', onListening);
|
|
51
|
+
reject(error.code === 'EADDRINUSE'
|
|
52
|
+
? new Error(`Port ${options.port} on ${options.host} is already in use; pass --port to choose another.`)
|
|
53
|
+
: error);
|
|
54
|
+
};
|
|
55
|
+
const onListening = () => {
|
|
56
|
+
server.off('error', onError);
|
|
57
|
+
resolve();
|
|
58
|
+
};
|
|
59
|
+
server.once('error', onError);
|
|
60
|
+
server.once('listening', onListening);
|
|
61
|
+
server.listen(options.port, options.host);
|
|
62
|
+
});
|
|
63
|
+
const address = server.address();
|
|
64
|
+
const port = typeof address === 'object' && address ? address.port : options.port;
|
|
65
|
+
actualPort = port;
|
|
66
|
+
return {
|
|
67
|
+
port,
|
|
68
|
+
...(token === undefined ? {} : { token }),
|
|
69
|
+
urls: tokenUrls(options.host, port, token),
|
|
70
|
+
sessions,
|
|
71
|
+
close: async () => {
|
|
72
|
+
clearInterval(prune);
|
|
73
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
async function handle(request, response) {
|
|
77
|
+
const method = request.method ?? 'GET';
|
|
78
|
+
const url = new URL(request.url ?? '/', `http://${request.headers.host ?? '127.0.0.1'}`);
|
|
79
|
+
const ip = request.socket.remoteAddress ?? 'unknown';
|
|
80
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS))
|
|
81
|
+
response.setHeader(name, value);
|
|
82
|
+
// A same-origin page is the only thing allowed to change state: the cookie is SameSite=Strict,
|
|
83
|
+
// and a foreign Origin is refused outright rather than relying on the browser alone.
|
|
84
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
85
|
+
const origin = request.headers.origin;
|
|
86
|
+
if (origin && origin !== 'null') {
|
|
87
|
+
let same = false;
|
|
88
|
+
try {
|
|
89
|
+
same = new URL(origin).host === (request.headers.host ?? '');
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
same = false;
|
|
93
|
+
}
|
|
94
|
+
if (!same)
|
|
95
|
+
return json(response, 403, { error: 'Cross-origin requests are refused.' });
|
|
96
|
+
}
|
|
97
|
+
const type = String(request.headers['content-type'] ?? '');
|
|
98
|
+
if (!type.toLowerCase().startsWith('application/json'))
|
|
99
|
+
return json(response, 415, { error: 'Send application/json.' });
|
|
100
|
+
}
|
|
101
|
+
if (url.pathname === '/favicon.ico') {
|
|
102
|
+
response.writeHead(204);
|
|
103
|
+
response.end();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (url.pathname === '/' && method === 'GET') {
|
|
107
|
+
if (!sessions) {
|
|
108
|
+
const page = await renderPage();
|
|
109
|
+
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
110
|
+
response.end(page);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const candidate = url.searchParams.get('token') ?? undefined;
|
|
114
|
+
if (candidate !== undefined) {
|
|
115
|
+
if (limiter.blocked(ip))
|
|
116
|
+
return json(response, 429, { error: 'Too many failed attempts; wait five minutes.' });
|
|
117
|
+
if (!sessions.verify(candidate)) {
|
|
118
|
+
limiter.fail(ip);
|
|
119
|
+
return text(response, 401, 'Token rejected', 'The token in this link is not the current one. Run websearch-mcp --print-url for a fresh link.');
|
|
120
|
+
}
|
|
121
|
+
limiter.clear(ip);
|
|
122
|
+
const id = sessions.issue(ip);
|
|
123
|
+
response.setHeader('Set-Cookie', sessionCookie(id, Math.floor(24 * 3600)));
|
|
124
|
+
response.writeHead(303, { Location: '/' });
|
|
125
|
+
response.end();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!sessions.check(cookieValue(request.headers.cookie, SESSION_COOKIE))) {
|
|
129
|
+
return text(response, 401, 'Token required', 'Open the URL printed by websearch-mcp --print-url, or restart the service and read its log.');
|
|
130
|
+
}
|
|
131
|
+
const page = await renderPage();
|
|
132
|
+
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
133
|
+
response.end(page);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (url.pathname.startsWith('/api/')) {
|
|
137
|
+
if (sessions && !sessions.check(cookieValue(request.headers.cookie, SESSION_COOKIE))) {
|
|
138
|
+
return json(response, 401, { error: 'Session expired. Reload the link from --print-url.' });
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
await api(method, url, request, response, options);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error instanceof SettingsError) {
|
|
145
|
+
return json(response, error.status, { error: error.message, issues: error.issues });
|
|
146
|
+
}
|
|
147
|
+
options.log(`api ${url.pathname} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
148
|
+
return json(response, 500, { error: error instanceof Error ? error.message : 'Internal error.' });
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
return json(response, 404, { error: 'Not found.' });
|
|
153
|
+
}
|
|
154
|
+
async function api(method, url, request, response, settings) {
|
|
155
|
+
if (url.pathname === '/api/settings' && method === 'GET') {
|
|
156
|
+
const current = await snapshot(settings.configPath);
|
|
157
|
+
return json(response, 200, {
|
|
158
|
+
...current,
|
|
159
|
+
version: settings.version,
|
|
160
|
+
bound: { host: settings.host, port: actualPort },
|
|
161
|
+
auth: token === undefined ? 'none' : 'token',
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (url.pathname === '/api/settings' && method === 'PUT') {
|
|
165
|
+
const body = await readJson(request);
|
|
166
|
+
const saved = await saveConfig(settings.configPath, {
|
|
167
|
+
config: body.config,
|
|
168
|
+
compactByDefault: body.compactByDefault,
|
|
169
|
+
expectedRevision: body.expectedRevision,
|
|
170
|
+
});
|
|
171
|
+
settings.log(`configuration saved from the page (revision ${saved.revision})`);
|
|
172
|
+
return json(response, 200, { saved: true, ...saved });
|
|
173
|
+
}
|
|
174
|
+
if (url.pathname === '/api/credentials' && method === 'POST') {
|
|
175
|
+
const body = (await readJson(request));
|
|
176
|
+
const scope = body.scope === 'browser' ? 'browser' : 'backend';
|
|
177
|
+
const saved = await saveCredential(settings.configPath, {
|
|
178
|
+
scope,
|
|
179
|
+
...(typeof body.id === 'string' ? { id: body.id } : {}),
|
|
180
|
+
...(typeof body.value === 'string' ? { value: body.value } : {}),
|
|
181
|
+
...(body.remove === true ? { remove: true } : {}),
|
|
182
|
+
});
|
|
183
|
+
settings.log(`credential ${scope === 'browser' ? 'browser' : String(body.id)} ${body.remove === true ? 'removed' : 'saved'} from the page`);
|
|
184
|
+
return json(response, 200, { saved: true, revision: saved.revision, state: saved.state });
|
|
185
|
+
}
|
|
186
|
+
if (url.pathname === '/api/test' && method === 'POST') {
|
|
187
|
+
const body = (await readJson(request));
|
|
188
|
+
const backendId = typeof body.backendId === 'string' ? body.backendId : '';
|
|
189
|
+
const query = typeof body.query === 'string' && body.query.trim() !== '' ? body.query.trim() : 'websearch-mcp connectivity test';
|
|
190
|
+
if (!catalog.some(item => item.id === backendId))
|
|
191
|
+
throw new SettingsError(`Unknown backend id: ${backendId || '(none)'}.`);
|
|
192
|
+
const config = await loadConfig({ configPath: settings.configPath });
|
|
193
|
+
const backend = config.search.backends[backendId];
|
|
194
|
+
if (!backend?.enabled)
|
|
195
|
+
throw new SettingsError(`${backendId} is disabled in the saved configuration; enable it and save first.`);
|
|
196
|
+
const engine = new SearchEngine(config.search, reference => credentialResolver(config)(reference));
|
|
197
|
+
try {
|
|
198
|
+
const result = await engine.search({ query }, AbortSignal.timeout(30_000), backendId);
|
|
199
|
+
return json(response, 200, {
|
|
200
|
+
ok: true,
|
|
201
|
+
text: result.content,
|
|
202
|
+
sources: result.sources.slice(0, 5).map(source => ({ title: source.title, url: source.url })),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
return json(response, 200, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return json(response, 404, { error: 'Not found.' });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async function readJson(request) {
|
|
213
|
+
const chunks = [];
|
|
214
|
+
let size = 0;
|
|
215
|
+
for await (const chunk of request) {
|
|
216
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
217
|
+
size += buffer.length;
|
|
218
|
+
if (size > MAX_BODY)
|
|
219
|
+
throw new SettingsError('Request body is too large.');
|
|
220
|
+
chunks.push(buffer);
|
|
221
|
+
}
|
|
222
|
+
if (!size)
|
|
223
|
+
throw new SettingsError('A JSON body is required.');
|
|
224
|
+
try {
|
|
225
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
throw new SettingsError('The request body is not valid JSON.');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function json(response, status, value) {
|
|
232
|
+
const body = `${JSON.stringify(value)}\n`;
|
|
233
|
+
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
234
|
+
response.end(body);
|
|
235
|
+
}
|
|
236
|
+
function text(response, status, title, detail) {
|
|
237
|
+
const escape = (input) => input.replace(/[&<>"]/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[character]);
|
|
238
|
+
const body = `<!doctype html><meta charset="utf-8"><title>${escape(title)}</title>
|
|
239
|
+
<body style="font:15px/1.6 ui-sans-serif,system-ui,sans-serif;max-width:38rem;margin:12vh auto;padding:0 1.5rem;color:#111;background:#fff">
|
|
240
|
+
<h1 style="font-size:1.25rem">${escape(title)}</h1><p style="color:#555">${escape(detail)}</p></body>`;
|
|
241
|
+
response.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
242
|
+
response.end(body);
|
|
243
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export declare const SESSION_COOKIE = "wsm_session";
|
|
2
|
+
/**
|
|
3
|
+
* The token arrives from the environment, is exchanged once for an HttpOnly cookie, and lives only in
|
|
4
|
+
* this process: nothing here touches the disk.
|
|
5
|
+
*/
|
|
6
|
+
export declare class SessionStore {
|
|
7
|
+
private readonly token;
|
|
8
|
+
private readonly sessions;
|
|
9
|
+
private readonly now;
|
|
10
|
+
private readonly idleMs;
|
|
11
|
+
private readonly absoluteMs;
|
|
12
|
+
constructor(token: string, options?: {
|
|
13
|
+
idleMs?: number;
|
|
14
|
+
absoluteMs?: number;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
});
|
|
17
|
+
/** Constant-time: a timing side channel here would be a slower way to guess the token. */
|
|
18
|
+
verify(candidate: string | undefined): boolean;
|
|
19
|
+
issue(ip: string): string;
|
|
20
|
+
check(id: string | undefined): boolean;
|
|
21
|
+
revoke(id: string | undefined): void;
|
|
22
|
+
get size(): number;
|
|
23
|
+
/** Drops idle sessions so a long-lived process does not accumulate them. */
|
|
24
|
+
prune(): void;
|
|
25
|
+
}
|
|
26
|
+
/** Failed token guesses are throttled per address: the token is the only thing between the page and the file. */
|
|
27
|
+
export declare class FailureLimiter {
|
|
28
|
+
private readonly limit;
|
|
29
|
+
private readonly banMs;
|
|
30
|
+
private readonly now;
|
|
31
|
+
private readonly hits;
|
|
32
|
+
constructor(limit?: number, banMs?: number, now?: () => number);
|
|
33
|
+
blocked(ip: string): boolean;
|
|
34
|
+
fail(ip: string): void;
|
|
35
|
+
clear(ip: string): void;
|
|
36
|
+
}
|
|
37
|
+
export declare function cookieValue(header: string | undefined, name: string): string | undefined;
|
|
38
|
+
export declare function sessionCookie(id: string, maxAgeSeconds: number): string;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
export const SESSION_COOKIE = 'wsm_session';
|
|
3
|
+
const IDLE_MS = 15 * 60_000;
|
|
4
|
+
const ABSOLUTE_MS = 24 * 60 * 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* The token arrives from the environment, is exchanged once for an HttpOnly cookie, and lives only in
|
|
7
|
+
* this process: nothing here touches the disk.
|
|
8
|
+
*/
|
|
9
|
+
export class SessionStore {
|
|
10
|
+
token;
|
|
11
|
+
sessions = new Map();
|
|
12
|
+
now;
|
|
13
|
+
idleMs;
|
|
14
|
+
absoluteMs;
|
|
15
|
+
constructor(token, options = {}) {
|
|
16
|
+
this.token = token;
|
|
17
|
+
this.now = options.now ?? (() => Date.now());
|
|
18
|
+
this.idleMs = options.idleMs ?? IDLE_MS;
|
|
19
|
+
this.absoluteMs = options.absoluteMs ?? ABSOLUTE_MS;
|
|
20
|
+
}
|
|
21
|
+
/** Constant-time: a timing side channel here would be a slower way to guess the token. */
|
|
22
|
+
verify(candidate) {
|
|
23
|
+
if (!candidate)
|
|
24
|
+
return false;
|
|
25
|
+
const given = Buffer.from(candidate);
|
|
26
|
+
const expected = Buffer.from(this.token);
|
|
27
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
28
|
+
}
|
|
29
|
+
issue(ip) {
|
|
30
|
+
const id = randomBytes(32).toString('base64url');
|
|
31
|
+
const at = this.now();
|
|
32
|
+
this.sessions.set(id, { created: at, seen: at, ip });
|
|
33
|
+
return id;
|
|
34
|
+
}
|
|
35
|
+
check(id) {
|
|
36
|
+
if (!id)
|
|
37
|
+
return false;
|
|
38
|
+
const session = this.sessions.get(id);
|
|
39
|
+
if (!session)
|
|
40
|
+
return false;
|
|
41
|
+
const at = this.now();
|
|
42
|
+
if (at - session.seen > this.idleMs || at - session.created > this.absoluteMs) {
|
|
43
|
+
this.sessions.delete(id);
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
session.seen = at;
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
revoke(id) {
|
|
50
|
+
if (id)
|
|
51
|
+
this.sessions.delete(id);
|
|
52
|
+
}
|
|
53
|
+
get size() {
|
|
54
|
+
return this.sessions.size;
|
|
55
|
+
}
|
|
56
|
+
/** Drops idle sessions so a long-lived process does not accumulate them. */
|
|
57
|
+
prune() {
|
|
58
|
+
const at = this.now();
|
|
59
|
+
for (const [id, session] of this.sessions) {
|
|
60
|
+
if (at - session.seen > this.idleMs || at - session.created > this.absoluteMs)
|
|
61
|
+
this.sessions.delete(id);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Failed token guesses are throttled per address: the token is the only thing between the page and the file. */
|
|
66
|
+
export class FailureLimiter {
|
|
67
|
+
limit;
|
|
68
|
+
banMs;
|
|
69
|
+
now;
|
|
70
|
+
hits = new Map();
|
|
71
|
+
constructor(limit = 10, banMs = 5 * 60_000, now = () => Date.now()) {
|
|
72
|
+
this.limit = limit;
|
|
73
|
+
this.banMs = banMs;
|
|
74
|
+
this.now = now;
|
|
75
|
+
}
|
|
76
|
+
blocked(ip) {
|
|
77
|
+
const entry = this.hits.get(ip);
|
|
78
|
+
if (!entry)
|
|
79
|
+
return false;
|
|
80
|
+
if (entry.until > this.now())
|
|
81
|
+
return true;
|
|
82
|
+
if (entry.until !== 0)
|
|
83
|
+
this.hits.delete(ip);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
fail(ip) {
|
|
87
|
+
const entry = this.hits.get(ip) ?? { count: 0, until: 0 };
|
|
88
|
+
entry.count += 1;
|
|
89
|
+
if (entry.count >= this.limit)
|
|
90
|
+
entry.until = this.now() + this.banMs;
|
|
91
|
+
this.hits.set(ip, entry);
|
|
92
|
+
}
|
|
93
|
+
clear(ip) {
|
|
94
|
+
this.hits.delete(ip);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export function cookieValue(header, name) {
|
|
98
|
+
if (!header)
|
|
99
|
+
return undefined;
|
|
100
|
+
for (const part of header.split(';')) {
|
|
101
|
+
const index = part.indexOf('=');
|
|
102
|
+
if (index < 0)
|
|
103
|
+
continue;
|
|
104
|
+
if (part.slice(0, index).trim() === name)
|
|
105
|
+
return part.slice(index + 1).trim();
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
export function sessionCookie(id, maxAgeSeconds) {
|
|
110
|
+
return `${SESSION_COOKIE}=${id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}`;
|
|
111
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AccessMode, BackendDefinition, ConfigIssue, SearchConfig } from '@nite07/search-core';
|
|
2
|
+
/** One credential row: never the value, only where it came from and how long it is. */
|
|
3
|
+
export interface CredentialState {
|
|
4
|
+
id: string;
|
|
5
|
+
ref: string;
|
|
6
|
+
mode: AccessMode | null;
|
|
7
|
+
source: 'env' | 'file' | 'none';
|
|
8
|
+
length: number;
|
|
9
|
+
}
|
|
10
|
+
export interface SettingsSnapshot {
|
|
11
|
+
configPath: string;
|
|
12
|
+
revision: string;
|
|
13
|
+
config: SearchConfig;
|
|
14
|
+
defaults: SearchConfig;
|
|
15
|
+
catalog: BackendDefinition[];
|
|
16
|
+
credentials: CredentialState[];
|
|
17
|
+
browser: CredentialState;
|
|
18
|
+
compactByDefault: boolean;
|
|
19
|
+
/** The container copy a save also refreshes, when one exists beside the file. */
|
|
20
|
+
companion: {
|
|
21
|
+
path: string;
|
|
22
|
+
active: boolean;
|
|
23
|
+
};
|
|
24
|
+
/** Set when the file on disk does not validate; the page then opens on defaults so it can be repaired. */
|
|
25
|
+
loadError?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface SaveResult {
|
|
28
|
+
revision: string;
|
|
29
|
+
backup?: string;
|
|
30
|
+
}
|
|
31
|
+
export declare class SettingsError extends Error {
|
|
32
|
+
readonly issues: ConfigIssue[];
|
|
33
|
+
readonly status: number;
|
|
34
|
+
constructor(message: string, issues?: ConfigIssue[], status?: number);
|
|
35
|
+
}
|
|
36
|
+
export declare const MAX_CREDENTIAL_LENGTH = 16384;
|
|
37
|
+
/** Inside a container, loopback is the container itself, so a companion file names the host instead. */
|
|
38
|
+
export declare const CONTAINER_HOST = "host.containers.internal";
|
|
39
|
+
/** The same settings for a client that runs in a container: loopback there means the container. */
|
|
40
|
+
export declare const companionPath: (path: string) => string;
|
|
41
|
+
export declare function containerVariant(search: SearchConfig, home?: string): SearchConfig;
|
|
42
|
+
export declare function snapshot(path: string, env?: NodeJS.ProcessEnv): Promise<SettingsSnapshot>;
|
|
43
|
+
export interface SaveInput {
|
|
44
|
+
config: unknown;
|
|
45
|
+
compactByDefault?: boolean;
|
|
46
|
+
expectedRevision?: string;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Validates first and writes second: a rejected save leaves the file byte-identical, which is what
|
|
50
|
+
* lets the page show the issues without having damaged a working configuration.
|
|
51
|
+
*/
|
|
52
|
+
export declare function saveConfig(path: string, input: SaveInput): Promise<SaveResult>;
|
|
53
|
+
export interface CredentialInput {
|
|
54
|
+
scope: 'backend' | 'browser';
|
|
55
|
+
id?: string;
|
|
56
|
+
value?: string;
|
|
57
|
+
remove?: boolean;
|
|
58
|
+
}
|
|
59
|
+
export declare function saveCredential(path: string, input: CredentialInput): Promise<{
|
|
60
|
+
revision: string;
|
|
61
|
+
state: CredentialState;
|
|
62
|
+
}>;
|