viber-channel 0.8.8 → 0.8.9

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.
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import { createHash } from "node:crypto";
21
21
  import { join } from "node:path";
22
+ import { assertHashKey, assertHashKeyNumber } from "./hash_key.js";
22
23
  import { readFileSync, writeFileSync, unlinkSync } from "node:fs";
23
24
 
24
25
  export interface ChannelHandle {
@@ -43,6 +44,10 @@ export function sessionFilePath(
43
44
  instanceKey: string,
44
45
  dir: string,
45
46
  ): string {
47
+ // #480: guard the hash inputs — see lib/hash_key.ts. A missing field upstream
48
+ // would silently key every agent's handle on the same "undefined" string.
49
+ assertHashKey(baseUrl, "sessionFilePath(baseUrl)", { allowEmpty: false });
50
+ assertHashKey(instanceKey, "sessionFilePath(instanceKey)", { allowEmpty: false });
46
51
  const suffix = createHash("sha256")
47
52
  .update(`${baseUrl}\n${instanceKey}`)
48
53
  .digest("hex")
@@ -74,6 +79,11 @@ export function sessionFilePathForName(
74
79
  name: string,
75
80
  dir: string,
76
81
  ): string {
82
+ assertHashKey(baseUrl, "sessionFilePathForName(baseUrl)", { allowEmpty: false });
83
+ // projectId is a NUMBER: absent, it interpolates to "undefined" in the template
84
+ // below just like a missing string would, so it needs its own guard (#480).
85
+ assertHashKeyNumber(projectId, "sessionFilePathForName(projectId)");
86
+ assertHashKey(name, "sessionFilePathForName(name)", { allowEmpty: false });
77
87
  const suffix = createHash("sha256")
78
88
  .update(`${baseUrl}\n${projectId}\n${name}`)
79
89
  .digest("hex")
@@ -0,0 +1,124 @@
1
+ // The tool definitions served to a CLAUDE session on the `viber-channel` MCP
2
+ // server (ListTools). Extracted from viber-channel.ts into a PURE constant so the
3
+ // rules they carry can be asserted without booting the server (#479).
4
+ //
5
+ // These `description`s are NOT truncated — unlike the MCP `instructions` blob,
6
+ // which the client cuts around 2 KB. That makes them the durable home for the
7
+ // channel-contract style rules (artifact usage, no emoji, literal identifiers):
8
+ // the blob keeps only routing + anti-deadlock, and points here for the rest.
9
+ // See lib/channel_instructions.ts for the budget that split them.
10
+
11
+ import { CONTRACT_STYLE_NEUTRAL, CONTRACT_STYLE_TOOLS } from "./channel_instructions.ts";
12
+
13
+ export const CLAUDE_TOOL_DEFS = [
14
+ {
15
+ name: "send_message",
16
+ description:
17
+ // Claude's OWN delivery policy: it has no auto-post fallback, so send_message
18
+ // is genuinely the only way out. The codex/gemma surface says something
19
+ // different on purpose — see CONTRACT_STYLE_TOOLS for why the shared
20
+ // fragments carry no delivery policy at all.
21
+ "Reply to the USER. This is how you talk to the user — NOT the terminal / your stdout (they do not watch it). Calling this IS your reply for the turn. " +
22
+ "Send a message into the Viber conversation this channel is bound to. " +
23
+ // #479 codex review: consume the SHARED fragments instead of restating the
24
+ // contract. A hand-copied contract is how the three runtimes drifted apart in
25
+ // the first place — and separate green tests would have hidden it.
26
+ CONTRACT_STYLE_NEUTRAL +
27
+ " " +
28
+ CONTRACT_STYLE_TOOLS +
29
+ " Use `html` only when structural HTML markdown can't express is required.",
30
+ inputSchema: {
31
+ type: "object" as const,
32
+ properties: {
33
+ text: {
34
+ type: "string",
35
+ minLength: 1,
36
+ // #479: tool descriptions are NEVER truncated, unlike `instructions` — so
37
+ // this is where the style rules survive. The full contract is on the tool
38
+ // description above (shared fragments); this field stays SPECIFIC and adds
39
+ // only what is about `text` itself, without recopying the contract.
40
+ description: "Conversational reply, read aloud AND shown as Markdown — light Markdown (short lists, **bold**) for readability. Actions and questions go here, visibly. NO emoji (it gets read aloud). Write identifiers LITERALLY (288, auth.json) — never spell out dots or dashes; a lone long token or path belongs in the artifact instead.",
41
+ },
42
+ artifact: {
43
+ type: "object",
44
+ description: "Optional HEAVY/LONG content (big code, large tables, long analyses, JSON, file lists) rendered in the artifact viewer alongside the spoken text. When you use it, keep `text` a brief spoken summary that points to it ('details on the side').",
45
+ properties: {
46
+ content: {
47
+ type: "string",
48
+ minLength: 1,
49
+ description: "Artifact body — markdown, code, JSON, or HTML.",
50
+ },
51
+ format: {
52
+ type: "string",
53
+ enum: ["markdown", "code", "json", "html"],
54
+ description:
55
+ "Render format for the artifact body. Defaults to markdown if omitted. " +
56
+ "Use `html` only when structural HTML is required (styled cards, badges, mixed layouts); " +
57
+ "scripts, event handlers, iframes, and inline styles are stripped server-side before rendering.",
58
+ },
59
+ },
60
+ required: ["content"],
61
+ },
62
+ },
63
+ required: ["text"],
64
+ },
65
+ },
66
+ {
67
+ name: "list_agents",
68
+ description:
69
+ "List the OTHER agents (instances) you can talk to directly (#288). " +
70
+ "Returns each agent's id, label, runtime kind, and whether it is currently online. " +
71
+ "Use this to find the id of an agent (e.g. 'Codex Review') before calling message_agent. " +
72
+ "Normally scoped to this project; if the owner designated this instance an ORCHESTRATOR " +
73
+ "(#307), the list covers ALL the owner's projects and each entry carries a `project` field. " +
74
+ "You are never in the list.",
75
+ inputSchema: {
76
+ type: "object" as const,
77
+ properties: {},
78
+ required: [],
79
+ additionalProperties: false,
80
+ },
81
+ },
82
+ {
83
+ name: "message_agent",
84
+ description:
85
+ "Send a direct message to ANOTHER agent (#288) — NOT for replying to the user (use send_message for that). " +
86
+ "Pass the target agent's instance id (from list_agents, or the from_instance_id of a DM you received) " +
87
+ "and the message text. Opens or reuses a private 1:1 DM with that agent and posts your message; " +
88
+ "the agent's reply arrives back on this channel tagged source=agent-dm. " +
89
+ "Targets are normally same-project; an ORCHESTRATOR instance (#307) can also message agents " +
90
+ "of the owner's other projects (ids from its cross-project list_agents). " +
91
+ "Fails if the target agent is offline.",
92
+ inputSchema: {
93
+ type: "object" as const,
94
+ properties: {
95
+ instance_id: {
96
+ type: "string",
97
+ minLength: 1,
98
+ description: "The target agent's instance id (from list_agents or a received DM's from_instance_id).",
99
+ },
100
+ text: {
101
+ type: "string",
102
+ minLength: 1,
103
+ description: "The message to send to the target agent.",
104
+ },
105
+ },
106
+ required: ["instance_id", "text"],
107
+ additionalProperties: false,
108
+ },
109
+ },
110
+ {
111
+ name: "capabilities",
112
+ description:
113
+ "On-demand: learn what the Viber control plane (vibe-master) can do on this " +
114
+ "machine — how to spawn and supervise OTHER agents (Codex, Claude, Gemma). " +
115
+ "Call this only when orchestrating other agents is relevant; it is not part " +
116
+ "of the default context. Returns a short usage reference.",
117
+ inputSchema: {
118
+ type: "object" as const,
119
+ properties: {},
120
+ required: [],
121
+ additionalProperties: false,
122
+ },
123
+ },
124
+ ] as const;
@@ -87,7 +87,14 @@ export async function sendInstanceHeartbeat(
87
87
  }
88
88
 
89
89
  export interface ControlStreamOptions {
90
- baseUrl: string;
90
+ /**
91
+ * #480 — a getter, not a string. `runPersistentControlStream` RECONNECTS in a
92
+ * loop reusing these options, so a captured string would pin every reconnect
93
+ * (and the internal beat) to whatever host was current when the stream first
94
+ * opened. Same reasoning as `heartbeat.ts`; keeping a string here would be an
95
+ * unexplained asymmetry between two flows doing the same thing.
96
+ */
97
+ getBaseUrl: () => string;
91
98
  instanceId: string;
92
99
  instanceToken: string;
93
100
  signal?: AbortSignal;
@@ -116,7 +123,7 @@ export async function* subscribeControlStream(
116
123
  opts: ControlStreamOptions,
117
124
  ): AsyncGenerator<ControlEvent> {
118
125
  const doFetch = opts.fetchImpl ?? fetch;
119
- const url = buildControlStreamUrl(opts.baseUrl, opts.instanceId);
126
+ const url = buildControlStreamUrl(opts.getBaseUrl(), opts.instanceId);
120
127
 
121
128
  const resp = await doFetch(url, {
122
129
  headers: {
@@ -6,7 +6,13 @@ import { readHandle, writeHandle } from "./channel_session.js";
6
6
  export interface ConversationMintResponse {
7
7
  conversation_id: string;
8
8
  conversation_token: string;
9
+ /**
10
+ * SSE / voice host. Comes from the server's VOICE_BASE_URL (the tunnel) — it is
11
+ * NOT the REST host and #480 deliberately leaves it alone.
12
+ */
9
13
  ws_url: string;
14
+ /** #480 — REST API origin announced by the server. Optional (see register). */
15
+ api_base_url?: string;
10
16
  expires_at: number;
11
17
  }
12
18
 
package/lib/dm_stream.ts CHANGED
@@ -57,7 +57,12 @@ export interface DmStreamOptions {
57
57
  * DIFFERENT origin from `wsUrl` in staging/prod (the messages route lives on
58
58
  * the Worker, not the SSE tunnel); collapsing them caused #333's catch-up 404.
59
59
  */
60
- apiBaseUrl: string;
60
+ /**
61
+ * #480 — a getter, not a string: a DM stream reconnects and calls catchUp()
62
+ * again, so a host announced AFTER the stream started must be picked up. A
63
+ * captured string would pin the DM to the bootstrap host for its whole life.
64
+ */
65
+ getApiBaseUrl: () => string;
61
66
  conversationId: string;
62
67
  conversationToken: string;
63
68
  onMessage: (msg: DmMessage) => void | Promise<void>;
@@ -187,7 +192,7 @@ async function catchUp(opts: DmStreamOptions, handledIds: Set<string>): Promise<
187
192
  const doFetch = opts.fetchMessagesImpl ?? fetchMessages;
188
193
  let msgs: Array<Record<string, unknown>>;
189
194
  try {
190
- msgs = await doFetch(opts.apiBaseUrl, opts.conversationId, opts.conversationToken);
195
+ msgs = await doFetch(opts.getApiBaseUrl(), opts.conversationId, opts.conversationToken);
191
196
  } catch (err) {
192
197
  if (err instanceof ConversationTokenExpiredError) throw new DmStreamAuthError();
193
198
  opts.log?.(
@@ -0,0 +1,65 @@
1
+ /**
2
+ * hash_key.ts — guard for values that feed a PATH-DERIVING hash (#480).
3
+ *
4
+ * Session-file and lock-file paths are SHA-256 prefixes of concatenated strings.
5
+ * A missing field in a caller's object literal becomes `undefined`, which
6
+ * stringifies to `"undefined"` and still produces a perfectly valid-looking
7
+ * path — so every agent that hits the bug converges on the SAME lock and the
8
+ * SAME conversation handle, silently, across projects.
9
+ *
10
+ * `viber-channel` has no tsconfig, so nothing typechecks these call sites in CI
11
+ * (the #480 step-02 review found exactly this bug in the Codex `--conversation`
12
+ * path, live, with a green test suite). This guard is the cheap substitute:
13
+ * fail loudly at the moment the hash is computed.
14
+ */
15
+
16
+ /**
17
+ * Throw unless `value` is a usable hash input.
18
+ *
19
+ * `""` is ACCEPTED by default: it is a meaningful value in this codebase — the
20
+ * lock's session axis is `""` for plain bunx clients, and `lockfile.test.ts`
21
+ * deliberately passes an empty fingerprint to prove the separators keep the
22
+ * three axes apart. The bug this guards against is a MISSING field
23
+ * (`undefined`), not an empty one. Pass `{ allowEmpty: false }` where empty is
24
+ * genuinely meaningless (a base URL).
25
+ */
26
+ export function assertHashKey(
27
+ value: unknown,
28
+ what: string,
29
+ opts: { allowEmpty?: boolean } = {},
30
+ ): void {
31
+ if (typeof value !== "string") {
32
+ throw new TypeError(
33
+ `${what}: hash inputs must be a string, got ${String(value)}. ` +
34
+ `A missing field here would silently make every agent share one lock/handle (#480).`,
35
+ );
36
+ }
37
+ if (value.length === 0 && opts.allowEmpty === false) {
38
+ throw new TypeError(`${what}: hash input must not be empty (#480).`);
39
+ }
40
+ // Catches the classic `${undefined}` / `${null}` interpolation upstream, which
41
+ // arrives as a real string and would otherwise pass the check above.
42
+ if (value === "undefined" || value === "null") {
43
+ throw new TypeError(
44
+ `${what}: hash input is the literal "${value}" — an interpolated missing value (#480).`,
45
+ );
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Same guard for a NUMERIC hash axis (e.g. `projectId`).
51
+ *
52
+ * A missing `number` field interpolates to `"undefined"` inside the template
53
+ * string exactly like a missing string does — but `assertHashKey` would reject
54
+ * every legitimate number, so the numeric axes need their own check. Found in
55
+ * review: the first version of this guard covered 2 of the 3 axes of
56
+ * `sessionFilePathForName`, and the uncovered one was the same type as the
57
+ * incident that motivated the guard.
58
+ */
59
+ export function assertHashKeyNumber(value: unknown, what: string): void {
60
+ if (typeof value !== "number" || !Number.isFinite(value)) {
61
+ throw new TypeError(
62
+ `${what}: numeric hash inputs must be a finite number, got ${String(value)} (#480).`,
63
+ );
64
+ }
65
+ }
package/lib/heartbeat.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  * it from the Agents sidebar and signal its streams to stop. This module
9
9
  * centralizes the beat so the two clients can't diverge.
10
10
  *
11
- * The token is read through a getter on every tick so the beat follows token
12
- * refresh (#237) without re-wiring. (The legacy per-conversation heartbeat #298
11
+ * The token AND the API host are read through getters on every tick so the beat
12
+ * follows token refresh (#237) and the #480 host announcement without re-wiring. (The legacy per-conversation heartbeat #298
13
13
  * was removed in #315 once "Active" derived from instance liveness.)
14
14
  */
15
15
 
@@ -71,7 +71,15 @@ export interface HeartbeatHandle {
71
71
  }
72
72
 
73
73
  export interface InstanceHeartbeatOptions {
74
- baseUrl: string;
74
+ /**
75
+ * #480 — read on EVERY tick, exactly like `getInstanceToken` below and for the
76
+ * same reason: the value CHANGES mid-run. The API host is announced by the
77
+ * server (register / mint / join), so a heartbeat started before the
78
+ * announcement would otherwise keep beating at the bootstrap host for the whole
79
+ * session — and the beat is the dominant traffic this whole change exists to
80
+ * move.
81
+ */
82
+ getBaseUrl: () => string;
75
83
  instanceId: string;
76
84
  /** Current instance token — read each tick (follows refresh). */
77
85
  getInstanceToken: () => string;
@@ -111,6 +119,7 @@ export interface InstanceHeartbeatOptions {
111
119
  export function startInstanceHeartbeat(opts: InstanceHeartbeatOptions): HeartbeatHandle {
112
120
  const intervalMs = opts.intervalMs ?? resolveHeartbeatIntervalMs();
113
121
  const log = opts.log ?? ((line: string) => process.stderr.write(line));
122
+ // NB deliberately NOT captured in a local const: it must be re-read per tick.
114
123
  const setTimer =
115
124
  opts.setTimer ?? ((fn: () => void, ms: number) => setInterval(fn, ms) as unknown);
116
125
  const clearTimer =
@@ -135,7 +144,7 @@ export function startInstanceHeartbeat(opts: InstanceHeartbeatOptions): Heartbea
135
144
  if (inFlight) return;
136
145
  inFlight = true;
137
146
  const conversationId = getConversationId();
138
- void beat(opts.baseUrl, opts.instanceId, opts.getInstanceToken(), conversationId)
147
+ void beat(opts.getBaseUrl(), opts.instanceId, opts.getInstanceToken(), conversationId)
139
148
  .then((result) => {
140
149
  if (!result.ok) {
141
150
  log("[viber-channel] instance heartbeat failed (will retry next interval)\n");
package/lib/instance.ts CHANGED
@@ -13,6 +13,13 @@ import { authFilePath, persistInstanceCredentials, type AuthJson } from "./auth.
13
13
  export interface RegisterInstanceResponse {
14
14
  instance_id: string;
15
15
  instance_token: string;
16
+ /**
17
+ * #480 — API origin announced by the server. Optional: an older server (or one
18
+ * with the var unset) simply omits it, and the client keeps its current host.
19
+ * Register is the FIRST authenticated response, hence the earliest chance to
20
+ * adopt — the heartbeat and control stream start right after it.
21
+ */
22
+ api_base_url?: string;
16
23
  }
17
24
 
18
25
  /**
@@ -165,6 +172,13 @@ export interface AcquiredInstance {
165
172
  * `sender_instance_id`; undefined → the self-echo guard fails open (delivers everything).
166
173
  */
167
174
  instance_id?: string;
175
+ /**
176
+ * #480 — the API origin the server announced during register, when this call
177
+ * actually registered. undefined on the paths that reuse an existing token
178
+ * (env-injected or persisted): those make no HTTP call, so there is nothing to
179
+ * announce — the host is then learned at mint/join instead.
180
+ */
181
+ api_base_url?: string;
168
182
  }
169
183
 
170
184
  /**
@@ -212,7 +226,7 @@ export async function acquireInstance(
212
226
  label,
213
227
  instanceKindFromEnv(),
214
228
  );
215
- result = { instance_token: reg.instance_token, instance_key: reg.instance_id, instance_id: reg.instance_id };
229
+ result = { instance_token: reg.instance_token, instance_key: reg.instance_id, instance_id: reg.instance_id, api_base_url: reg.api_base_url };
216
230
  } else if (auth.instance_token !== undefined && auth.instance_token.trim() !== "") {
217
231
  const realId =
218
232
  auth.instance_id !== undefined && auth.instance_id.trim() !== "" ? auth.instance_id : undefined;
@@ -231,7 +245,7 @@ export async function acquireInstance(
231
245
  );
232
246
  persistInstanceCredentials(authFilePath(cwd), reg.instance_id, reg.instance_token, log);
233
247
  log(`[viber-channel] instance: registered + persisted (id=${reg.instance_id})\n`);
234
- result = { instance_token: reg.instance_token, instance_key: reg.instance_id, instance_id: reg.instance_id };
248
+ result = { instance_token: reg.instance_token, instance_key: reg.instance_id, instance_id: reg.instance_id, api_base_url: reg.api_base_url };
235
249
  }
236
250
  }
237
251
 
package/lib/lockfile.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  */
24
24
  import { createHash } from "node:crypto";
25
25
  import { join } from "node:path";
26
+ import { assertHashKey } from "./hash_key.js";
26
27
 
27
28
  /**
28
29
  * Return the lock file path for a given base URL, fingerprint, and session id,
@@ -42,6 +43,14 @@ export function lockFilePath(
42
43
  sessionId: string,
43
44
  lockDir: string,
44
45
  ): string {
46
+ // #480: this repo has NO typecheck over viber-channel (no tsconfig), so a
47
+ // caller omitting the field in an object literal ships silently and we hash
48
+ // the string "undefined" — every agent then converges on the SAME lock and
49
+ // handle, cross-talking between projects. Cheap runtime guard instead of
50
+ // trusting a compiler that never runs.
51
+ assertHashKey(baseUrl, "lockFilePath(baseUrl)", { allowEmpty: false });
52
+ assertHashKey(fingerprint, "lockFilePath(fingerprint)");
53
+ assertHashKey(sessionId, "lockFilePath(sessionId)");
45
54
  const suffix = createHash("sha256")
46
55
  .update(`${baseUrl}\n${fingerprint}\n${sessionId}`)
47
56
  .digest("hex")
package/lib/urls.ts CHANGED
@@ -32,9 +32,12 @@ export function isTrustedViberOrigin(origin: string): boolean {
32
32
  if (u.protocol === "http:" && isLocalhost) return true;
33
33
  if (u.protocol !== "https:") return false;
34
34
  if (host === "viber.dgypx.dev" || host === "viber-dev.dgypx.dev") return true;
35
- // Explicitly-configured base (self-host / dev override) — matched by origin.
36
- const configured = process.env.VIBER_BASE_URL;
37
- if (configured) {
35
+ // #480: the agent API hosts. Hard-coded on purpose — see the warning below.
36
+ if (host === "viber-api-staging.dgypx.dev") return true;
37
+ // Explicitly-configured bases (self-host / dev override) — matched by origin.
38
+ // Both are LOCAL env vars, i.e. already trusted input.
39
+ for (const configured of [process.env.VIBER_BASE_URL, process.env.VIBER_API_BASE_URL]) {
40
+ if (!configured) continue;
38
41
  try {
39
42
  if (new URL(configured).origin === u.origin) return true;
40
43
  } catch {
@@ -43,3 +46,21 @@ export function isTrustedViberOrigin(origin: string): boolean {
43
46
  }
44
47
  return false;
45
48
  }
49
+
50
+ /**
51
+ * ⚠️ #480 — THIS ALLOWLIST MUST STAY STATIC.
52
+ *
53
+ * It is what stops a forged or compromised announcement from redirecting an agent
54
+ * to an attacker's host, where the client would then send its `project_token`,
55
+ * `instance_token`, `conversation_token` and — for runners — its `runner_token`,
56
+ * which is a local-code-execution capability.
57
+ *
58
+ * So it may only ever be fed:
59
+ * - hosts hard-coded above, and
60
+ * - the origin of a LOCAL env var (`VIBER_BASE_URL`, `VIBER_API_BASE_URL`).
61
+ *
62
+ * It must NEVER be fed a server-announced `api_base_url`. That would be circular:
63
+ * the value being checked would authorize itself, and this function would protect
64
+ * nothing while still looking like a security control. If a new deployment needs
65
+ * another host, add the literal here — in a reviewed commit.
66
+ */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viber-channel",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "description": "Voice + text MCP channel between a Claude Code session and the Viber UI (https://viber.dgypx.dev). Push transcripts to Claude; send_message tool delivers text back to the UI.",
5
5
  "type": "module",
6
6
  "bin": {