send-to-paseo 1.3.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.
@@ -0,0 +1,288 @@
1
+ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+ import {
7
+ DEFAULT_PORT,
8
+ ExternalBridgeUrlSchema,
9
+ RecentSendSchema,
10
+ type RecentSend,
11
+ } from "../shared/contracts";
12
+
13
+ /**
14
+ * The bridge's own state: the pairing token, the port, the default provider
15
+ * and a short send history for the Paseo surface.
16
+ *
17
+ * The token controls an endpoint that can start agents, so the file is written
18
+ * `0600` inside a `0700` directory and is never logged, echoed into an error,
19
+ * or included in a status payload. Only the explicit reveal RPC returns it.
20
+ */
21
+
22
+ const SettingsSchema = z.object({
23
+ version: z.literal(1),
24
+ token: z.string().min(1),
25
+ port: z.number().int().min(1).max(65535),
26
+ /** `provider/model`, or null to follow the daemon's own default. */
27
+ defaultProvider: z.string().nullable(),
28
+ /**
29
+ * A Paseo agent profile id (`daemon.agentProfiles[].id`) to follow, or null.
30
+ *
31
+ * Both of these are `.default(null)` rather than required so that a
32
+ * settings.json written before permission modes existed still validates. A
33
+ * failed parse regenerates the file — and with it the pairing token — which
34
+ * would silently unpair the extension on upgrade.
35
+ */
36
+ defaultProfileId: z.string().nullable().default(null),
37
+ /** Permission mode override, or null to follow the resolution chain. */
38
+ defaultModeId: z.string().nullable().default(null),
39
+ /** Create a fresh agent, or reuse the best root agent in the target workspace. */
40
+ agentDispatch: z.enum(["new", "main"]).default("new"),
41
+ /** Advisory: flipped true after the first authenticated request succeeds. */
42
+ paired: z.boolean(),
43
+ /** Newest first, capped at RECENT_LIMIT. */
44
+ recentSends: z.array(RecentSendSchema),
45
+ /**
46
+ * When non-empty, only these `chrome-extension://<id>` origins are accepted.
47
+ * Empty means any extension origin, which is the documented default.
48
+ */
49
+ allowedExtensionIds: z.array(z.string()),
50
+ /**
51
+ * Extra `Host` header values this bridge will answer on, beyond loopback.
52
+ *
53
+ * Exact `host:port` matches, empty by default. Only needed when a reverse
54
+ * proxy that presents a real name (Tailscale Serve, a corporate ingress)
55
+ * fronts the bridge; a plain `ssh -L` tunnel already arrives as loopback and
56
+ * needs nothing here. `.default([])` for the same reason as the fields above:
57
+ * a settings.json written before this existed must still validate, or the
58
+ * parse failure would regenerate the file and silently rotate the pairing
59
+ * token on upgrade.
60
+ *
61
+ * File-only, with no UI, because this is the advanced multi-name escape
62
+ * hatch. Normal remote setup uses the single, validated
63
+ * `externalBridgeUrl` below — see `hostAllowed` in server/bridge.ts.
64
+ */
65
+ allowedHosts: z.array(z.string()).default([]),
66
+ /**
67
+ * HTTPS origin of a reverse proxy the user explicitly configured in Paseo.
68
+ * The listener remains on loopback; this only authorizes the proxy's Host
69
+ * header. Null keeps the default local-only posture.
70
+ */
71
+ externalBridgeUrl: ExternalBridgeUrlSchema.nullable().default(null),
72
+ /**
73
+ * Plaintext password for a Paseo daemon that requires one, or null.
74
+ *
75
+ * A daemon listening on anything but loopback enables `daemon.auth.password`,
76
+ * and then it rejects an unauthenticated WebSocket outright — without this the
77
+ * plugin lists no providers or modes and every send fails. What `config.json`
78
+ * holds is a bcrypt hash, so the plaintext cannot be derived and has to be
79
+ * given here (or through an environment variable or the VM secret file).
80
+ *
81
+ * Treated exactly like `token`: file-only with no UI, 0600, never logged,
82
+ * never echoed into an error, and never part of a status payload. See
83
+ * `resolvePassword` in server/daemon.ts.
84
+ */
85
+ daemonPassword: z.string().nullable().default(null),
86
+ /** Additional Paseo machines this plugin routes browser requests to. */
87
+ additionalMachines: z
88
+ .array(
89
+ z.object({
90
+ id: z.string().min(1),
91
+ /** Added in v1.2.0; learned from a new code or the next authenticated ping. */
92
+ serverId: z.string().nullable().default(null),
93
+ label: z.string(),
94
+ bridgeUrl: ExternalBridgeUrlSchema,
95
+ token: z.string().min(1),
96
+ enabled: z.boolean(),
97
+ machineName: z.string().default(""),
98
+ }),
99
+ )
100
+ .default([]),
101
+ });
102
+
103
+ export type Settings = z.infer<typeof SettingsSchema>;
104
+
105
+ const RECENT_LIMIT = 20;
106
+
107
+ function dataDir(): string {
108
+ const home = process.env.PASEO_HOME ?? join(homedir(), ".paseo");
109
+ return join(home, "plugin-data", "send-to-paseo");
110
+ }
111
+
112
+ const filePath = () => join(dataDir(), "settings.json");
113
+
114
+ function newToken(): string {
115
+ return randomBytes(32).toString("base64url");
116
+ }
117
+
118
+ function defaults(): Settings {
119
+ return {
120
+ version: 1,
121
+ token: newToken(),
122
+ port: DEFAULT_PORT,
123
+ defaultProvider: null,
124
+ defaultProfileId: null,
125
+ defaultModeId: null,
126
+ agentDispatch: "new",
127
+ paired: false,
128
+ recentSends: [],
129
+ allowedExtensionIds: [],
130
+ allowedHosts: [],
131
+ externalBridgeUrl: null,
132
+ daemonPassword: null,
133
+ additionalMachines: [],
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Single-writer store. HTTP requests and RPC handlers share one process, so a
139
+ * promise chain is enough to keep read-modify-write sequences from interleaving
140
+ * and losing a token rotation.
141
+ */
142
+ let tail: Promise<unknown> = Promise.resolve();
143
+
144
+ function serialize<T>(work: () => Promise<T>): Promise<T> {
145
+ const next = tail.then(work, work);
146
+ tail = next.then(
147
+ () => undefined,
148
+ () => undefined,
149
+ );
150
+ return next;
151
+ }
152
+
153
+ /** In-memory copy so the hot auth path never touches the filesystem. */
154
+ let cached: Settings | null = null;
155
+
156
+ async function load(): Promise<Settings> {
157
+ if (cached !== null) return cached;
158
+ let parsed: Settings | null = null;
159
+ try {
160
+ const raw = await readFile(filePath(), "utf8");
161
+ const result = SettingsSchema.safeParse(JSON.parse(raw));
162
+ if (result.success) {
163
+ parsed = result.data;
164
+ } else {
165
+ // Never log the file contents; it holds the token.
166
+ console.error("[send-to-paseo] settings failed validation; regenerating");
167
+ }
168
+ } catch (error) {
169
+ const code = (error as NodeJS.ErrnoException).code;
170
+ if (code !== "ENOENT") {
171
+ console.error("[send-to-paseo] could not read settings; regenerating", code ?? "unknown");
172
+ }
173
+ }
174
+ if (parsed === null) {
175
+ parsed = defaults();
176
+ await persist(parsed);
177
+ console.log("[send-to-paseo] generated a new pairing token");
178
+ }
179
+ cached = parsed;
180
+ return parsed;
181
+ }
182
+
183
+ async function persist(settings: Settings): Promise<void> {
184
+ const dir = dataDir();
185
+ await mkdir(dir, { recursive: true, mode: 0o700 });
186
+ await chmod(dir, 0o700).catch(() => undefined);
187
+ const target = filePath();
188
+ const temp = `${target}.${randomUUID()}.tmp`;
189
+ await writeFile(temp, JSON.stringify(settings, null, 2), { encoding: "utf8", mode: 0o600 });
190
+ await chmod(temp, 0o600);
191
+ await rename(temp, target);
192
+ cached = settings;
193
+ }
194
+
195
+ export const settings = {
196
+ read: (): Promise<Settings> => serialize(load),
197
+
198
+ /** Applies a partial patch and persists. Returns the new settings. */
199
+ update: (patch: Partial<Omit<Settings, "version">>): Promise<Settings> =>
200
+ serialize(async () => {
201
+ const current = await load();
202
+ const next: Settings = { ...current, ...patch, version: 1 };
203
+ await persist(next);
204
+ return next;
205
+ }),
206
+
207
+ regenerateToken: (): Promise<Settings> =>
208
+ serialize(async () => {
209
+ const current = await load();
210
+ // Rotation also un-pairs: the old extension copy no longer works.
211
+ const next: Settings = { ...current, token: newToken(), paired: false };
212
+ await persist(next);
213
+ console.log("[send-to-paseo] pairing token regenerated");
214
+ return next;
215
+ }),
216
+
217
+ markPaired: (): Promise<void> =>
218
+ serialize(async () => {
219
+ const current = await load();
220
+ if (current.paired) return;
221
+ await persist({ ...current, paired: true });
222
+ }),
223
+
224
+ recordSend: (entry: Omit<RecentSend, "id" | "at">): Promise<void> =>
225
+ serialize(async () => {
226
+ const current = await load();
227
+ const row: RecentSend = { id: randomUUID(), at: new Date().toISOString(), ...entry };
228
+ const recentSends = [row, ...current.recentSends].slice(0, RECENT_LIMIT);
229
+ await persist({ ...current, recentSends });
230
+ }),
231
+
232
+ clearRecentSends: (): Promise<number> =>
233
+ serialize(async () => {
234
+ const current = await load();
235
+ const removed = current.recentSends.length;
236
+ if (removed > 0) await persist({ ...current, recentSends: [] });
237
+ return removed;
238
+ }),
239
+
240
+ addAdditionalMachine: (machine: Settings["additionalMachines"][number]): Promise<Settings> =>
241
+ serialize(async () => {
242
+ const current = await load();
243
+ const additionalMachines = [
244
+ ...current.additionalMachines.filter((item) => item.id !== machine.id),
245
+ machine,
246
+ ];
247
+ const next = { ...current, additionalMachines };
248
+ await persist(next);
249
+ return next;
250
+ }),
251
+
252
+ updateAdditionalMachine: (
253
+ id: string,
254
+ patch: Partial<Omit<Settings["additionalMachines"][number], "id" | "token" | "bridgeUrl">>,
255
+ ): Promise<Settings> =>
256
+ serialize(async () => {
257
+ const current = await load();
258
+ const additionalMachines = current.additionalMachines.map((item) =>
259
+ item.id === id ? { ...item, ...patch } : item,
260
+ );
261
+ const next = { ...current, additionalMachines };
262
+ await persist(next);
263
+ return next;
264
+ }),
265
+
266
+ removeAdditionalMachine: (id: string): Promise<boolean> =>
267
+ serialize(async () => {
268
+ const current = await load();
269
+ const additionalMachines = current.additionalMachines.filter((item) => item.id !== id);
270
+ if (additionalMachines.length === current.additionalMachines.length) return false;
271
+ await persist({ ...current, additionalMachines });
272
+ return true;
273
+ }),
274
+ };
275
+
276
+ /** Constant-time bearer comparison, so a wrong token leaks no timing signal. */
277
+ export function tokenMatches(expected: string, presented: string): boolean {
278
+ const a = Buffer.from(expected, "utf8");
279
+ const b = Buffer.from(presented, "utf8");
280
+ if (a.length !== b.length) return false;
281
+ return timingSafeEqual(a, b);
282
+ }
283
+
284
+ /** `Cg7x…9fQk`: enough to tell two tokens apart, not enough to use one. */
285
+ export function previewToken(token: string): string {
286
+ if (token.length <= 12) return "•".repeat(token.length);
287
+ return `${token.slice(0, 4)}…${token.slice(-4)}`;
288
+ }
@@ -0,0 +1,6 @@
1
+ import { requireServerId } from "./daemon";
2
+ import { assertServerTarget } from "../shared/host-target";
3
+
4
+ export async function requireServerTarget(requestedServerId: string): Promise<void> {
5
+ assertServerTarget(requestedServerId, await requireServerId());
6
+ }