@wkqco33/pi-remote-control 0.2.0 → 0.2.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkqco33/pi-remote-control",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Remote control extension for pi coding agent: stream live sessions, steer/followUp prompts, and approve tool calls from a web relay server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,41 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { loadExtensionConfig } from "./config-loader.js";
6
+
7
+ describe("loadExtensionConfig", () => {
8
+ let root: string;
9
+ const write = async (path: string, body: object) => {
10
+ await mkdir(dirname(path), { recursive: true });
11
+ await writeFile(path, JSON.stringify(body));
12
+ };
13
+ const load = (projectTrusted: boolean, env: Record<string, string> = {}) =>
14
+ loadExtensionConfig({ cwd: join(root, "repo"), homeDir: join(root, "home"), configDirName: ".pi", projectTrusted, env });
15
+
16
+ beforeEach(async () => {
17
+ root = await mkdtemp(join(tmpdir(), "remote-config-"));
18
+ await write(join(root, "home/.pi/agent/remote-control.json"), { serverUrl: "wss://mine/ws/agent" });
19
+ await write(join(root, "repo/.pi/remote-control.json"), { serverUrl: "wss://theirs/ws/agent", requirePairing: true });
20
+ });
21
+ afterEach(() => rm(root, { recursive: true, force: true }));
22
+
23
+ it("does not apply an untrusted project file", async () => {
24
+ const { config, warnings } = await load(false);
25
+ expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: false });
26
+ expect(warnings.join()).toContain("not trusted");
27
+ });
28
+
29
+ it("applies only the tightening values of a trusted project", async () => {
30
+ const { config, warnings } = await load(true);
31
+ expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: true });
32
+ expect(warnings.join()).toContain("serverUrl");
33
+ });
34
+
35
+ it("reads only the file named by PI_REMOTE_CONFIG", async () => {
36
+ const path = join(root, "chosen.json");
37
+ await write(path, { serverUrl: "wss://chosen/ws/agent" });
38
+ const { config } = await load(true, { PI_REMOTE_CONFIG: path });
39
+ expect(config).toMatchObject({ serverUrl: "wss://chosen/ws/agent", requirePairing: false });
40
+ });
41
+ });
@@ -0,0 +1,71 @@
1
+ /** Reads the extension configuration files. */
2
+
3
+ import { readFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import {
6
+ applyProjectConfig,
7
+ parseRemoteConfig,
8
+ resolveRemoteConfig,
9
+ type ParsedConfigResult,
10
+ type RemoteControlConfig,
11
+ } from "./config.js";
12
+
13
+ export interface ConfigLoadOptions {
14
+ readonly cwd: string;
15
+ readonly homeDir: string;
16
+ /** pi's config directory name, ".pi". */
17
+ readonly configDirName: string;
18
+ readonly projectTrusted: boolean;
19
+ readonly env: Record<string, string | undefined>;
20
+ }
21
+
22
+ export interface LoadedConfig {
23
+ readonly config: RemoteControlConfig;
24
+ readonly warnings: string[];
25
+ }
26
+
27
+ /** Returns null when the file does not exist or cannot be used. */
28
+ async function readConfigFile(path: string, warnings: string[]): Promise<ParsedConfigResult | null> {
29
+ try {
30
+ const parsed = parseRemoteConfig(JSON.parse(await readFile(path, "utf8")) as unknown);
31
+ warnings.push(...parsed.warnings);
32
+ return parsed;
33
+ } catch (error) {
34
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
35
+ warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
36
+ }
37
+ return null;
38
+ }
39
+ }
40
+
41
+ export async function loadExtensionConfig(options: ConfigLoadOptions): Promise<LoadedConfig> {
42
+ const warnings: string[] = [];
43
+ // PI_REMOTE_CONFIG is chosen by the user, so it replaces both files.
44
+ const override = options.env.PI_REMOTE_CONFIG?.trim();
45
+ const userPath = override || join(options.homeDir, options.configDirName, "agent", "remote-control.json");
46
+ const userFile = await readConfigFile(userPath, warnings);
47
+ const config = resolveRemoteConfig(userFile?.config ?? {}, options.env);
48
+ if (override) return { config, warnings };
49
+
50
+ const projectPath = join(options.cwd, options.configDirName, "remote-control.json");
51
+ if (resolve(projectPath) === resolve(userPath)) return { config, warnings };
52
+ // The project file comes with the repository, which the user may not control.
53
+ const projectWarnings: string[] = [];
54
+ const projectFile = await readConfigFile(projectPath, projectWarnings);
55
+ if (!options.projectTrusted) {
56
+ if (projectFile || projectWarnings.length > 0) {
57
+ warnings.push(`ignored ${projectPath} because the project is not trusted`);
58
+ }
59
+ return { config, warnings };
60
+ }
61
+ warnings.push(...projectWarnings);
62
+ if (!projectFile) return { config, warnings };
63
+
64
+ const applied = applyProjectConfig(config, projectFile.config);
65
+ if (applied.ignored.length > 0) {
66
+ warnings.push(
67
+ `ignored in ${projectPath}: ${applied.ignored.join(", ")} (project config may only tighten security; set these in ${userPath})`,
68
+ );
69
+ }
70
+ return { config: applied.config, warnings };
71
+ }
package/src/config.ts CHANGED
@@ -96,6 +96,39 @@ export function resolveRemoteConfig(
96
96
  };
