alvin-bot 4.12.1 → 4.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +145 -0
- package/README.md +42 -5
- package/dist/handlers/async-agent-chunk-handler.js +17 -0
- package/dist/handlers/background-bypass.js +75 -0
- package/dist/handlers/message.js +127 -16
- package/dist/index.js +75 -3
- package/dist/providers/claude-sdk-provider.js +4 -1
- package/dist/services/allowed-users-gate.js +56 -0
- package/dist/services/async-agent-watcher.js +25 -0
- package/dist/services/cron.js +17 -0
- package/dist/services/exec-guard.js +26 -1
- package/dist/services/fallback-order.js +4 -1
- package/dist/services/file-permissions.js +93 -0
- package/dist/services/session-persistence.js +19 -2
- package/dist/services/session.js +2 -0
- package/dist/services/subagents.js +23 -5
- package/dist/services/timing-safe-bearer.js +51 -0
- package/dist/web/doctor-api.js +8 -2
- package/dist/web/server.js +7 -3
- package/dist/web/setup-api.js +5 -2
- package/docs/security.md +279 -0
- package/package.json +4 -1
- package/test/allowed-users-gate.test.ts +98 -0
- package/test/async-agent-chunk-flow.test.ts +113 -0
- package/test/background-bypass-integration.test.ts +443 -0
- package/test/background-bypass-stress.test.ts +417 -0
- package/test/background-bypass.test.ts +127 -0
- package/test/exec-guard-metachars.test.ts +110 -0
- package/test/file-permissions.test.ts +130 -0
- package/test/session-pending-background.test.ts +59 -0
- package/test/subagent-toolset-allowlist.test.ts +146 -0
- package/test/subagents-toolset.test.ts +22 -2
- package/test/timing-safe-bearer.test.ts +65 -0
- package/test/watcher-pending-count.test.ts +228 -0
|
@@ -114,7 +114,10 @@ export class ClaudeSDKProvider {
|
|
|
114
114
|
allowDangerouslySkipPermissions: true,
|
|
115
115
|
env: cleanEnv,
|
|
116
116
|
settingSources: ["user", "project"],
|
|
117
|
-
allowedTools
|
|
117
|
+
// v4.12.2 — options.allowedTools can override the default full set.
|
|
118
|
+
// Used by sub-agents with toolset="readonly"/"research" to restrict
|
|
119
|
+
// what Claude can do. Default = full access.
|
|
120
|
+
allowedTools: options.allowedTools ?? [
|
|
118
121
|
"Read", "Write", "Edit", "Bash", "Glob", "Grep",
|
|
119
122
|
"WebSearch", "WebFetch", "Task",
|
|
120
123
|
],
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ALLOWED_USERS Startup Gate (v4.12.2)
|
|
3
|
+
*
|
|
4
|
+
* Pure decision function that runs at startup to decide whether Alvin should
|
|
5
|
+
* refuse to start because its Telegram bot is configured but has no user
|
|
6
|
+
* allowlist.
|
|
7
|
+
*
|
|
8
|
+
* Before v4.12.2, an empty ALLOWED_USERS with AUTH_MODE=allowlist would only
|
|
9
|
+
* emit a console.warn and the bot would start anyway. On production this
|
|
10
|
+
* left a "configured but unguarded" surface — any Telegram user who sends
|
|
11
|
+
* a DM would reach the bot and could exploit shell/filesystem access via
|
|
12
|
+
* prompt injection.
|
|
13
|
+
*
|
|
14
|
+
* The gate has two explicit escape hatches, both intentional:
|
|
15
|
+
* 1. AUTH_MODE=open — user explicitly wants a public bot (not recommended)
|
|
16
|
+
* 2. ALVIN_INSECURE_ACKNOWLEDGED=1 — explicit operator opt-out used for
|
|
17
|
+
* test environments and scripted installs where the operator
|
|
18
|
+
* acknowledges they know what they're doing.
|
|
19
|
+
*
|
|
20
|
+
* Pure: takes config values as args, returns a decision. The actual
|
|
21
|
+
* process.exit(1) lives in src/index.ts as a thin wrapper.
|
|
22
|
+
*/
|
|
23
|
+
export function checkAllowedUsersGate(input) {
|
|
24
|
+
// WebUI-only deployments don't have a BOT_TOKEN → nothing to gate
|
|
25
|
+
if (!input.hasTelegram) {
|
|
26
|
+
return { allowed: true };
|
|
27
|
+
}
|
|
28
|
+
// Telegram is enabled AND allowlist is populated → normal path
|
|
29
|
+
if (input.allowedUsersCount > 0) {
|
|
30
|
+
return { allowed: true };
|
|
31
|
+
}
|
|
32
|
+
// Telegram enabled but allowlist empty — check escape hatches
|
|
33
|
+
if (input.authMode === "open") {
|
|
34
|
+
return {
|
|
35
|
+
allowed: true,
|
|
36
|
+
warning: "AUTH_MODE=open explicitly set. Any Telegram user can message the bot. " +
|
|
37
|
+
"This is NOT recommended for machines with sensitive files or shell access.",
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (input.insecureAcknowledged) {
|
|
41
|
+
return {
|
|
42
|
+
allowed: true,
|
|
43
|
+
warning: "ALVIN_INSECURE_ACKNOWLEDGED=1 set. Bot starts with empty ALLOWED_USERS. " +
|
|
44
|
+
"The operator has explicitly opted out of the safety gate.",
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// No escape hatch — refuse to start
|
|
48
|
+
return {
|
|
49
|
+
allowed: false,
|
|
50
|
+
reason: "ALLOWED_USERS is empty but BOT_TOKEN is set. " +
|
|
51
|
+
"Alvin Bot has full shell/filesystem access on this machine, so starting with " +
|
|
52
|
+
"an empty allowlist would leave the bot open to anyone who sends it a Telegram message. " +
|
|
53
|
+
"Fix: set ALLOWED_USERS=<your telegram user id> in ~/.alvin-bot/.env (get your ID from @userinfobot). " +
|
|
54
|
+
"Explicit opt-out: AUTH_MODE=open OR ALVIN_INSECURE_ACKNOWLEDGED=1.",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -26,6 +26,7 @@ import fs from "fs";
|
|
|
26
26
|
import { dirname } from "path";
|
|
27
27
|
import { parseOutputFileStatus } from "./async-agent-parser.js";
|
|
28
28
|
import { ASYNC_AGENTS_STATE_FILE } from "../paths.js";
|
|
29
|
+
import { getAllSessions } from "./session.js";
|
|
29
30
|
/** How often the polling loop runs against each pending agent. */
|
|
30
31
|
const POLL_INTERVAL_MS = 15_000;
|
|
31
32
|
/** Hard ceiling per agent — 12h. After this, give up and deliver
|
|
@@ -81,10 +82,32 @@ export function registerPendingAgent(input) {
|
|
|
81
82
|
lastCheckedAt: 0,
|
|
82
83
|
giveUpAt: input.giveUpAt ?? now + MAX_AGENT_AGE_MS,
|
|
83
84
|
toolUseId: input.toolUseId,
|
|
85
|
+
sessionKey: input.sessionKey,
|
|
84
86
|
};
|
|
85
87
|
pending.set(input.agentId, entry);
|
|
86
88
|
saveToDisk();
|
|
87
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* v4.12.3 — Decrement the session's pendingBackgroundCount. Called on
|
|
92
|
+
* every delivery (completed/failed/timeout). Clamped at 0 so drift
|
|
93
|
+
* scenarios (counter was already 0, or session was reset) never crash.
|
|
94
|
+
* Missing/unknown sessionKey → no-op. Never throws.
|
|
95
|
+
*/
|
|
96
|
+
function decrementPendingCount(sessionKey) {
|
|
97
|
+
if (!sessionKey)
|
|
98
|
+
return;
|
|
99
|
+
try {
|
|
100
|
+
const all = getAllSessions();
|
|
101
|
+
const s = all.get(sessionKey);
|
|
102
|
+
if (!s)
|
|
103
|
+
return;
|
|
104
|
+
s.pendingBackgroundCount = Math.max(0, (s.pendingBackgroundCount ?? 0) - 1);
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
// Never let a decrement failure break delivery.
|
|
108
|
+
console.error("[async-watcher] decrement failed:", err);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
88
111
|
/** Returns a snapshot of in-memory pending agents (for /subagents + diagnostics). */
|
|
89
112
|
export function listPendingAgents() {
|
|
90
113
|
return [...pending.values()];
|
|
@@ -167,6 +190,7 @@ async function deliverAsCompleted(entry, output, tokensUsed) {
|
|
|
167
190
|
catch (err) {
|
|
168
191
|
console.error(`[async-watcher] delivery failed for ${entry.agentId}:`, err);
|
|
169
192
|
}
|
|
193
|
+
decrementPendingCount(entry.sessionKey);
|
|
170
194
|
}
|
|
171
195
|
async function deliverAsFailure(entry, status, error) {
|
|
172
196
|
const { deliverSubAgentResult } = await import("./subagent-delivery.js");
|
|
@@ -194,6 +218,7 @@ async function deliverAsFailure(entry, status, error) {
|
|
|
194
218
|
catch (err) {
|
|
195
219
|
console.error(`[async-watcher] failure delivery failed for ${entry.agentId}:`, err);
|
|
196
220
|
}
|
|
221
|
+
decrementPendingCount(entry.sessionKey);
|
|
197
222
|
}
|
|
198
223
|
// ── Test helpers ──────────────────────────────────────────────────
|
|
199
224
|
/** Test-only: drop in-memory state. Doesn't touch disk. */
|
package/dist/services/cron.js
CHANGED
|
@@ -124,6 +124,23 @@ async function executeJob(job) {
|
|
|
124
124
|
}
|
|
125
125
|
case "shell": {
|
|
126
126
|
const cmd = job.payload.command || "echo 'no command'";
|
|
127
|
+
// v4.12.2 — Cron shell jobs now go through exec-guard. Before
|
|
128
|
+
// v4.12.2 cron bypassed the allowlist, which was inconsistent
|
|
129
|
+
// with the rest of the bot's shell execution policy. With
|
|
130
|
+
// EXEC_SECURITY=allowlist (default) this rejects jobs with
|
|
131
|
+
// shell metacharacters or non-allowlisted binaries. Operators
|
|
132
|
+
// who legitimately need complex shell pipelines in cron set
|
|
133
|
+
// EXEC_SECURITY=full explicitly.
|
|
134
|
+
const { checkExecAllowed } = await import("./exec-guard.js");
|
|
135
|
+
const guard = checkExecAllowed(cmd);
|
|
136
|
+
if (!guard.allowed) {
|
|
137
|
+
const msg = `Cron shell job blocked by exec-guard: ${guard.reason}`;
|
|
138
|
+
console.warn(`[cron] ${job.name}: ${msg}`);
|
|
139
|
+
if (notifyCallback) {
|
|
140
|
+
await notifyCallback(job.target, `🛑 ${job.name}\n${msg}\n\nSet EXEC_SECURITY=full if this is intentional.`);
|
|
141
|
+
}
|
|
142
|
+
return { output: msg };
|
|
143
|
+
}
|
|
127
144
|
// Per-job timeout, default = no timeout (execSync treats timeout=0
|
|
128
145
|
// or "undefined" as infinite). Users opt in via /cron add … --timeout N.
|
|
129
146
|
const shellOpts = {
|
|
@@ -30,12 +30,37 @@ function extractBinary(command) {
|
|
|
30
30
|
// Strip path: /usr/bin/curl -> curl
|
|
31
31
|
return first.split("/").pop() || first;
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* v4.12.2 — Reject shell metacharacters in allowlist mode.
|
|
35
|
+
*
|
|
36
|
+
* The pre-v4.12.2 allowlist check only inspected the first word of the
|
|
37
|
+
* command. That was trivially bypassable via:
|
|
38
|
+
* - ";" chaining: "echo safe; rm -rf /"
|
|
39
|
+
* - "&&" / "||" chains: "echo hi && cat /etc/passwd"
|
|
40
|
+
* - pipe: "cat /etc/passwd | head"
|
|
41
|
+
* - substitution: "echo $(whoami)" or "`whoami`"
|
|
42
|
+
* - redirect: "echo hi > /etc/passwd"
|
|
43
|
+
* - backgrounding: "... &"
|
|
44
|
+
*
|
|
45
|
+
* Strategy: in allowlist mode, any command containing any of these
|
|
46
|
+
* metachars is rejected outright. Users who need shell pipelines opt in
|
|
47
|
+
* explicitly via EXEC_SECURITY=full.
|
|
48
|
+
*/
|
|
49
|
+
const SHELL_METACHAR_PATTERN = /[;&|`$(){}<>]/;
|
|
33
50
|
export function checkExecAllowed(command) {
|
|
34
51
|
if (config.execSecurity === "full")
|
|
35
52
|
return { allowed: true };
|
|
36
53
|
if (config.execSecurity === "deny")
|
|
37
54
|
return { allowed: false, reason: "Shell execution is disabled" };
|
|
38
|
-
// allowlist mode
|
|
55
|
+
// allowlist mode — v4.12.2 metachar guard
|
|
56
|
+
if (SHELL_METACHAR_PATTERN.test(command)) {
|
|
57
|
+
return {
|
|
58
|
+
allowed: false,
|
|
59
|
+
reason: `Command contains shell metacharacters (pipes, redirects, substitution, chaining). ` +
|
|
60
|
+
`Allowlist mode only permits simple binary invocations. ` +
|
|
61
|
+
`Set EXEC_SECURITY=full if you need shell pipelines.`,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
39
64
|
const binary = extractBinary(command);
|
|
40
65
|
if (SAFE_BINS.includes(binary))
|
|
41
66
|
return { allowed: true };
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import fs from "fs";
|
|
12
12
|
import { FALLBACK_FILE, ENV_FILE, DATA_DIR } from "../paths.js";
|
|
13
|
+
import { writeSecure } from "./file-permissions.js";
|
|
13
14
|
// ── Public API ──────────────────────────────────────────────────────────────
|
|
14
15
|
/**
|
|
15
16
|
* Get the current fallback order.
|
|
@@ -143,7 +144,9 @@ function syncToEnv(primary, fallbacks) {
|
|
|
143
144
|
else {
|
|
144
145
|
env += `\nFALLBACK_PROVIDERS=${fallbackStr}`;
|
|
145
146
|
}
|
|
146
|
-
|
|
147
|
+
// v4.12.2 — writeSecure enforces 0o600 on .env so other users on the
|
|
148
|
+
// machine can't read tokens/API keys.
|
|
149
|
+
writeSecure(ENV_FILE, env);
|
|
147
150
|
}
|
|
148
151
|
catch (err) {
|
|
149
152
|
console.error("Failed to sync fallback order to .env:", err);
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Permissions Hardening (v4.12.2)
|
|
3
|
+
*
|
|
4
|
+
* On multi-user dev servers, Alvin's sensitive files (.env, sessions.json,
|
|
5
|
+
* memory files, cron-jobs.json) were previously written with the default
|
|
6
|
+
* umask — typically 0o644 on Linux/macOS, meaning any other user on the
|
|
7
|
+
* same machine could read API keys, conversation history, cron job
|
|
8
|
+
* definitions, etc.
|
|
9
|
+
*
|
|
10
|
+
* This module provides:
|
|
11
|
+
* - writeSecure(path, content) — atomic write with mode 0o600
|
|
12
|
+
* - ensureSecureMode(path) — chmod-repair an existing file if it's too permissive
|
|
13
|
+
* - auditSensitiveFiles(paths[]) — batch-audit a list of files and repair
|
|
14
|
+
*
|
|
15
|
+
* The handler strategy:
|
|
16
|
+
* - NEW writes: use writeSecure() or pass `{ mode: 0o600 }` to writeFileSync
|
|
17
|
+
* - STARTUP: call auditSensitiveFiles() once with the list of known-sensitive
|
|
18
|
+
* files to chmod-repair anything that was written pre-v4.12.2
|
|
19
|
+
*
|
|
20
|
+
* Pure file-system operations — no grammy, no session, testable in isolation.
|
|
21
|
+
*/
|
|
22
|
+
import fs from "fs";
|
|
23
|
+
/** Strict mode for all sensitive files: owner read/write only. */
|
|
24
|
+
export const SECURE_MODE = 0o600;
|
|
25
|
+
/**
|
|
26
|
+
* Atomically write a file with mode 0o600.
|
|
27
|
+
*
|
|
28
|
+
* Uses fs.writeFileSync's built-in `mode` option for initial creation, then
|
|
29
|
+
* an explicit fs.chmodSync to handle the case where the file already exists
|
|
30
|
+
* (in which case the mode arg to writeFileSync is ignored).
|
|
31
|
+
*/
|
|
32
|
+
export function writeSecure(path, content) {
|
|
33
|
+
fs.writeFileSync(path, content, { mode: SECURE_MODE });
|
|
34
|
+
// writeFileSync's mode is only applied on initial create. If the file
|
|
35
|
+
// already existed with a looser mode, we need to explicitly chmod it.
|
|
36
|
+
try {
|
|
37
|
+
fs.chmodSync(path, SECURE_MODE);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Best effort — some filesystems (e.g. FAT) don't support chmod
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Ensure a file is at most as permissive as SECURE_MODE (0o600). If it's
|
|
45
|
+
* already 0o600 or stricter (e.g. 0o400), leave it alone. If it's more
|
|
46
|
+
* permissive (e.g. 0o644, 0o666), repair it to 0o600.
|
|
47
|
+
*
|
|
48
|
+
* Returns a report of what happened — used by auditSensitiveFiles().
|
|
49
|
+
*/
|
|
50
|
+
export function ensureSecureMode(path) {
|
|
51
|
+
let stat;
|
|
52
|
+
try {
|
|
53
|
+
stat = fs.statSync(path);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
const e = err;
|
|
57
|
+
if (e.code === "ENOENT") {
|
|
58
|
+
return { path, status: "missing" };
|
|
59
|
+
}
|
|
60
|
+
return { path, status: "error", error: e.message };
|
|
61
|
+
}
|
|
62
|
+
const currentMode = stat.mode & 0o777;
|
|
63
|
+
// If the file is already at SECURE_MODE or stricter (fewer bits), leave it.
|
|
64
|
+
// We use bitwise AND: if (currentMode & ~SECURE_MODE) === 0 then all set bits
|
|
65
|
+
// are within SECURE_MODE's bits — i.e. the file is not MORE permissive.
|
|
66
|
+
if ((currentMode & ~SECURE_MODE) === 0) {
|
|
67
|
+
return { path, status: "already-secure" };
|
|
68
|
+
}
|
|
69
|
+
// File is more permissive than 0o600 — repair.
|
|
70
|
+
try {
|
|
71
|
+
fs.chmodSync(path, SECURE_MODE);
|
|
72
|
+
return {
|
|
73
|
+
path,
|
|
74
|
+
status: "repaired",
|
|
75
|
+
previousMode: currentMode.toString(8),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return {
|
|
80
|
+
path,
|
|
81
|
+
status: "error",
|
|
82
|
+
error: err instanceof Error ? err.message : String(err),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Audit + repair a list of sensitive file paths. Returns a report per file.
|
|
88
|
+
* Called once at bot startup with the list of known-sensitive files so that
|
|
89
|
+
* any file written pre-v4.12.2 (with default 0o644/0o666 umask) gets repaired.
|
|
90
|
+
*/
|
|
91
|
+
export function auditSensitiveFiles(paths) {
|
|
92
|
+
return paths.map(p => ensureSecureMode(p));
|
|
93
|
+
}
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
import fs from "fs";
|
|
22
22
|
import { dirname } from "path";
|
|
23
23
|
import { SESSIONS_STATE_FILE } from "../paths.js";
|
|
24
|
+
import { SECURE_MODE } from "./file-permissions.js";
|
|
24
25
|
import { getAllSessions, getTelegramWorkspacesMap, } from "./session.js";
|
|
25
26
|
/** History entries to keep in the persisted snapshot (per session). */
|
|
26
27
|
const MAX_PERSISTED_HISTORY = 50;
|
|
@@ -85,9 +86,20 @@ export async function flushSessions() {
|
|
|
85
86
|
sessions: out,
|
|
86
87
|
telegramWorkspaces: tgWorkspaces,
|
|
87
88
|
};
|
|
88
|
-
// Atomic write: tmp + rename
|
|
89
|
+
// Atomic write: tmp + rename. v4.12.2 — mode 0o600 enforced so other
|
|
90
|
+
// users on the same machine can't read conversation history or tokens.
|
|
89
91
|
const tmpFile = `${SESSIONS_STATE_FILE}.tmp`;
|
|
90
|
-
fs.writeFileSync(tmpFile, JSON.stringify(envelope, null, 2),
|
|
92
|
+
fs.writeFileSync(tmpFile, JSON.stringify(envelope, null, 2), {
|
|
93
|
+
encoding: "utf-8",
|
|
94
|
+
mode: SECURE_MODE,
|
|
95
|
+
});
|
|
96
|
+
// Belt-and-suspenders: chmod in case the tmp file already existed with
|
|
97
|
+
// looser permissions (writeFileSync's mode option is only applied on
|
|
98
|
+
// initial create).
|
|
99
|
+
try {
|
|
100
|
+
fs.chmodSync(tmpFile, SECURE_MODE);
|
|
101
|
+
}
|
|
102
|
+
catch { /* fs may not support */ }
|
|
91
103
|
fs.renameSync(tmpFile, SESSIONS_STATE_FILE);
|
|
92
104
|
}
|
|
93
105
|
catch (err) {
|
|
@@ -179,6 +191,11 @@ export function loadPersistedSessions() {
|
|
|
179
191
|
compactionCount: 0,
|
|
180
192
|
checkpointHintsInjected: 0,
|
|
181
193
|
sdkSubTaskCount: 0,
|
|
194
|
+
// v4.12.3 — Don't persist pendingBackgroundCount. On restart, the
|
|
195
|
+
// async-agent-watcher re-hydrates its own state file and polls each
|
|
196
|
+
// pending agent's outputFile, which handles delivery independently.
|
|
197
|
+
// Starting at 0 avoids stale counters surviving a crash.
|
|
198
|
+
pendingBackgroundCount: 0,
|
|
182
199
|
history: Array.isArray(persisted.history) ? persisted.history : [],
|
|
183
200
|
language: persisted.language ?? "en",
|
|
184
201
|
messageQueue: [],
|
package/dist/services/session.js
CHANGED
|
@@ -94,6 +94,7 @@ export function getSession(key) {
|
|
|
94
94
|
compactionCount: 0,
|
|
95
95
|
checkpointHintsInjected: 0,
|
|
96
96
|
sdkSubTaskCount: 0,
|
|
97
|
+
pendingBackgroundCount: 0,
|
|
97
98
|
history: [],
|
|
98
99
|
language: "en",
|
|
99
100
|
messageQueue: [],
|
|
@@ -122,6 +123,7 @@ export function resetSession(key) {
|
|
|
122
123
|
session.compactionCount = 0;
|
|
123
124
|
session.checkpointHintsInjected = 0;
|
|
124
125
|
session.sdkSubTaskCount = 0;
|
|
126
|
+
session.pendingBackgroundCount = 0;
|
|
125
127
|
session.history = [];
|
|
126
128
|
session.lastSdkHistoryIndex = -1;
|
|
127
129
|
session.startedAt = Date.now();
|
|
@@ -250,12 +250,30 @@ async function runSubAgent(id, agentConfig, abort, resolvedName) {
|
|
|
250
250
|
? agentConfig.workingDir || os.homedir()
|
|
251
251
|
: os.homedir();
|
|
252
252
|
const systemPrompt = `You are a sub-agent named "${resolvedName}". Complete the following task autonomously and report your results clearly when done. Working directory: ${effectiveCwd}`;
|
|
253
|
+
// v4.12.2 — Map the toolset preset to an explicit allowedTools list.
|
|
254
|
+
// The provider honors this override (see src/providers/claude-sdk-provider.ts
|
|
255
|
+
// line ~140). Passing undefined = full access (provider default).
|
|
256
|
+
const allowedToolsForToolset = (preset) => {
|
|
257
|
+
switch (preset) {
|
|
258
|
+
case "readonly":
|
|
259
|
+
// Read, analyze, search — no writes, no shell, no network.
|
|
260
|
+
return ["Read", "Glob", "Grep"];
|
|
261
|
+
case "research":
|
|
262
|
+
// Same as readonly + web access for research tasks.
|
|
263
|
+
return ["Read", "Glob", "Grep", "WebSearch", "WebFetch"];
|
|
264
|
+
case "full":
|
|
265
|
+
default:
|
|
266
|
+
// undefined → provider uses its full default set.
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
253
270
|
for await (const chunk of registry.queryWithFallback({
|
|
254
271
|
prompt: agentConfig.prompt,
|
|
255
272
|
systemPrompt,
|
|
256
273
|
workingDir: effectiveCwd,
|
|
257
274
|
effort: "high",
|
|
258
275
|
abortSignal: abort.signal,
|
|
276
|
+
allowedTools: allowedToolsForToolset(agentConfig.toolset ?? "full"),
|
|
259
277
|
})) {
|
|
260
278
|
if (chunk.type === "text") {
|
|
261
279
|
// Both SDK providers emit `text` as the accumulated string.
|
|
@@ -483,12 +501,12 @@ export function spawnSubAgent(agentConfig) {
|
|
|
483
501
|
if (depth > MAX_SUBAGENT_DEPTH) {
|
|
484
502
|
return Promise.reject(new Error(`Sub-agent depth limit reached (${MAX_SUBAGENT_DEPTH}). Agents can only spawn ${MAX_SUBAGENT_DEPTH} level(s) of nested agents.`));
|
|
485
503
|
}
|
|
486
|
-
// G1: toolset preset.
|
|
487
|
-
//
|
|
488
|
-
// bypass TypeScript (e.g. plugin code loaded at runtime).
|
|
504
|
+
// G1: toolset preset (v4.12.2 — extended with readonly + research).
|
|
505
|
+
// The literal type constrains at compile time; the runtime check catches
|
|
506
|
+
// callers that bypass TypeScript (e.g. plugin code loaded at runtime).
|
|
489
507
|
const toolset = agentConfig.toolset ?? "full";
|
|
490
|
-
if (toolset !== "full") {
|
|
491
|
-
return Promise.reject(new Error(`Invalid toolset "${toolset}".
|
|
508
|
+
if (toolset !== "full" && toolset !== "readonly" && toolset !== "research") {
|
|
509
|
+
return Promise.reject(new Error(`Invalid toolset "${toolset}". Valid presets: full, readonly, research.`));
|
|
492
510
|
}
|
|
493
511
|
const maxParallel = getMaxParallelAgents();
|
|
494
512
|
const queueCap = getQueueCap();
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timing-Safe Bearer Token Comparison (v4.12.2)
|
|
3
|
+
*
|
|
4
|
+
* Replaces naive `authHeader !== "Bearer " + token` comparison with
|
|
5
|
+
* crypto.timingSafeEqual so that token comparison time doesn't leak
|
|
6
|
+
* character-level information via side-channel.
|
|
7
|
+
*
|
|
8
|
+
* Real-world exploitability over network is low due to network jitter,
|
|
9
|
+
* but this is the right tool regardless — defense in depth.
|
|
10
|
+
*
|
|
11
|
+
* Behavior:
|
|
12
|
+
* - Strict "Bearer <token>" format required (exactly one space)
|
|
13
|
+
* - Empty expected token always rejects (prevents accidental auth bypass)
|
|
14
|
+
* - Different-length tokens compared via timingSafeEqual on padded buffers
|
|
15
|
+
* so timing doesn't leak whether the prefix matched
|
|
16
|
+
* - Unicode-safe: Buffer.from uses UTF-8 encoding
|
|
17
|
+
*/
|
|
18
|
+
import { timingSafeEqual } from "crypto";
|
|
19
|
+
export function timingSafeBearerMatch(authHeader, expectedToken) {
|
|
20
|
+
// Empty expected token → always reject. Prevents a misconfig where
|
|
21
|
+
// config.webhookToken is "" from accidentally allowing any "Bearer "
|
|
22
|
+
// or empty Authorization header.
|
|
23
|
+
if (!expectedToken || expectedToken.length === 0)
|
|
24
|
+
return false;
|
|
25
|
+
// Missing or non-string header
|
|
26
|
+
if (!authHeader || typeof authHeader !== "string")
|
|
27
|
+
return false;
|
|
28
|
+
// Strict format: "Bearer <token>" with exactly one space. Anything else
|
|
29
|
+
// (double space, leading whitespace, wrong prefix) is rejected. We do
|
|
30
|
+
// this via startsWith + exact-length check, not split, so attackers
|
|
31
|
+
// can't use whitespace variations to confuse the parser.
|
|
32
|
+
const prefix = "Bearer ";
|
|
33
|
+
if (!authHeader.startsWith(prefix))
|
|
34
|
+
return false;
|
|
35
|
+
const providedToken = authHeader.slice(prefix.length);
|
|
36
|
+
// timingSafeEqual requires equal-length buffers. If lengths differ,
|
|
37
|
+
// we return false — but we still touch both strings symbolically so
|
|
38
|
+
// the compare itself is constant-time relative to the shorter one.
|
|
39
|
+
// (A length leak through string.length check is acceptable; what we
|
|
40
|
+
// actually care about is that the character-by-character comparison
|
|
41
|
+
// doesn't leak.)
|
|
42
|
+
const expectedBuf = Buffer.from(expectedToken, "utf-8");
|
|
43
|
+
const providedBuf = Buffer.from(providedToken, "utf-8");
|
|
44
|
+
if (expectedBuf.length !== providedBuf.length) {
|
|
45
|
+
// Do a dummy comparison so total time is closer to constant.
|
|
46
|
+
// Not perfect but better than early-return alone.
|
|
47
|
+
timingSafeEqual(expectedBuf, expectedBuf);
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
return timingSafeEqual(expectedBuf, providedBuf);
|
|
51
|
+
}
|
package/dist/web/doctor-api.js
CHANGED
|
@@ -12,6 +12,7 @@ import fs from "fs";
|
|
|
12
12
|
import { resolve, dirname } from "path";
|
|
13
13
|
import { execSync } from "child_process";
|
|
14
14
|
import { BOT_ROOT, ENV_FILE, BACKUP_DIR, DATA_DIR, MEMORY_DIR, MEMORY_FILE, SOUL_FILE, SOUL_EXAMPLE, TOOLS_MD, TOOLS_JSON, CUSTOM_MODELS, CRON_FILE, MCP_CONFIG } from "../paths.js";
|
|
15
|
+
import { writeSecure } from "../services/file-permissions.js";
|
|
15
16
|
// Files to include in backups (absolute paths)
|
|
16
17
|
const BACKUP_FILES = [
|
|
17
18
|
{ src: ENV_FILE, label: ".env" },
|
|
@@ -222,9 +223,14 @@ function autoRepair(action) {
|
|
|
222
223
|
const exampleFile = resolve(BOT_ROOT, ".env.example");
|
|
223
224
|
if (fs.existsSync(exampleFile)) {
|
|
224
225
|
fs.copyFileSync(exampleFile, ENV_FILE);
|
|
226
|
+
// v4.12.2 — enforce 0o600 on fresh .env
|
|
227
|
+
try {
|
|
228
|
+
fs.chmodSync(ENV_FILE, 0o600);
|
|
229
|
+
}
|
|
230
|
+
catch { /* fs may not support */ }
|
|
225
231
|
return { ok: true, message: ".env created from .env.example" };
|
|
226
232
|
}
|
|
227
|
-
|
|
233
|
+
writeSecure(ENV_FILE, "BOT_TOKEN=\nALLOWED_USERS=\nPRIMARY_PROVIDER=claude-sdk\n");
|
|
228
234
|
return { ok: true, message: "Default .env created (BOT_TOKEN still needs to be set)" };
|
|
229
235
|
}
|
|
230
236
|
case "create-docs": {
|
|
@@ -272,7 +278,7 @@ function autoRepair(action) {
|
|
|
272
278
|
const lines = fs.readFileSync(ENV_FILE, "utf-8").split("\n");
|
|
273
279
|
if (lineIdx >= 0 && lineIdx < lines.length) {
|
|
274
280
|
lines[lineIdx] = "# " + lines[lineIdx]; // Comment out broken line
|
|
275
|
-
|
|
281
|
+
writeSecure(ENV_FILE, lines.join("\n"));
|
|
276
282
|
return { ok: true, message: `Line ${lineIdx + 1} commented out` };
|
|
277
283
|
}
|
|
278
284
|
}
|
package/dist/web/server.js
CHANGED
|
@@ -28,6 +28,8 @@ import { handleDoctorAPI } from "./doctor-api.js";
|
|
|
28
28
|
import { handleOpenAICompat } from "./openai-compat.js";
|
|
29
29
|
import { addCanvasClient } from "./canvas.js";
|
|
30
30
|
import { BOT_ROOT, ENV_FILE, PUBLIC_DIR, MEMORY_DIR, MEMORY_FILE, SOUL_FILE, DATA_DIR, MCP_CONFIG, SKILLS_DIR } from "../paths.js";
|
|
31
|
+
import { writeSecure } from "../services/file-permissions.js";
|
|
32
|
+
import { timingSafeBearerMatch } from "../services/timing-safe-bearer.js";
|
|
31
33
|
import { broadcast } from "../services/broadcast.js";
|
|
32
34
|
import { BOT_VERSION } from "../version.js";
|
|
33
35
|
import { decideNextBindAction } from "./bind-strategy.js";
|
|
@@ -106,8 +108,9 @@ async function handleAPI(req, res, urlPath, body) {
|
|
|
106
108
|
res.end(JSON.stringify({ error: "Webhooks disabled" }));
|
|
107
109
|
return;
|
|
108
110
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
+
// v4.12.2 — timing-safe bearer token comparison. Previously used
|
|
112
|
+
// naive !== which leaks comparison position via timing side-channel.
|
|
113
|
+
if (!timingSafeBearerMatch(req.headers.authorization, config.webhookToken ?? "")) {
|
|
111
114
|
res.writeHead(401);
|
|
112
115
|
res.end(JSON.stringify({ error: "Unauthorized" }));
|
|
113
116
|
return;
|
|
@@ -1041,7 +1044,8 @@ async function handleAPI(req, res, urlPath, body) {
|
|
|
1041
1044
|
else {
|
|
1042
1045
|
envContent = envContent.trimEnd() + `\n${key}=${value}\n`;
|
|
1043
1046
|
}
|
|
1044
|
-
|
|
1047
|
+
// v4.12.2 — enforce 0o600 on .env
|
|
1048
|
+
writeSecure(ENV_FILE, envContent);
|
|
1045
1049
|
res.end(JSON.stringify({ ok: true, note: "Restart required for changes to take effect" }));
|
|
1046
1050
|
}
|
|
1047
1051
|
catch {
|
package/dist/web/setup-api.js
CHANGED
|
@@ -13,6 +13,7 @@ import { getRegistry } from "../engine.js";
|
|
|
13
13
|
import { listJobs, createJob, deleteJob, toggleJob, updateJob, runJobNow, formatNextRun, humanReadableSchedule } from "../services/cron.js";
|
|
14
14
|
import { storePassword, revokePassword, getSudoStatus, verifyPassword, sudoExec, requestAdminViaDialog, openSystemSettings } from "../services/sudo.js";
|
|
15
15
|
import { ENV_FILE, CUSTOM_MODELS as CUSTOM_MODELS_FILE, BOT_ROOT, WHATSAPP_AUTH } from "../paths.js";
|
|
16
|
+
import { writeSecure } from "../services/file-permissions.js";
|
|
16
17
|
// ── Env Helpers ─────────────────────────────────────────
|
|
17
18
|
function readEnv() {
|
|
18
19
|
if (!fs.existsSync(ENV_FILE))
|
|
@@ -36,14 +37,16 @@ function writeEnvVar(key, value) {
|
|
|
36
37
|
else {
|
|
37
38
|
content = content.trimEnd() + `\n${key}=${value}\n`;
|
|
38
39
|
}
|
|
39
|
-
|
|
40
|
+
// v4.12.2 — .env contains all secrets (bot tokens, API keys). Enforce
|
|
41
|
+
// 0o600 so other users on the machine can't read it.
|
|
42
|
+
writeSecure(ENV_FILE, content);
|
|
40
43
|
}
|
|
41
44
|
function removeEnvVar(key) {
|
|
42
45
|
if (!fs.existsSync(ENV_FILE))
|
|
43
46
|
return;
|
|
44
47
|
let content = fs.readFileSync(ENV_FILE, "utf-8");
|
|
45
48
|
content = content.replace(new RegExp(`^${key}=.*\n?`, "m"), "");
|
|
46
|
-
|
|
49
|
+
writeSecure(ENV_FILE, content);
|
|
47
50
|
}
|
|
48
51
|
function loadCustomModels() {
|
|
49
52
|
try {
|