Skip to content

Commit 5a20a79

Browse files
author
Cad from Arca
committed
fix(hermes-agent): enforce authorization and persist cursors
1 parent d7f2fc0 commit 5a20a79

11 files changed

Lines changed: 480 additions & 35 deletions

File tree

‎examples/hermes-agent/README.md‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ and executes tools on the Hermes server.
66

77
## Behavior
88

9-
- Direct messages always dispatch to Hermes.
10-
- Top-level channel messages dispatch only when they mention the bot handle.
9+
- Direct messages dispatch only when the sender ID is explicitly allowed.
10+
- Channel messages require both an allowed sender ID and an allowed channel ID;
11+
top-level messages must also mention the bot handle.
1112
- The first channel answer is posted in a thread.
1213
- Later human replies continue without another mention while the bot appears in the
1314
latest 200 replies; older dormant threads require a fresh mention.
@@ -20,12 +21,17 @@ and executes tools on the Hermes server.
2021
- Final replies use a deterministic ClickClack message nonce derived from the
2122
source message ID.
2223

23-
On a fresh process, the connector captures ClickClack's atomic current event tail
24-
and does not replay old messages. After a transient disconnect, it drains events
25-
from the last completed in-memory cursor before reconnecting. Socket read-ahead is
26-
capped at 32 durable events; hitting the cap closes and resumes the socket from the
27-
committed cursor. A process crash can skip those admitted in-memory events, but it
28-
will not replay older messages and rerun side-effecting tools.
24+
On the first process start, the connector captures and atomically persists
25+
ClickClack's current event tail, so it does not replay old messages. Reconnects and
26+
process restarts resume from the last contiguous successfully completed cursor.
27+
Socket read-ahead is capped at 32 durable events; hitting the cap closes and
28+
resumes the socket from that committed cursor.
29+
30+
Delivery is at least once across crashes. If the process exits after Hermes
31+
finishes but before the cursor file is committed, that event is replayed. The
32+
deterministic ClickClack reply nonce prevents a duplicate final message, but a
33+
side-effecting Hermes tool may run again. Use Hermes approval policies and
34+
idempotent tools for externally mutating work.
2935

3036
## Requirements
3137

@@ -94,6 +100,9 @@ pnpm install --frozen-lockfile
94100
CLICKCLACK_BASE_URL=https://app.clickclack.chat \
95101
CLICKCLACK_BOT_TOKEN=ccb_... \
96102
CLICKCLACK_WORKSPACE_ID=wsp_... \
103+
HERMES_CONNECTOR_ALLOWED_USER_IDS=usr_manager \
104+
HERMES_CONNECTOR_ALLOWED_CHANNEL_IDS=chn_ops \
105+
HERMES_CONNECTOR_CURSOR_FILE=/var/lib/clickclack-hermes/cursor.json \
97106
HERMES_API_URL=http://127.0.0.1:8642 \
98107
HERMES_API_KEY=replace-with-a-long-random-secret \
99108
pnpm --filter @clickclack/example-hermes-agent start
@@ -111,6 +120,9 @@ non-loopback Hermes URL.
111120
| `CLICKCLACK_BOT_TOKEN` | yes | — | Workspace-scoped `ccb_...` token |
112121
| `CLICKCLACK_WORKSPACE_ID` | yes | — | Workspace watched by the bot |
113122
| `CLICKCLACK_CONNECTOR_ALLOW_INSECURE_REMOTE_HTTP` | no | `false` | Allow remote plaintext ClickClack only on trusted dev networks |
123+
| `HERMES_CONNECTOR_ALLOWED_USER_IDS` | yes | — | Comma-separated human user IDs allowed to invoke Hermes; wildcards are rejected |
124+
| `HERMES_CONNECTOR_ALLOWED_CHANNEL_IDS` | no | empty | Comma-separated channel IDs allowed to invoke Hermes; empty denies every channel |
125+
| `HERMES_CONNECTOR_CURSOR_FILE` | yes | — | Absolute path for workspace-bound durable cursor state |
114126
| `HERMES_API_URL` | no | `http://127.0.0.1:8642` | Hermes API server origin |
115127
| `HERMES_API_KEY` | remote Hermes only | — | Hermes bearer key |
116128
| `HERMES_CONNECTOR_HISTORY_LIMIT` | no | `20` | Prior DM/thread messages, `0-200` |
@@ -135,6 +147,10 @@ seconds, so an unresponsive Hermes stop endpoint cannot pin the slot.
135147
## Operational notes
136148

