scalix 1.5.1 → 1.6.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/.env.example +5 -3
- package/CHANGELOG.md +40 -0
- package/LICENSE +0 -1
- package/README.md +91 -3
- package/dist/agent-presets.js +33 -0
- package/dist/agent.js +372 -43
- package/dist/api-client.js +64 -5
- package/dist/board-context.js +81 -0
- package/dist/browser-access.js +0 -0
- package/dist/cli.js +397 -45
- package/dist/cloud.js +1 -1
- package/dist/command-sandbox.js +146 -0
- package/dist/commands.js +18 -6
- package/dist/config.js +44 -5
- package/dist/constants.js +90 -11
- package/dist/context-builder.js +9 -1
- package/dist/cost-tracker.js +1 -1
- package/dist/feedback.js +51 -0
- package/dist/headless.js +43 -9
- package/dist/ipc-server.js +371 -110
- package/dist/keychain.js +34 -9
- package/dist/marketplace.js +400 -0
- package/dist/mcp.js +498 -29
- package/dist/openrouter-oauth.js +149 -0
- package/dist/project-index.js +46 -23
- package/dist/providers/index.js +21 -4
- package/dist/sandbox.js +115 -27
- package/dist/secure-fetch.js +117 -0
- package/dist/sessions.js +12 -0
- package/dist/settings.js +193 -44
- package/dist/slash-commands.js +8 -0
- package/dist/sub-agent.js +6 -2
- package/dist/tools-browser.js +95 -18
- package/dist/tools-extra.js +101 -7
- package/dist/tools-memory.js +74 -0
- package/dist/tools-web.js +92 -28
- package/dist/tools.js +99 -23
- package/dist/workspace-trust.js +11 -1
- package/dist/worktree.js +24 -5
- package/package.json +5 -3
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter OAuth PKCE ("Connect OpenRouter") for the /setup wizard.
|
|
3
|
+
*
|
|
4
|
+
* Flow (https://openrouter.ai/docs/guides/overview/auth/oauth):
|
|
5
|
+
* 1. Generate a PKCE pair (S256: challenge = base64url(sha256(verifier))).
|
|
6
|
+
* 2. Open `https://openrouter.ai/auth?callback_url=http://127.0.0.1:<port>&code_challenge=<challenge>&code_challenge_method=S256`.
|
|
7
|
+
* OpenRouter allows ANY localhost/loopback callback port — we bind port 0
|
|
8
|
+
* and let the OS pick, so parallel wizards never collide.
|
|
9
|
+
* 3. After approval the browser hits the loopback server with `?code=...`
|
|
10
|
+
* (or `?error=...` on rejection).
|
|
11
|
+
* 4. Exchange at POST /api/v1/auth/keys { code, code_verifier } → data.key
|
|
12
|
+
* (an sk-or-v1-... key scoped to the USER's own OpenRouter account and
|
|
13
|
+
* billing — zero inference cost for Scalix).
|
|
14
|
+
*
|
|
15
|
+
* Headless / SSH fallback: OpenRouter also shows a single-use, 10-minute code
|
|
16
|
+
* directly in the browser; the wizard accepts that code pasted manually and
|
|
17
|
+
* runs the same exchange.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
20
|
+
import http from 'node:http';
|
|
21
|
+
const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
|
|
22
|
+
const OPENROUTER_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
|
|
23
|
+
function b64url(buf) {
|
|
24
|
+
return buf.toString('base64url');
|
|
25
|
+
}
|
|
26
|
+
export function generatePkcePair(randomSource) {
|
|
27
|
+
const rand = randomSource ?? ((n) => randomBytes(n));
|
|
28
|
+
// RFC 7636: verifier is 43-128 chars of unreserved characters. 32 raw bytes
|
|
29
|
+
// → 43 base64url chars, all from the unreserved set by construction.
|
|
30
|
+
const verifier = b64url(rand(32));
|
|
31
|
+
if (verifier.length < 43 || verifier.length > 128) {
|
|
32
|
+
throw new Error('PKCE verifier length out of RFC 7636 range');
|
|
33
|
+
}
|
|
34
|
+
const challenge = b64url(createHash('sha256').update(verifier).digest());
|
|
35
|
+
return { verifier, challenge };
|
|
36
|
+
}
|
|
37
|
+
export function buildAuthUrl(callbackOrigin, pair) {
|
|
38
|
+
const u = new URL(OPENROUTER_AUTH_URL);
|
|
39
|
+
u.searchParams.set('callback_url', callbackOrigin);
|
|
40
|
+
u.searchParams.set('code_challenge', pair.challenge);
|
|
41
|
+
u.searchParams.set('code_challenge_method', 'S256');
|
|
42
|
+
return u.toString();
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Bind a one-shot loopback HTTP server and wait for OpenRouter's redirect.
|
|
46
|
+
*
|
|
47
|
+
* Every path is accepted (providers sometimes append path segments under the
|
|
48
|
+
* callback origin); only the query matters. Responds with a tiny HTML page so
|
|
49
|
+
* the browser tab doesn't hang on a blank error.
|
|
50
|
+
*/
|
|
51
|
+
export function startLoopbackCallback(timeoutMs = 5 * 60_000) {
|
|
52
|
+
return new Promise((resolveBind, rejectBind) => {
|
|
53
|
+
let settled = false;
|
|
54
|
+
let resolveCode;
|
|
55
|
+
let rejectCode;
|
|
56
|
+
const codePromise = new Promise((res, rej) => {
|
|
57
|
+
resolveCode = res;
|
|
58
|
+
rejectCode = rej;
|
|
59
|
+
});
|
|
60
|
+
const server = http.createServer((req, res) => {
|
|
61
|
+
const u = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
62
|
+
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
63
|
+
const err = u.searchParams.get('error');
|
|
64
|
+
if (err) {
|
|
65
|
+
res.end('<html><body><h3>OpenRouter connection was not completed.</h3>You can close this tab and retry in the terminal.</body></html>');
|
|
66
|
+
settled = true;
|
|
67
|
+
rejectCode(new Error(`OpenRouter returned an error: ${err}`));
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
const code = u.searchParams.get('code') ?? '';
|
|
71
|
+
res.end('<html><body><h3>Scalix Coder connected.</h3>You can close this tab and return to the terminal.</body></html>');
|
|
72
|
+
settled = true;
|
|
73
|
+
if (code)
|
|
74
|
+
resolveCode(code);
|
|
75
|
+
else
|
|
76
|
+
rejectCode(new Error('Callback reached without an authorization code'));
|
|
77
|
+
}
|
|
78
|
+
// One-shot: stop accepting after the first callback either way.
|
|
79
|
+
server.close(() => { });
|
|
80
|
+
});
|
|
81
|
+
server.on('error', (err) => {
|
|
82
|
+
if (!settled)
|
|
83
|
+
rejectBind(err instanceof Error ? err : new Error(String(err)));
|
|
84
|
+
});
|
|
85
|
+
server.listen(0, '127.0.0.1', () => {
|
|
86
|
+
const addr = server.address();
|
|
87
|
+
const url = `http://127.0.0.1:${addr.port}`;
|
|
88
|
+
const timer = setTimeout(() => {
|
|
89
|
+
settled = true;
|
|
90
|
+
rejectCode(new Error('Timed out waiting for the OpenRouter callback'));
|
|
91
|
+
server.close(() => { });
|
|
92
|
+
}, timeoutMs);
|
|
93
|
+
codePromise.finally(() => clearTimeout(timer)).catch(() => { });
|
|
94
|
+
resolveBind({
|
|
95
|
+
url,
|
|
96
|
+
code: codePromise,
|
|
97
|
+
close() {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
server.close(() => { });
|
|
100
|
+
// Unblock a wizard abandoned mid-flow.
|
|
101
|
+
if (!settled)
|
|
102
|
+
rejectCode(new Error('Cancelled'));
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Exchange the authorization code for a user-scoped API key.
|
|
110
|
+
* Shape per docs: { key: "sk-or-v1-..." } nested under `data`.
|
|
111
|
+
*/
|
|
112
|
+
export async function exchangeCodeForKey(code, verifier, fetchImpl = fetch) {
|
|
113
|
+
const resp = await fetchImpl(OPENROUTER_EXCHANGE_URL, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: { 'Content-Type': 'application/json' },
|
|
116
|
+
body: JSON.stringify({ code, code_verifier: verifier }),
|
|
117
|
+
});
|
|
118
|
+
if (!resp.ok) {
|
|
119
|
+
const detail = await resp.text().catch(() => '');
|
|
120
|
+
throw new Error(`OpenRouter key exchange failed (${resp.status})${detail ? `: ${detail.slice(0, 200)}` : ''}`);
|
|
121
|
+
}
|
|
122
|
+
const body = (await resp.json());
|
|
123
|
+
const key = body.key ?? body.data?.key;
|
|
124
|
+
if (!key || typeof key !== 'string') {
|
|
125
|
+
throw new Error('OpenRouter key exchange returned no key');
|
|
126
|
+
}
|
|
127
|
+
return key;
|
|
128
|
+
}
|
|
129
|
+
/** Best-effort browser open across platforms; resolves false when nothing worked. */
|
|
130
|
+
export async function openInBrowser(url) {
|
|
131
|
+
const { execFile } = await import('node:child_process');
|
|
132
|
+
const platform = process.platform;
|
|
133
|
+
try {
|
|
134
|
+
if (platform === 'darwin') {
|
|
135
|
+
execFile('open', [url]);
|
|
136
|
+
}
|
|
137
|
+
else if (platform === 'win32') {
|
|
138
|
+
// 'start' is a cmd builtin, not an executable — must go through cmd.
|
|
139
|
+
execFile('cmd', ['/c', 'start', '', url]);
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
execFile('xdg-open', [url]);
|
|
143
|
+
}
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
package/dist/project-index.js
CHANGED
|
@@ -205,42 +205,65 @@ async function extractSymbols(filePath, relativePath) {
|
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
207
|
// Import patterns for dependency tracking
|
|
208
|
-
const
|
|
209
|
-
// JS/TS: import { x } from './y' or import x from './y' or require('./y')
|
|
210
|
-
{ ext: new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']),
|
|
211
|
-
pattern: /(?:import\s+(?:{([^}]+)}\s+from\s+|(\w+)\s+from\s+)?['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g },
|
|
212
|
-
// Python: from x import y or import x
|
|
213
|
-
{ ext: new Set(['.py']),
|
|
214
|
-
pattern: /(?:from\s+([\w.]+)\s+import\s+([\w,\s*]+)|import\s+([\w.]+))/g },
|
|
215
|
-
// Go: import "x" or import ( "x" )
|
|
216
|
-
{ ext: new Set(['.go']),
|
|
217
|
-
pattern: /import\s+(?:(?:\w+\s+)?"([^"]+)"|[\s\S]*?"([^"]+)")/g },
|
|
218
|
-
// Rust: use x::y
|
|
219
|
-
{ ext: new Set(['.rs']),
|
|
220
|
-
pattern: /use\s+([\w:]+(?:::\{[^}]+\})?)/g },
|
|
221
|
-
];
|
|
208
|
+
const JS_TS_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']);
|
|
222
209
|
function extractImports(content, relativePath, ext) {
|
|
223
210
|
const imports = [];
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const regex = new RegExp(pattern.source, pattern.flags);
|
|
211
|
+
if (JS_TS_EXTS.has(ext)) {
|
|
212
|
+
// Matches: import ... from '...'; import '...'; export ... from '...'; require('...')
|
|
213
|
+
const jsPattern = /(?:(?:import|export)\s+(?:type\s+)?(?:(?:\*\s+as\s+\w+|{([\s\S]*?)}|[\w\s,]+)\s+from\s+)?['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g;
|
|
228
214
|
let match;
|
|
229
|
-
while ((match =
|
|
230
|
-
const modulePath = match[
|
|
215
|
+
while ((match = jsPattern.exec(content)) !== null) {
|
|
216
|
+
const modulePath = match[2] || match[3] || '';
|
|
231
217
|
if (!modulePath)
|
|
232
218
|
continue;
|
|
233
|
-
// Only track local imports (starting with . or relative paths)
|
|
234
219
|
const isLocal = modulePath.startsWith('.') || modulePath.startsWith('/');
|
|
235
220
|
if (!isLocal)
|
|
236
221
|
continue;
|
|
237
|
-
const
|
|
222
|
+
const symbolsRaw = match[1] || '';
|
|
223
|
+
const symbols = symbolsRaw
|
|
224
|
+
? symbolsRaw.split(',').map((s) => s.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim()).filter(Boolean)
|
|
225
|
+
: [];
|
|
238
226
|
imports.push({
|
|
239
227
|
from: relativePath,
|
|
240
228
|
to: modulePath,
|
|
241
|
-
symbols
|
|
229
|
+
symbols,
|
|
242
230
|
});
|
|
243
231
|
}
|
|
232
|
+
return imports;
|
|
233
|
+
}
|
|
234
|
+
if (ext === '.py') {
|
|
235
|
+
const pyPattern = /(?:from\s+([\w.]+)\s+import\s+([\w,\s*]+)|import\s+([\w.]+))/g;
|
|
236
|
+
let match;
|
|
237
|
+
while ((match = pyPattern.exec(content)) !== null) {
|
|
238
|
+
const modulePath = match[1] || match[3] || '';
|
|
239
|
+
if (!modulePath || !modulePath.startsWith('.'))
|
|
240
|
+
continue;
|
|
241
|
+
const symbols = (match[2] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
242
|
+
imports.push({ from: relativePath, to: modulePath, symbols });
|
|
243
|
+
}
|
|
244
|
+
return imports;
|
|
245
|
+
}
|
|
246
|
+
if (ext === '.go') {
|
|
247
|
+
const goPattern = /import\s+(?:(?:\w+\s+)?"([^"]+)"|[\s\S]*?"([^"]+)")/g;
|
|
248
|
+
let match;
|
|
249
|
+
while ((match = goPattern.exec(content)) !== null) {
|
|
250
|
+
const modulePath = match[1] || match[2] || '';
|
|
251
|
+
if (!modulePath || (!modulePath.startsWith('.') && !modulePath.startsWith('/')))
|
|
252
|
+
continue;
|
|
253
|
+
imports.push({ from: relativePath, to: modulePath, symbols: [] });
|
|
254
|
+
}
|
|
255
|
+
return imports;
|
|
256
|
+
}
|
|
257
|
+
if (ext === '.rs') {
|
|
258
|
+
const rsPattern = /use\s+((?:crate|super|self)::[\w:]+(?:::\{[^}]+\})?)/g;
|
|
259
|
+
let match;
|
|
260
|
+
while ((match = rsPattern.exec(content)) !== null) {
|
|
261
|
+
const modulePath = match[1] || '';
|
|
262
|
+
if (!modulePath)
|
|
263
|
+
continue;
|
|
264
|
+
imports.push({ from: relativePath, to: modulePath, symbols: [] });
|
|
265
|
+
}
|
|
266
|
+
return imports;
|
|
244
267
|
}
|
|
245
268
|
return imports;
|
|
246
269
|
}
|
package/dist/providers/index.js
CHANGED
|
@@ -4,26 +4,43 @@
|
|
|
4
4
|
// user's own endpoint + key (no hardcoded third-party defaults anywhere).
|
|
5
5
|
// The agent consumes a client (ScalixClient-shaped) plus a capability set that
|
|
6
6
|
// scopes the Scalix-platform workarounds to the scalix provider only.
|
|
7
|
+
//
|
|
8
|
+
// A provider KEY (e.g. `scalix`, `openai`, `novita`, `local-ollama`) names a
|
|
9
|
+
// configured registry entry; an ADAPTER (`scalix` | `openai`) picks the wire
|
|
10
|
+
// dialect and, with it, the capability set. Every non-scalix key speaks the
|
|
11
|
+
// OpenAI-compatible wire, so new BYOK providers need no code — only config.
|
|
7
12
|
import { ScalixClient } from '../api-client.js';
|
|
8
13
|
import { OpenAICompatClient } from './openai.js';
|
|
14
|
+
/** Built-in provider keys. Any other key is a user-defined BYOK provider. */
|
|
9
15
|
export const PROVIDER_IDS = ['scalix', 'openai'];
|
|
16
|
+
const PROVIDER_KEY_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
|
17
|
+
/** A syntactically usable provider key. Unknown keys are allowed on purpose:
|
|
18
|
+
* the registry (config.providers) is the source of truth for what exists. */
|
|
10
19
|
export function isProviderId(v) {
|
|
20
|
+
return typeof v === 'string' && PROVIDER_KEY_RE.test(v);
|
|
21
|
+
}
|
|
22
|
+
export function isBuiltInProviderId(v) {
|
|
11
23
|
return typeof v === 'string' && PROVIDER_IDS.includes(v);
|
|
12
24
|
}
|
|
25
|
+
/** Resolve the wire dialect for a provider key. Scalix is the only special
|
|
26
|
+
* case; everything else is OpenAI-compatible. */
|
|
27
|
+
export function adapterFor(provider) {
|
|
28
|
+
return provider === 'scalix' ? 'scalix' : 'openai';
|
|
29
|
+
}
|
|
13
30
|
const CAPABILITIES = {
|
|
14
31
|
scalix: { streamingToolCalls: false, maxTokensPolicy: 'clamped', platformTools: true },
|
|
15
32
|
openai: { streamingToolCalls: true, maxTokensPolicy: 'explicit-only', platformTools: false },
|
|
16
33
|
};
|
|
17
34
|
export function capabilitiesFor(provider) {
|
|
18
|
-
return CAPABILITIES[provider];
|
|
35
|
+
return CAPABILITIES[adapterFor(provider)];
|
|
19
36
|
}
|
|
20
37
|
/** Build the chat client for a provider. baseUrl semantics differ:
|
|
21
38
|
* - scalix: API host root (gateway nests /v1/ai) — DEFAULT_BASE_URL applies upstream;
|
|
22
|
-
* - openai: the endpoint root of any OpenAI-compatible server, with
|
|
23
|
-
* without its /v1 suffix (api.openai.com/v1, openrouter.ai/api/v1,
|
|
39
|
+
* - openai-compatible: the endpoint root of any OpenAI-compatible server, with
|
|
40
|
+
* or without its /v1 suffix (api.openai.com/v1, openrouter.ai/api/v1,
|
|
24
41
|
* localhost:11434, ...). Required — there is no default third-party URL. */
|
|
25
42
|
export function createChatClient(provider, baseUrl, apiKey) {
|
|
26
|
-
if (provider === 'openai') {
|
|
43
|
+
if (adapterFor(provider) === 'openai') {
|
|
27
44
|
return new OpenAICompatClient(baseUrl, apiKey);
|
|
28
45
|
}
|
|
29
46
|
return new ScalixClient(baseUrl, apiKey);
|
package/dist/sandbox.js
CHANGED
|
@@ -15,8 +15,15 @@ function normalizeSep(p) {
|
|
|
15
15
|
return process.platform === 'win32' ? p.replace(/\//g, '\\') : p;
|
|
16
16
|
}
|
|
17
17
|
export function isWithinRoot(p, root) {
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
// Case-fold only where the filesystem does. Folding on Linux made
|
|
19
|
+
// `/srv/Secret/x` test as inside `/srv/secret` — two genuinely different
|
|
20
|
+
// directories — which is an escape, not a convenience. macOS is usually
|
|
21
|
+
// case-insensitive but can be formatted otherwise; comparing exactly there
|
|
22
|
+
// can only reject a path that is really inside the root, which fails closed,
|
|
23
|
+
// and callers realpath first so the on-disk casing already agrees.
|
|
24
|
+
const fold = (s) => (IS_WINDOWS ? s.toLowerCase() : s);
|
|
25
|
+
const np = fold(normalizeSep(p));
|
|
26
|
+
const nr = fold(normalizeSep(root));
|
|
20
27
|
return np === nr || np.startsWith(nr + path.sep);
|
|
21
28
|
}
|
|
22
29
|
// Resolve symlinks on the longest existing prefix of `resolved` synchronously.
|
|
@@ -83,24 +90,44 @@ export function sandboxPath(filePath) {
|
|
|
83
90
|
}
|
|
84
91
|
return real;
|
|
85
92
|
}
|
|
93
|
+
// Async twin of realpathLongestExistingPrefix.
|
|
94
|
+
async function realpathLongestExistingPrefixAsync(resolved) {
|
|
95
|
+
let existing = resolved;
|
|
96
|
+
const remainder = [];
|
|
97
|
+
while (true) {
|
|
98
|
+
try {
|
|
99
|
+
// fs/promises has no realpath.native, so strip the prefix defensively.
|
|
100
|
+
const real = stripExtendedLengthPrefix(await fs.realpath(existing));
|
|
101
|
+
return remainder.length > 0 ? path.join(real, ...remainder) : real;
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
if (err.code !== 'ENOENT')
|
|
105
|
+
throw err;
|
|
106
|
+
const parent = path.dirname(existing);
|
|
107
|
+
if (parent === existing)
|
|
108
|
+
return resolved;
|
|
109
|
+
remainder.unshift(path.basename(existing));
|
|
110
|
+
existing = parent;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
86
114
|
export async function sandboxPathAsync(filePath) {
|
|
87
115
|
const root = getSandboxRoot();
|
|
88
116
|
const resolved = path.resolve(root, filePath);
|
|
89
117
|
if (!isWithinRoot(resolved, root)) {
|
|
90
118
|
throw new Error(`Path traversal blocked: "${filePath}" resolves outside working directory`);
|
|
91
119
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
return resolved;
|
|
102
|
-
throw err;
|
|
120
|
+
// The path usually does NOT exist yet — every write of a new file lands here.
|
|
121
|
+
// Returning `resolved` unchecked on ENOENT was the hole: only the leaf has to
|
|
122
|
+
// be missing for the check to be skipped, so `<root>/link/new.txt`, where
|
|
123
|
+
// `link` is a symlink to /etc, wrote straight out of the sandbox. Resolve the
|
|
124
|
+
// longest ancestor that does exist and verify containment on that, exactly as
|
|
125
|
+
// the sync path already does.
|
|
126
|
+
const real = await realpathLongestExistingPrefixAsync(resolved);
|
|
127
|
+
if (!isWithinRoot(real, realSandboxRoot(root))) {
|
|
128
|
+
throw new Error(`Symlink traversal blocked: "${filePath}" resolves to "${real}" outside working directory`);
|
|
103
129
|
}
|
|
130
|
+
return real;
|
|
104
131
|
}
|
|
105
132
|
let _scopedRules = [];
|
|
106
133
|
export function setScopedPermissionRules(rules) {
|
|
@@ -115,6 +142,12 @@ function parseScopedToolSpec(spec) {
|
|
|
115
142
|
return { tool: match[1], prefix: match[2].replace(/\*$/, '') };
|
|
116
143
|
return { tool: spec };
|
|
117
144
|
}
|
|
145
|
+
// A prefix rule describes the command it names, not everything that can be
|
|
146
|
+
// stapled onto it. `run_command(git *)` was matching `git status; curl x | sh`
|
|
147
|
+
// with a plain startsWith, so one allow rule for a read-only command handed
|
|
148
|
+
// over arbitrary execution. Anything here means the text after the prefix is no
|
|
149
|
+
// longer the command the rule was written about.
|
|
150
|
+
const SHELL_CHAINING_RE = /[;&|<>\n\r`]|\$\(/;
|
|
118
151
|
export function checkScopedPermission(toolName, args) {
|
|
119
152
|
if (_scopedRules.length === 0)
|
|
120
153
|
return null;
|
|
@@ -125,17 +158,40 @@ export function checkScopedPermission(toolName, args) {
|
|
|
125
158
|
continue;
|
|
126
159
|
if (parsed.tool !== toolName)
|
|
127
160
|
continue;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if
|
|
131
|
-
|
|
161
|
+
const deny = rule.action === 'deny';
|
|
162
|
+
// deny is an OR over its conditions, allow is an AND. Both directions round
|
|
163
|
+
// toward refusing: a deny rule fires if anything it names matches, and an
|
|
164
|
+
// allow rule fires only if everything it names matches. Previously both
|
|
165
|
+
// were an OR that `prefix`-less rules short-circuited past entirely, so
|
|
166
|
+
// `{tool:'run_command', regex:'^git status$', action:'allow'}` allowed
|
|
167
|
+
// every command the tool could run — the regex was never consulted.
|
|
168
|
+
let prefixHit = null;
|
|
169
|
+
if (parsed.prefix) {
|
|
170
|
+
prefixHit = !!argStr && argStr.startsWith(parsed.prefix);
|
|
171
|
+
// Only allow rules need the chaining check; a deny that matched should
|
|
172
|
+
// keep matching however the command continues.
|
|
173
|
+
if (prefixHit && !deny && toolName === 'run_command'
|
|
174
|
+
&& SHELL_CHAINING_RE.test(argStr.slice(parsed.prefix.length))) {
|
|
175
|
+
prefixHit = false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
let regexHit = null;
|
|
132
179
|
if (rule.regex) {
|
|
133
180
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
181
|
+
regexHit = new RegExp(rule.regex).test(argStr || '');
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
// An unparseable pattern is a config error. Honouring it as a match on
|
|
185
|
+
// a deny rule over-blocks; ignoring it on an allow rule under-permits.
|
|
186
|
+
regexHit = deny;
|
|
136
187
|
}
|
|
137
|
-
catch { }
|
|
138
188
|
}
|
|
189
|
+
const conditions = [prefixHit, regexHit].filter((c) => c !== null);
|
|
190
|
+
const matched = conditions.length === 0
|
|
191
|
+
? true // bare `run_command` — the whole tool
|
|
192
|
+
: deny ? conditions.some(Boolean) : conditions.every(Boolean);
|
|
193
|
+
if (matched)
|
|
194
|
+
return rule.action;
|
|
139
195
|
}
|
|
140
196
|
return null;
|
|
141
197
|
}
|
|
@@ -264,11 +320,16 @@ export function getToolPermission(toolName, mode) {
|
|
|
264
320
|
}
|
|
265
321
|
export function getToolPermissionWithArgs(toolName, mode, args) {
|
|
266
322
|
const scoped = checkScopedPermission(toolName, args);
|
|
267
|
-
if (scoped === 'allow')
|
|
268
|
-
return 'allow';
|
|
269
323
|
if (scoped === 'deny')
|
|
270
324
|
return 'block';
|
|
271
|
-
|
|
325
|
+
const base = getToolPermission(toolName, mode);
|
|
326
|
+
// A scoped allow skips the confirmation prompt; it does not widen the mode.
|
|
327
|
+
// Returning 'allow' unconditionally let a saved `run_command(...)` rule run
|
|
328
|
+
// commands in plan mode — the one mode whose entire promise is that nothing
|
|
329
|
+
// executes. Rules earn 'ask' → 'allow', never 'block' → 'allow'.
|
|
330
|
+
if (scoped === 'allow')
|
|
331
|
+
return base === 'block' ? 'block' : 'allow';
|
|
332
|
+
return base;
|
|
272
333
|
}
|
|
273
334
|
export function isDangerousTool(toolName) {
|
|
274
335
|
const sets = getEffectiveToolSets();
|
|
@@ -409,15 +470,43 @@ const POWERSHELL_BLOCKLIST = [
|
|
|
409
470
|
/New-LocalUser\b/i,
|
|
410
471
|
/Add-LocalGroupMember\b.*Administrators/i,
|
|
411
472
|
];
|
|
473
|
+
// The Unix patterns above were written without /i, so `RM -RF /` and `Shutdown`
|
|
474
|
+
// walked past them — and on macOS and Windows, where the filesystem is
|
|
475
|
+
// case-insensitive, those spellings run exactly like the lower-case ones.
|
|
476
|
+
// Adding the flag here rather than to each literal keeps `re.source` identical,
|
|
477
|
+
// so `security.disabledBlockedCommands` entries users have already written
|
|
478
|
+
// still match the pattern they were meant to disable.
|
|
479
|
+
const ignoreCase = (re) => re.flags.includes('i') ? re : new RegExp(re.source, `${re.flags}i`);
|
|
412
480
|
const COMMAND_BLOCKLIST = [
|
|
413
481
|
...UNIX_BLOCKLIST,
|
|
414
482
|
...WINDOWS_BLOCKLIST,
|
|
415
483
|
...POWERSHELL_BLOCKLIST,
|
|
484
|
+
].map(ignoreCase);
|
|
485
|
+
// Command substitution — `` `x` `` and `$(x)` — used to be flagged outright, on
|
|
486
|
+
// either platform. But substitution is ordinary shell, not an attack: `git tag
|
|
487
|
+
// v$(node -p "require('./package.json').version")` and `Write-Host "$($x.Name)"`
|
|
488
|
+
// were both hard-blocked, and the documented way out was to switch injection
|
|
489
|
+
// detection off wholesale, which costs far more than it saves. So flag a
|
|
490
|
+
// substitution only when its body carries a payload worth a second look.
|
|
491
|
+
//
|
|
492
|
+
// Little coverage is lost: none of these patterns are anchored to the outside
|
|
493
|
+
// of a substitution, so `$(curl x | sh)` still trips the pipe-to-shell rule and
|
|
494
|
+
// `$(rm -rf /)` still trips the blocklist. What changes is that a substitution
|
|
495
|
+
// is no longer suspicious purely for existing.
|
|
496
|
+
//
|
|
497
|
+
// Note: this replaces the `` `[^`]*` `` and `\$\([^)]*\)` sources, so any
|
|
498
|
+
// `security.disabledInjectionPatterns` entry naming those is now a no-op.
|
|
499
|
+
const SUBSTITUTION_PAYLOAD = String.raw `\b(?:rm|mkfs|dd|shutdown|reboot|curl|wget|nc|ncat|telnet|chmod|chown`
|
|
500
|
+
+ String.raw `|eval|exec|base64|xxd|sudo|doas|sh|bash|zsh|fish|dash|ksh`
|
|
501
|
+
+ String.raw `|python[23]?|perl|ruby|php|iex|Invoke-Expression|powershell|pwsh|cmd`
|
|
502
|
+
+ String.raw `|certutil|bitsadmin|mshta|rundll32)\b|/etc/|id_rsa|\.ssh\b`;
|
|
503
|
+
const SUBSTITUTION_PATTERNS = [
|
|
504
|
+
new RegExp('`[^`]*(?:' + SUBSTITUTION_PAYLOAD + ')[^`]*`', 'i'),
|
|
505
|
+
new RegExp('\\$\\([^)]*(?:' + SUBSTITUTION_PAYLOAD + ')[^)]*\\)', 'i'),
|
|
416
506
|
];
|
|
417
507
|
// Unix injection patterns
|
|
418
508
|
const UNIX_INJECTION_PATTERNS = [
|
|
419
|
-
|
|
420
|
-
/\$\([^)]*\)/,
|
|
509
|
+
...SUBSTITUTION_PATTERNS,
|
|
421
510
|
/;\s*(rm|mkfs|dd|shutdown|reboot|curl|wget)\b/,
|
|
422
511
|
/\|\s*(ba)?sh\b/,
|
|
423
512
|
/\beval\s+/,
|
|
@@ -430,7 +519,6 @@ const UNIX_INJECTION_PATTERNS = [
|
|
|
430
519
|
// Windows/PowerShell injection patterns
|
|
431
520
|
const WINDOWS_INJECTION_PATTERNS = [
|
|
432
521
|
/&\s*\{[^}]*\}/,
|
|
433
|
-
/\$\([^)]*\)/,
|
|
434
522
|
/;\s*(del|rd|rmdir|format|diskpart|net\s+user|reg\s+delete)\b/i,
|
|
435
523
|
/\|\s*powershell\b/i,
|
|
436
524
|
/\|\s*pwsh\b/i,
|
|
@@ -445,7 +533,7 @@ const WINDOWS_INJECTION_PATTERNS = [
|
|
|
445
533
|
const INJECTION_PATTERNS = [
|
|
446
534
|
...UNIX_INJECTION_PATTERNS,
|
|
447
535
|
...WINDOWS_INJECTION_PATTERNS,
|
|
448
|
-
];
|
|
536
|
+
].map(ignoreCase);
|
|
449
537
|
const SENSITIVE_ENV_PATTERNS = [
|
|
450
538
|
/API_KEY/i, /SECRET/i, /TOKEN/i, /PASSWORD/i, /CREDENTIAL/i, /AUTH/i, /PRIVATE/i,
|
|
451
539
|
// Broad substrings that commonly carry secrets or connection strings.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Connection-pinned fetch.
|
|
2
|
+
//
|
|
3
|
+
// The SSRF checks in tools-web.ts and mcp.ts resolve the hostname, decide the
|
|
4
|
+
// address is public, and then let fetch() resolve the name AGAIN on its own.
|
|
5
|
+
// Between the two lookups an attacker who controls DNS can flip the answer
|
|
6
|
+
// (DNS rebinding): the validation sees a public address, the connection lands
|
|
7
|
+
// on 127.0.0.1 / 169.254.169.254 / anything internal, with whatever
|
|
8
|
+
// Authorization header the caller attached. Validating and connecting are two
|
|
9
|
+
// different resolutions of the same name, so the check protects nothing.
|
|
10
|
+
//
|
|
11
|
+
// The fix is to make them the SAME resolution: resolve once, keep the
|
|
12
|
+
// addresses, and hand them to the connection as a pinned `lookup` so the
|
|
13
|
+
// socket can only ever reach an address that was actually validated.
|
|
14
|
+
//
|
|
15
|
+
// node:http/https are used rather than global fetch for exactly one reason —
|
|
16
|
+
// fetch (undici) exposes no way to pin DNS. The hostname is left untouched, so
|
|
17
|
+
// SNI, the Host header and the certificate's hostname check all still apply to
|
|
18
|
+
// the real name; only the address it dials is constrained.
|
|
19
|
+
import dns from 'node:dns';
|
|
20
|
+
import http from 'node:http';
|
|
21
|
+
import https from 'node:https';
|
|
22
|
+
import zlib from 'node:zlib';
|
|
23
|
+
import { Readable } from 'node:stream';
|
|
24
|
+
/**
|
|
25
|
+
* Resolve a hostname for pinning. Returns [] when the name cannot be resolved
|
|
26
|
+
* (or the caller deliberately skipped pinning) — the request then falls back
|
|
27
|
+
* to ordinary fetch, whose own failure is the honest outcome.
|
|
28
|
+
*/
|
|
29
|
+
export async function resolveLookupAddresses(hostname) {
|
|
30
|
+
try {
|
|
31
|
+
const addresses = await dns.promises.lookup(hostname, { all: true });
|
|
32
|
+
return addresses.length > 0 ? addresses : [];
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export function pinnedLookup(addresses) {
|
|
39
|
+
const list = addresses.map((a) => ({ address: a.address, family: a.family }));
|
|
40
|
+
return function lookup(_hostname, options, callback) {
|
|
41
|
+
if (options && options.all) {
|
|
42
|
+
callback(null, list);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
const first = list[0];
|
|
46
|
+
callback(null, first.address, first.family);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** Decode a compressed HTTP stream so callers see the same bytes fetch() would. */
|
|
51
|
+
function decodeBody(res) {
|
|
52
|
+
const encoding = res.headers['content-encoding'];
|
|
53
|
+
if (encoding === 'gzip')
|
|
54
|
+
return res.pipe(zlib.createGunzip());
|
|
55
|
+
if (encoding === 'deflate')
|
|
56
|
+
return res.pipe(zlib.createInflate());
|
|
57
|
+
if (encoding === 'br')
|
|
58
|
+
return res.pipe(zlib.createBrotliDecompress());
|
|
59
|
+
return res;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* fetch() with the connection pinned to pre-validated addresses.
|
|
63
|
+
*
|
|
64
|
+
* Drop-in for the call sites in tools-web.ts and mcp.ts: same RequestInit
|
|
65
|
+
* shape, same Response contract (streaming body included, so long-lived SSE
|
|
66
|
+
* responses such as MCP's keep working).
|
|
67
|
+
*/
|
|
68
|
+
export async function pinnedFetch(url, init, addresses) {
|
|
69
|
+
if (addresses.length === 0) {
|
|
70
|
+
// Nothing was validated to pin to; the caller decided this is allowed.
|
|
71
|
+
return fetch(url, init);
|
|
72
|
+
}
|
|
73
|
+
const transport = url.protocol === 'https:' ? https : http;
|
|
74
|
+
const headers = new Headers(init.headers);
|
|
75
|
+
const method = (init.method || 'GET').toUpperCase();
|
|
76
|
+
const body = init.body;
|
|
77
|
+
const nodeResponse = await new Promise((resolve, reject) => {
|
|
78
|
+
const request = transport.request(url, {
|
|
79
|
+
method,
|
|
80
|
+
// The whole point: dial only what we validated.
|
|
81
|
+
lookup: pinnedLookup(addresses),
|
|
82
|
+
// Fresh connection per request — a pooled socket is keyed by host:port
|
|
83
|
+
// and would carry no lookup of its own.
|
|
84
|
+
agent: false,
|
|
85
|
+
signal: init.signal ?? undefined,
|
|
86
|
+
headers: Object.fromEntries(headers.entries()),
|
|
87
|
+
}, resolve);
|
|
88
|
+
request.on('error', reject);
|
|
89
|
+
if (body !== undefined && body !== null) {
|
|
90
|
+
if (typeof body === 'string')
|
|
91
|
+
request.write(body);
|
|
92
|
+
else if (body instanceof Uint8Array)
|
|
93
|
+
request.write(body);
|
|
94
|
+
else if (body instanceof URLSearchParams)
|
|
95
|
+
request.write(body.toString());
|
|
96
|
+
else
|
|
97
|
+
reject(new Error(`pinnedFetch: unsupported request body type (${typeof body})`));
|
|
98
|
+
}
|
|
99
|
+
request.end();
|
|
100
|
+
});
|
|
101
|
+
const responseHeaders = new Headers();
|
|
102
|
+
for (const [key, value] of Object.entries(nodeResponse.headers)) {
|
|
103
|
+
if (value === undefined)
|
|
104
|
+
continue;
|
|
105
|
+
responseHeaders.set(key, Array.isArray(value) ? value.join(', ') : value);
|
|
106
|
+
}
|
|
107
|
+
// A decoded stream's length no longer matches the compressed original, and a
|
|
108
|
+
// stale content-length makes readers stop early.
|
|
109
|
+
const decoded = nodeResponse.headers['content-encoding'] !== undefined;
|
|
110
|
+
if (decoded)
|
|
111
|
+
responseHeaders.delete('content-length');
|
|
112
|
+
return new Response(Readable.toWeb(decodeBody(nodeResponse)), {
|
|
113
|
+
status: nodeResponse.statusCode ?? 502,
|
|
114
|
+
statusText: nodeResponse.statusMessage || '',
|
|
115
|
+
headers: responseHeaders,
|
|
116
|
+
});
|
|
117
|
+
}
|
package/dist/sessions.js
CHANGED
|
@@ -92,6 +92,18 @@ export async function listSessions() {
|
|
|
92
92
|
}
|
|
93
93
|
return sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
94
94
|
}
|
|
95
|
+
export async function renameSession(id, newName) {
|
|
96
|
+
const session = await loadSession(id);
|
|
97
|
+
const trimmed = newName.trim();
|
|
98
|
+
if (trimmed) {
|
|
99
|
+
session.meta.name = trimmed;
|
|
100
|
+
session.meta.updatedAt = new Date().toISOString();
|
|
101
|
+
}
|
|
102
|
+
const tmpPath = path.join(SESSIONS_DIR, `scalix-session-${id}-${Date.now()}-${randomUUID().slice(0, 8)}.tmp`);
|
|
103
|
+
await fs.writeFile(tmpPath, JSON.stringify(session, null, 2), { encoding: 'utf-8', mode: 0o600 });
|
|
104
|
+
await fs.rename(tmpPath, sessionPath(id));
|
|
105
|
+
return session.meta;
|
|
106
|
+
}
|
|
95
107
|
export async function deleteSession(id) {
|
|
96
108
|
try {
|
|
97
109
|
await fs.unlink(sessionPath(id));
|