peekable 0.6.0 → 0.6.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.
@@ -0,0 +1,8 @@
1
+ export type CliUpdateNotice = {
2
+ current: string;
3
+ latest: string;
4
+ min: string;
5
+ action: "recommended" | "required";
6
+ };
7
+ export declare function readCliUpdate(data: unknown): CliUpdateNotice | null;
8
+ export declare function warnCliUpdateToStderr(notice: CliUpdateNotice): void;
@@ -0,0 +1,34 @@
1
+ // Surfaces the server's "your CLI is stale" notice that rides on the
2
+ // session-create response (see src/cliVersion.ts server-side). A published CLI
3
+ // can silently lag the server's capabilities; this makes that visible to both
4
+ // humans (stderr) and agents (the --json payload) at the moment a session
5
+ // starts. The fix is always `npm i -g peekable@latest` — never `peekable
6
+ // upgrade`, which is the billing command.
7
+ // Extract and validate the notice from a session-create response body.
8
+ // Returns null when absent or malformed — a missing notice must never break
9
+ // the command.
10
+ export function readCliUpdate(data) {
11
+ if (!data || typeof data !== "object")
12
+ return null;
13
+ const u = data.cli_update;
14
+ if (!u || typeof u !== "object")
15
+ return null;
16
+ const notice = u;
17
+ if (typeof notice.current !== "string" || typeof notice.latest !== "string")
18
+ return null;
19
+ return {
20
+ current: notice.current,
21
+ latest: notice.latest,
22
+ min: typeof notice.min === "string" ? notice.min : notice.latest,
23
+ action: notice.action === "required" ? "required" : "recommended",
24
+ };
25
+ }
26
+ // Human-facing warning printed to stderr (so it never pollutes --json stdout).
27
+ // Non-blocking: the command still runs on a stale CLI.
28
+ export function warnCliUpdateToStderr(notice) {
29
+ const lead = notice.action === "required"
30
+ ? `⚠ Your Peekable CLI (v${notice.current}) is out of date — some features (e.g. tunnelling apps that call their own backend) may not work until you update.`
31
+ : `↑ A newer Peekable CLI is available (v${notice.current} → v${notice.latest}).`;
32
+ console.error(lead);
33
+ console.error(" Update: npm i -g peekable@latest");
34
+ }
@@ -3,21 +3,27 @@ import { requireConfig } from "../config.js";
3
3
  import { api } from "../api.js";
4
4
  import { CommandFailure, printCommandError } from "../command-error.js";
5
5
  import { runWithTelemetry } from "../telemetry.js";
6
+ import { readCliUpdate, warnCliUpdateToStderr } from "../cliUpdateNotice.js";
6
7
  export const createCommand = new Command("create")
7
8
  .argument("<name>", "Session name")
8
9
  .description("Create a new sharing session")
9
10
  .option("--json", "Output JSON")