137149
- Run one connector process per bot token/workspace pair.
150+
- Keep the cursor file on persistent local storage. Give the connector user write
151+
access to its parent directory; cursor files are created with mode `0600`.
152+
- Do not reuse a cursor file across workspaces. The connector fails closed when
153+
the stored workspace ID differs from `CLICKCLACK_WORKSPACE_ID`.
138154
- Use a process supervisor and restart on non-zero exit.
139155
- Rotate the ClickClack and Hermes keys independently.
140156
- Do not expose an unsandboxed Hermes API directly to the public internet.

‎examples/hermes-agent/src/config.test.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ const required = {
77
CLICKCLACK_BASE_URL: "https://clickclack.example/",
88
CLICKCLACK_BOT_TOKEN: "ccb_test",
99
CLICKCLACK_WORKSPACE_ID: "wsp_1",
10+
HERMES_CONNECTOR_ALLOWED_USER_IDS: "usr_1, usr_2",
11+
HERMES_CONNECTOR_CURSOR_FILE: "/var/lib/clickclack-hermes/cursor.json",
1012
};
1113

1214
test("loadConfig normalizes URLs and parses bounded integer options", () => {
@@ -27,12 +29,31 @@ test("loadConfig normalizes URLs and parses bounded integer options", () => {
2729
assert.equal(config.maxConcurrentRuns, 6);
2830
assert.equal(config.runTimeoutMs, 9000);
2931
assert.equal(config.reconnectMs, 250);
32+
assert.deepEqual(config.allowedUserIds, new Set(["usr_1", "usr_2"]));
33+
assert.deepEqual(config.allowedChannelIds, new Set<string>());
34+
assert.equal(config.cursorFile, "/var/lib/clickclack-hermes/cursor.json");
3035
});
3136

32-
test("loadConfig reports every missing required ClickClack variable", () => {
37+
test("loadConfig reports every missing required security variable", () => {
3338
assert.throws(
3439
() => loadConfig({}),
35-
/CLICKCLACK_BASE_URL, CLICKCLACK_BOT_TOKEN, CLICKCLACK_WORKSPACE_ID/,
40+
/CLICKCLACK_BASE_URL, CLICKCLACK_BOT_TOKEN, CLICKCLACK_WORKSPACE_ID, HERMES_CONNECTOR_ALLOWED_USER_IDS, HERMES_CONNECTOR_CURSOR_FILE/,
41+
);
42+
});
43+
44+
test("loadConfig parses an explicit channel allowlist", () => {
45+
const config = loadConfig({
46+
...required,
47+
HERMES_CONNECTOR_ALLOWED_CHANNEL_IDS: "chn_1,chn_2, chn_1",
48+
});
49+
50+
assert.deepEqual(config.allowedChannelIds, new Set(["chn_1", "chn_2"]));
51+
});
52+
53+
test("loadConfig requires an absolute cursor file path", () => {
54+
assert.throws(
55+
() => loadConfig({ ...required, HERMES_CONNECTOR_CURSOR_FILE: "state/cursor.json" }),
56+
/HERMES_CONNECTOR_CURSOR_FILE must be an absolute path/,
3657
);
3758
});
3859

‎examples/hermes-agent/src/config.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isAbsolute } from "node:path";
2+
13
export type HermesConnectorConfig = {
24
clickclackBaseUrl: string;
35
clickclackBotToken: string;
@@ -9,6 +11,9 @@ export type HermesConnectorConfig = {
911
maxConcurrentRuns: number;
1012
runTimeoutMs: number;
1113
reconnectMs: number;
14+
allowedUserIds: ReadonlySet<string>;
15+
allowedChannelIds: ReadonlySet<string>;
16+
cursorFile: string;
1217
instructions?: string;
1318
};
1419

@@ -21,6 +26,8 @@ export function loadConfig(env: Environment): HermesConnectorConfig {
2126
"CLICKCLACK_BASE_URL",
2227
"CLICKCLACK_BOT_TOKEN",
2328
"CLICKCLACK_WORKSPACE_ID",
29+
"HERMES_CONNECTOR_ALLOWED_USER_IDS",
30+
"HERMES_CONNECTOR_CURSOR_FILE",
2431
] as const;
2532
const missing = required.filter((key) => !env[key]?.trim());
2633
if (missing.length > 0) {
@@ -43,6 +50,10 @@ export function loadConfig(env: Environment): HermesConnectorConfig {
4350
"HERMES_API_URL",
4451
);
4552
const hermesApiKey = env.HERMES_API_KEY?.trim() || undefined;
53+
const cursorFile = env.HERMES_CONNECTOR_CURSOR_FILE!.trim();
54+
if (!isAbsolute(cursorFile)) {
55+
throw new Error("HERMES_CONNECTOR_CURSOR_FILE must be an absolute path");
56+
}
4657
const hermesUrl = new URL(hermesBaseUrl);
4758
const remoteHermes = !isLoopbackHost(hermesUrl.hostname);
4859
if (!hermesApiKey && remoteHermes) {
@@ -75,12 +86,31 @@ export function loadConfig(env: Environment): HermesConnectorConfig {
7586
86_400_000,
7687
),
7788
reconnectMs: parseInteger(env, "HERMES_CONNECTOR_RECONNECT_MS", 2_000, 50, 60_000),
89+
allowedUserIds: parseIdList(
90+
env.HERMES_CONNECTOR_ALLOWED_USER_IDS!,
91+
"HERMES_CONNECTOR_ALLOWED_USER_IDS",
92+
),
93+
allowedChannelIds: parseIdList(
94+
env.HERMES_CONNECTOR_ALLOWED_CHANNEL_IDS ?? "",
95+
"HERMES_CONNECTOR_ALLOWED_CHANNEL_IDS",
96+
),
97+
cursorFile,
7898
...(env.HERMES_CONNECTOR_INSTRUCTIONS?.trim()
7999
? { instructions: env.HERMES_CONNECTOR_INSTRUCTIONS.trim() }
80100
: {}),
81101
};
82102
}
83103

104+
function parseIdList(value: string, name: string): ReadonlySet<string> {
105+
const raw = value.trim();
106+
if (!raw) return new Set();
107+
const values = raw.split(",").map((entry) => entry.trim());
108+
if (values.some((entry) => !entry || entry === "*" || /\s/u.test(entry))) {
109+
throw new Error(`${name} must be a comma-separated list of explicit IDs`);
110+
}
111+
return new Set(values);
112+
}
113+
84114
function normalizeHttpUrl(value: string, name: string): string {
85115
let url: URL;
86116
try {

‎examples/hermes-agent/src/connector.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,11 @@ function connector(
255255
maxConcurrentRuns = 4,
256256
runTimeoutMs = 1_800_000,
257257
stopTimeoutMs = 5_000,
258+
policy: {
259+
allowedUserIds?: string[];
260+
allowedChannelIds?: string[];
261+
signal?: AbortSignal;
262+
} = {},
258263
) {
259264
return new HermesClickClackConnector({
260265
clickclack: client,
@@ -265,6 +270,9 @@ function connector(
265270
maxConcurrentRuns,
266271
runTimeoutMs,
267272
stopTimeoutMs,
273+
allowedUserIds: new Set(policy.allowedUserIds ?? ["usr_human"]),
274+
allowedChannelIds: new Set(policy.allowedChannelIds ?? ["chn_1"]),
275+
signal: policy.signal,
268276
logger: {
269277
info: () => {},
270278
warn: () => {},
@@ -273,6 +281,63 @@ function connector(
273281
});
274282
}
275283

284+
test("rejects a DM from a sender outside the explicit allowlist", async () => {
285+
const client = new FakeClickClack();
286+
const hermes = new FakeHermes();
287+
const current = message("msg_denied_dm", "run a tool", {
288+
channel_id: undefined,
289+
direct_conversation_id: "dm_1",
290+
channel_seq: 1,
291+
});
292+
client.byId.set(current.id, current);
293+
client.dmHistory.set("dm_1", [current]);
294+
295+
await connector(client, hermes, [], 4, 1_800_000, 5_000, {
296+
allowedUserIds: ["usr_someone_else"],
297+
}).handleEvent(eventFor(current));
298+
299+
assert.equal(hermes.starts.length, 0);
300+
assert.equal(client.dmSends.length, 0);
301+
});
302+
303+
test("rejects a channel mention outside the explicit channel allowlist", async () => {
304+
const client = new FakeClickClack();
305+
const hermes = new FakeHermes();
306+
const current = message("msg_denied_channel", "@hermes run a tool");
307+
client.byId.set(current.id, current);
308+
309+
await connector(client, hermes, [], 4, 1_800_000, 5_000, {
310+
allowedChannelIds: ["chn_somewhere_else"],
311+
}).handleEvent(eventFor(current));
312+
313+
assert.equal(hermes.starts.length, 0);
314+
assert.equal(client.threadSends.length, 0);
315+
});
316+
317+
test("rejects malformed dual-target and cross-workspace messages", async () => {
318+
const client = new FakeClickClack();
319+
const hermes = new FakeHermes();
320+
const dualTarget = message("msg_dual_target", "hello", {
321+
channel_id: "chn_1",
322+
direct_conversation_id: "dm_1",
323+
});
324+
const wrongWorkspace = message("msg_wrong_workspace", "hello", {
325+
channel_id: undefined,
326+
direct_conversation_id: "dm_1",
327+
workspace_id: "wsp_other",
328+
});
329+
client.byId.set(dualTarget.id, dualTarget);
330+
client.byId.set(wrongWorkspace.id, wrongWorkspace);
331+
332+
const instance = connector(client, hermes);
333+
await instance.handleEvent(eventFor(dualTarget));
334+
await instance.handleEvent(eventFor(wrongWorkspace));
335+
336+
assert.equal(hermes.starts.length, 0);
337+
assert.equal(client.dmSends.length, 0);
338+
assert.equal(client.threadSends.length, 0);
339+
});
340+
276341
test("ignores self-authored, bot-authored, activity, and unmentioned channel messages", async () => {
277342
const client = new FakeClickClack();
278343
const hermes = new FakeHermes();
@@ -587,6 +652,75 @@ test("retries transient final reply delivery with one deterministic nonce", asyn
587652
assert.equal(lifecycle.line.status, "completed");
588653
});
589654

655+
test("rejects completion when final reply delivery exhausts retries", async () => {
656+
const client = new FakeClickClack();
657+
const hermes = new FakeHermes();
658+
const current = message("msg_reply_exhausted", "hello", {
659+
channel_id: undefined,
660+
direct_conversation_id: "dm_1",
661+
channel_seq: 1,
662+
});
663+
client.byId.set(current.id, current);
664+
client.dmHistory.set("dm_1", [current]);
665+
client.dmFailuresRemaining = 3;
666+
667+
const scheduled = await connector(client, hermes).scheduleEvent(eventFor(current));
668+
669+
await assert.rejects(scheduled.completion, /reply delivery exhausted retries/i);
670+
assert.equal(client.dmSends.length, 3);
671+
});
672+
673+
test("rejects completion when generic failure delivery exhausts retries", async () => {
674+
const client = new FakeClickClack();
675+
const hermes = new FakeHermes();
676+
const current = message("msg_failure_exhausted", "hello", {
677+
channel_id: undefined,
678+
direct_conversation_id: "dm_1",
679+
channel_seq: 1,
680+
});
681+
client.byId.set(current.id, current);
682+
client.dmHistory.set("dm_1", [current]);
683+
client.dmFailuresRemaining = 3;
684+
hermes.startError = new Error("provider failed");
685+
686+
const scheduled = await connector(client, hermes).scheduleEvent(eventFor(current));
687+
688+
await assert.rejects(scheduled.completion, /reply delivery exhausted retries/i);
689+
assert.equal(client.dmSends.length, 3);
690+
});
691+
692+
test("rejects active and queued completions interrupted by shutdown", async () => {
693+
const client = new FakeClickClack();
694+
const hermes = new TimeoutHermes();
695+
const abort = new AbortController();
696+
const first = message("msg_abort_1", "first", {
697+
channel_id: undefined,
698+
direct_conversation_id: "dm_1",
699+
channel_seq: 1,
700+
});
701+
const second = message("msg_abort_2", "second", {
702+
channel_id: undefined,
703+
direct_conversation_id: "dm_1",
704+
channel_seq: 2,
705+
});
706+
client.byId.set(first.id, first);
707+
client.byId.set(second.id, second);
708+
client.dmHistory.set("dm_1", [first, second]);
709+
const instance = connector(client, hermes, [], 4, 1_800_000, 5_000, {
710+
signal: abort.signal,
711+
});
712+
713+
const firstTask = await instance.scheduleEvent(eventFor(first));
714+
const secondTask = await instance.scheduleEvent(eventFor(second));
715+
await waitForCondition(() => hermes.starts.length === 1);
716+
abort.abort(new Error("connector shutdown"));
717+
718+
await assert.rejects(firstTask.completion, /connector shutdown/i);
719+
await assert.rejects(secondTask.completion, /connector shutdown/i);
720+
assert.equal(hermes.starts.length, 1);
721+
assert.equal(client.dmSends.length, 0);
722+
});
723+
590724
test("times out a stalled run, stops it, and reports a generic failure", async () => {
591725
const client = new FakeClickClack();
592726
const hermes = new TimeoutHermes();

0 commit comments

Comments
 (0)