97
97
  }
98
98
 
99
+ const POLICY_STRICTNESS: Record<RemoteToolPolicy, number> = { unrestricted: 0, "read-only": 1, "no-tools": 2 };
100
+ // "local" needs someone at the terminal, so it is stricter than "web".
101
+ const APPROVAL_STRICTNESS: Record<RemoteToolApproval, number> = { off: 0, web: 1, local: 2 };
102
+
103
+ type ProjectRule<Key extends keyof RemoteControlConfig> = (
104
+ value: RemoteControlConfig[Key],
105
+ current: RemoteControlConfig[Key],
106
+ ) => boolean;
107
+
108
+ /** Keys a project may set, and when its value is at least as strict. All other keys belong to the user. */
109
+ const PROJECT_RULES: { readonly [Key in keyof RemoteControlConfig]?: ProjectRule<Key> } = {
110
+ requirePairing: (value, current) => value || !current,
111
+ remoteToolPolicy: (value, current) => POLICY_STRICTNESS[value] >= POLICY_STRICTNESS[current],
112
+ remoteToolApproval: (value, current) => APPROVAL_STRICTNESS[value] >= APPROVAL_STRICTNESS[current],
113
+ approvalTimeoutMs: (value, current) => value <= current,
114
+ pairingTtlMs: (value, current) => value <= current,
115
+ };
116
+
117
+ /** Layers a repository's config over the user's without letting it weaken or redirect anything. */
118
+ export function applyProjectConfig(
119
+ base: RemoteControlConfig,
120
+ project: Partial<RemoteControlConfig>,
121
+ ): { config: RemoteControlConfig; ignored: string[] } {
122
+ const accepted: Record<string, unknown> = {};
123
+ const ignored: string[] = [];
124
+ for (const key of Object.keys(project) as (keyof RemoteControlConfig)[]) {
125
+ const rule = PROJECT_RULES[key] as ((value: unknown, current: unknown) => boolean) | undefined;
126
+ if (rule?.(project[key], base[key])) accepted[key] = project[key];
127
+ else ignored.push(key);
128
+ }
129
+ return { config: { ...base, ...(accepted as Partial<RemoteControlConfig>) }, ignored };
130
+ }
131
+
99
132
  export function expandHomePath(filePath: string, homeDir: string): string {
100
133
  const trimmed = filePath.trim();
101
134
  if (trimmed === "~") return homeDir;
package/src/index.ts CHANGED
@@ -5,17 +5,15 @@
5
5
 
6
6
  import { readFile, stat } from "node:fs/promises";
7
7
  import { homedir, hostname } from "node:os";
8
- import { join } from "node:path";
9
8
  import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
10
9
  import { RemoteBridge, type RemoteHost } from "./client/remote-bridge.js";
11
10
  import { WsClient } from "./client/ws-client.js";
12
11
  import {
13
12
  expandHomePath,
14
- parseRemoteConfig,
15
13
  parseTokenFileContent,
16
- resolveRemoteConfig,
17
14
  type RemoteControlConfig,
18
15
  } from "./config.js";
16
+ import { loadExtensionConfig } from "./config-loader.js";
19
17
  import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
20
18
  import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
21
19
  import { formatFooterLabel, formatStatusReport } from "./core/status.js";
@@ -29,35 +27,6 @@ import {
29
27
 
30
28
  const EXTENSION_KEY = "remote-control";
31
29
 
32
- async function loadExtensionConfig(cwd: string): Promise<{ config: RemoteControlConfig; warnings: string[] }> {
33
- const warnings: string[] = [];
34
- let merged: Partial<RemoteControlConfig> = {};
35
-
36
- const override = process.env.PI_REMOTE_CONFIG?.trim();
37
- const paths = override
38
- ? [override]
39
- : [
40
- join(homedir(), CONFIG_DIR_NAME, "agent", "remote-control.json"),
41
- join(cwd, CONFIG_DIR_NAME, "remote-control.json"),
42
- ];
43
-
44
- for (const path of paths) {
45
- try {
46
- const raw = await readFile(path, "utf8");
47
- const parsed = parseRemoteConfig(JSON.parse(raw) as unknown);
48
- warnings.push(...parsed.warnings);
49
- merged = { ...merged, ...parsed.config };
50
- } catch (error) {
51
- const code = (error as NodeJS.ErrnoException).code;
52
- if (code !== "ENOENT") {
53
- warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
54
- }
55
- }
56
- }
57
-
58
- return { config: resolveRemoteConfig(merged), warnings };
59
- }
60
-
61
30
  async function loadServerToken(config: RemoteControlConfig, warnings: string[]): Promise<string> {
62
31
  const envToken = process.env[config.tokenEnv]?.trim();
63
32
  if (envToken) {
@@ -157,7 +126,13 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
157
126
 
158
127
  pi.on("session_start", async (_event, ctx) => {
159
128
  sessionCtx = ctx;
160
- const { config, warnings } = await loadExtensionConfig(ctx.cwd);
129
+ const { config, warnings } = await loadExtensionConfig({
130
+ cwd: ctx.cwd,
131
+ homeDir: homedir(),
132
+ configDirName: CONFIG_DIR_NAME,
133
+ projectTrusted: ctx.isProjectTrusted(),
134
+ env: process.env,
135
+ });
161
136
  await refreshBranch(ctx.cwd);
162
137
  const serverToken = await loadServerToken(config, warnings);
163
138
 
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { applyProjectConfig, parseRemoteConfig, resolveRemoteConfig } from "./config.js";
3
+
4
+ const user = resolveRemoteConfig({ serverUrl: "wss://relay.example/ws/agent", remoteToolApproval: "web" }, {});
5
+ const apply = (project: unknown, base = user) => applyProjectConfig(base, parseRemoteConfig(project).config);
6
+
7
+ describe("applyProjectConfig", () => {
8
+ it("never lets a project choose the relay or the credentials", () => {
9
+ const { config, ignored } = apply({
10
+ serverUrl: "wss://other.example/ws/agent",
11
+ tokenEnv: "OTHER_SECRET",
12
+ tokenFile: "~/.ssh/id_ed25519",
13
+ });
14
+ expect(config).toEqual(user);
15
+ expect(ignored).toEqual(["serverUrl", "tokenEnv", "tokenFile"]);
16
+ });
17
+
18
+ it("ignores values that would weaken the user's protection", () => {
19
+ const strict = { ...user, requirePairing: true, remoteToolPolicy: "read-only" as const, remoteToolApproval: "local" as const };
20
+ const { config, ignored } = apply(
21
+ {
22
+ requirePairing: false,
23
+ remoteToolPolicy: "unrestricted",
24
+ remoteToolApproval: "web",
25
+ approvalTimeoutMs: 300_000,
26
+ pairingTtlMs: 3_600_000,
27
+ },
28
+ strict,
29
+ );
30
+ expect(config).toEqual(strict);
31
+ expect(ignored).toHaveLength(5);
32
+ });
33
+
34
+ it("accepts stricter values", () => {
35
+ const { config, ignored } = apply({
36
+ requirePairing: true,
37
+ remoteToolPolicy: "no-tools",
38
+ remoteToolApproval: "local",
39
+ approvalTimeoutMs: 10_000,
40
+ pairingTtlMs: 20_000,
41
+ });
42
+ expect(config).toMatchObject({
43
+ requirePairing: true,
44
+ remoteToolPolicy: "no-tools",
45
+ remoteToolApproval: "local",
46
+ approvalTimeoutMs: 10_000,
47
+ pairingTtlMs: 20_000,
48
+ });
49
+ expect(ignored).toEqual([]);
50
+ });
51
+ });