11
+ .option("--no-slug", "Use an opaque hostname that omits the session name (for sensitive shares)")
10
12
  .action(async (name, opts) => {
11
13
  await runWithTelemetry("create", async () => {
12
14
  try {
13
15
  const config = requireConfig();
14
- const data = await api(config, "POST", "/sessions", { name });
16
+ const data = await api(config, "POST", "/sessions", { name, slug: opts.slug });
17
+ const cliUpdate = readCliUpdate(data);
15
18
  if (opts.json) {
19
+ // data already carries cli_update when present; agents read it there.
16
20
  console.log(JSON.stringify(data));
17
21
  }
18
22
  else {
19
23
  console.log(`Created session: ${data.id}`);
20
24
  console.log(`URL: ${data.url}`);
25
+ if (cliUpdate)
26
+ warnCliUpdateToStderr(cliUpdate);
21
27
  }
22
28
  }
23
29
  catch (err) {
@@ -1,2 +1,3 @@
1
1
  import { Command } from "commander";
2
2
  export declare const proxyCommand: Command;
3
+ export declare function handleRequest(ws: WebSocket, msg: any, port: number, inflight: Map<string, AbortController>, fallbackPorts: Set<number>, pathPortCache: Map<string, number>, jsonOutput?: boolean): Promise<void>;
@@ -4,6 +4,7 @@ import { requireConfig } from "../config.js";
4
4
  import { api } from "../api.js";
5
5
  import { CommandFailure, printCommandError } from "../command-error.js";
6
6
  import { postStartEvent, postFireAndForgetDebugEvent } from "../telemetry.js";
7
+ import { readCliUpdate, warnCliUpdateToStderr } from "../cliUpdateNotice.js";
7
8
  const MAX_RESPONSE_BYTES = 25 * 1024 * 1024; // 25 MB
8
9
  const TEXT_CONTENT_TYPES = [
9
10
  "text/",
@@ -34,6 +35,7 @@ export const proxyCommand = new Command("proxy")
34
35
  // Create or reuse session
35
36
  let sessionId;
36
37
  let shareUrl;
38
+ let cliUpdate = null;
37
39
  if (opts.session) {
38
40
  sessionId = opts.session;
39
41
  const baseDomain = new URL(config.url).hostname;
@@ -54,12 +56,16 @@ export const proxyCommand = new Command("proxy")
54
56
  }
55
57
  sessionId = data.id;
56
58
  shareUrl = data.url;
59
+ cliUpdate = readCliUpdate(data);
57
60
  }
58
61
  if (opts.json) {
59
- console.log(JSON.stringify({ id: sessionId, url: shareUrl }));
62
+ // Agents read cli_update here to prompt the user to update.
63
+ console.log(JSON.stringify({ id: sessionId, url: shareUrl, ...(cliUpdate ? { cli_update: cliUpdate } : {}) }));
60
64
  }
61
65
  else {
62
66
  console.log(`Share URL: ${shareUrl}`);
67
+ if (cliUpdate)
68
+ warnCliUpdateToStderr(cliUpdate);
63
69
  }
64
70
  postStartEvent("cli_proxy_started", { session_id: sessionId, port });
65
71
  // Connect relay WebSocket
@@ -77,6 +83,7 @@ export const proxyCommand = new Command("proxy")
77
83
  const wsStartedAt = Date.now();
78
84
  const inflight = new Map();
79
85
  const fallbackPorts = new Set();
86
+ const pathPortCache = new Map();
80
87
  ws.addEventListener("open", () => {
81
88
  ws.send(JSON.stringify({
82
89
  type: "auth",
@@ -122,7 +129,7 @@ export const proxyCommand = new Command("proxy")
122
129
  return;
123
130
  }
124
131
  if (msg.type === "request") {
125
- await handleRequest(ws, msg, port, inflight, fallbackPorts, opts.json);
132
+ await handleRequest(ws, msg, port, inflight, fallbackPorts, pathPortCache, opts.json);
126
133
  }
127
134
  });
128
135
  ws.addEventListener("close", (event) => {
@@ -174,12 +181,18 @@ export const proxyCommand = new Command("proxy")
174
181
  setTimeout(() => process.exit(0), 200);
175
182
  });
176
183
  });
177
- async function handleRequest(ws, msg, port, inflight, fallbackPorts, jsonOutput) {
184
+ // Bounds pathPortCache so a long-lived session with many distinct paths can't
185
+ // grow it without limit; oldest entries are evicted first (Map insertion order).
186
+ const MAX_PATH_PORT_CACHE = 512;
187
+ export async function handleRequest(ws, msg, port, inflight, fallbackPorts, pathPortCache, jsonOutput) {
178
188
  const ac = new AbortController();
179
189
  inflight.set(msg.id, ac);
180
190
  try {
181
- const url = `http://localhost:${port}${msg.path}`;
182
- // Build headers, skip host and x-forwarded-*
191
+ // Build headers, skip host and x-forwarded-*. Origin is always stamped as
192
+ // the PRIMARY port: a real browser tab on localhost:<primary> calling any
193
+ // backend port sends Origin http://localhost:<primary>. APIs with origin
194
+ // allowlists (better-auth trustedOrigins, CORS) reject a fabricated
195
+ // per-backend origin — that 403 broke login through tunnels.
183
196
  const headers = new Headers();
184
197
  if (Array.isArray(msg.headers)) {
185
198
  for (const [k, v] of msg.headers) {
@@ -189,7 +202,6 @@ async function handleRequest(ws, msg, port, inflight, fallbackPorts, jsonOutput)
189
202
  headers.set(k, v);
190
203
  }
191
204
  }
192
- headers.set("host", `localhost:${port}`);
193
205
  headers.set("origin", `http://localhost:${port}`);
194
206
  headers.set("accept-encoding", "identity");
195
207
  // Decode body
@@ -201,49 +213,84 @@ async function handleRequest(ws, msg, port, inflight, fallbackPorts, jsonOutput)
201
213
  bytes[i] = binary.charCodeAt(i);
202
214
  body = bytes.buffer;
203
215
  }
204
- let upstream = await fetch(url, {
205
- method: msg.method ?? "GET",
206
- headers,
207
- body: body,
208
- redirect: "manual",
209
- signal: ac.signal,
210
- });
211
- // Detect when primary port can't handle the request — try fallback ports.
212
- // Key signal: response is HTML but request didn't ask for HTML (fetch vs navigation)
213
- const upstreamCt = upstream.headers.get("content-type") ?? "";
214
216
  const method = (msg.method ?? "GET").toUpperCase();
215
- const requestAccept = (Array.isArray(msg.headers) ? msg.headers.find(([k]) => k.toLowerCase() === "accept")?.[1] : "") ?? "";
216
- const requestExpectsHtml = requestAccept.includes("text/html");
217
- const isModifyingMethod = method !== "GET" && method !== "HEAD";
218
- const gotUnexpectedHtml = upstreamCt.includes("text/html") && !requestExpectsHtml;
219
- const shouldTryFallback = (gotUnexpectedHtml || isModifyingMethod) && fallbackPorts.size > 0;
220
- if (shouldTryFallback) {
221
- for (const fbPort of fallbackPorts) {
222
- if (fbPort === port)
223
- continue;
224
- try {
225
- const fbHeaders = new Headers(headers);
226
- fbHeaders.set("host", `localhost:${fbPort}`);
227
- fbHeaders.set("origin", `http://localhost:${fbPort}`);
228
- const fbUrl = `http://localhost:${fbPort}${msg.path}`;
229
- const fbResp = await fetch(fbUrl, {
230
- method: msg.method ?? "GET",
231
- headers: fbHeaders,
232
- body: body,
233
- redirect: "manual",
234
- signal: ac.signal,
235
- });
236
- if (fbResp.status !== 404) {
237
- // Fallback port handled the request (any status other than 404) — use it
238
- upstream = fbResp;
239
- break;
240
- }
217
+ const fetchPort = (p) => {
218
+ const h = new Headers(headers);
219
+ h.set("host", `localhost:${p}`);
220
+ return fetch(`http://localhost:${p}${msg.path}`, {
221
+ method: msg.method ?? "GET",
222
+ headers: h,
223
+ body: body,
224
+ redirect: "manual",
225
+ signal: ac.signal,
226
+ });
227
+ };
228
+ // Per-path port memoization. Once a path is known to belong to a backend
229
+ // port, go straight there and SKIP the primary hop — this avoids the wasted
230
+ // primary round trip AND, for modifying methods, avoids executing the write
231
+ // twice (primary + fallback). Key excludes the query string so it stays
232
+ // small; the port that owns a path does not vary by query.
233
+ const cacheKey = `${method} ${(msg.path ?? "").split("?")[0]}`;
234
+ const preferred = pathPortCache.get(cacheKey);
235
+ let upstream;
236
+ let servedPort = port;
237
+ if (preferred !== undefined && preferred !== port) {
238
+ try {
239
+ const r = await fetchPort(preferred);
240
+ if (r.status !== 404) {
241
+ upstream = r;
242
+ servedPort = preferred;
241
243
  }
242
- catch {
243
- // Fallback port not reachable, continue
244
+ }
245
+ catch {
246
+ // Preferred port unreachable (backend restarted / moved) — fall through
247
+ // to the primary + rediscovery path and let the cache re-learn.
248
+ pathPortCache.delete(cacheKey);
249
+ }
250
+ }
251
+ if (upstream === undefined) {
252
+ upstream = await fetchPort(port);
253
+ servedPort = port;
254
+ // Detect when the primary port can't handle the request — try fallbacks.
255
+ // Key signal: response is HTML but request didn't ask for HTML (a fetch
256
+ // hitting the SPA catch-all), or any modifying method.
257
+ const upstreamCt = upstream.headers.get("content-type") ?? "";
258
+ const requestAccept = (Array.isArray(msg.headers) ? msg.headers.find(([k]) => k.toLowerCase() === "accept")?.[1] : "") ?? "";
259
+ const requestExpectsHtml = requestAccept.includes("text/html");
260
+ const isModifyingMethod = method !== "GET" && method !== "HEAD";
261
+ const gotUnexpectedHtml = upstreamCt.includes("text/html") && !requestExpectsHtml;
262
+ const shouldTryFallback = (gotUnexpectedHtml || isModifyingMethod) && fallbackPorts.size > 0;
263
+ if (shouldTryFallback) {
264
+ for (const fbPort of fallbackPorts) {
265
+ if (fbPort === port)
266
+ continue;
267
+ try {
268
+ const fbResp = await fetchPort(fbPort);
269
+ if (fbResp.status !== 404) {
270
+ // Fallback port handled the request (any status other than 404).
271
+ upstream = fbResp;
272
+ servedPort = fbPort;
273
+ break;
274
+ }
275
+ }
276
+ catch {
277
+ // Fallback port not reachable, continue
278
+ }
244
279
  }
245
280
  }
246
281
  }
282
+ // Remember which backend port served this path so the next matching request
283
+ // skips the primary hop. Only cache non-primary wins — a primary-served path
284
+ // already takes the primary-first path with no wasted work.
285
+ if (servedPort !== port && upstream.status !== 404) {
286
+ pathPortCache.delete(cacheKey);
287
+ pathPortCache.set(cacheKey, servedPort);
288
+ if (pathPortCache.size > MAX_PATH_PORT_CACHE) {
289
+ const oldest = pathPortCache.keys().next().value;
290
+ if (oldest !== undefined)
291
+ pathPortCache.delete(oldest);
292
+ }
293
+ }
247
294
  // Build response header tuples
248
295
  const respHeaders = [];
249
296
  upstream.headers.forEach((v, k) => {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const CLI_VERSION = "0.6.0";
1
+ export declare const CLI_VERSION = "0.6.1";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.6.0";
1
+ export const CLI_VERSION = "0.6.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peekable",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Share HTML mockups with collaborators — CLI for peekable-server",
6
6
  "bin": {
package/skill/SKILL.md CHANGED
@@ -24,6 +24,8 @@ When the user wants to share an HTML file (playground, mockup, brainstorming com
24
24
 
25
25
  If a session already exists for this topic, reuse it (push creates a new version, collaborators auto-reload).
26
26
 
27
+ Session names are now visible in the share URL's subdomain (DNS and TLS SNI), not just to whoever opens the link. Avoid putting sensitive information in the session name. Use `peekable create "<name>" --no-slug` to get a nameless, opaque hostname when the name itself is sensitive.
28
+
27
29
  ### Share a video
28
30
 
29
31
  When the user wants to share a video for review:
@@ -119,6 +121,19 @@ peekable close <session-id> --json
119
121
 
120
122
  Free hosted accounts have an active-session cap. If create/proxy returns a limit error, run `peekable list --json`, close stale sessions, then retry.
121
123
 
124
+ ### Keep the CLI up to date
125
+
126
+ When `peekable create` or `peekable proxy --json` returns a `cli_update` object, the installed CLI is behind the server. Tell the user to update before relying on the session:
127
+
128
+ ```
129
+ npm i -g peekable@latest
130
+ ```
131
+
132
+ - `"action": "recommended"` — a newer version is available; mention it, then continue.
133
+ - `"action": "required"` — the installed version is missing fixes the current server depends on (e.g. tunnelling an app that calls its own backend). Surface this prominently and recommend updating before trusting the tunnel; the session still runs, but features may misbehave.
134
+
135
+ Use `npm i -g peekable@latest` — never `peekable upgrade`, which is the billing/Stripe command, not a version update.
136
+
122
137
  ### Diagnose setup
123
138
 
124
139
  When sharing fails, auth looks broken, or a user asks for help debugging: