rechrome 1.37.1 → 1.38.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.
package/serve.ts CHANGED
@@ -5,8 +5,8 @@ import { bearerOf, safeEqual } from "./secret.ts";
5
5
  import { WebrtcHost } from "./webrtc.ts";
6
6
  import { file } from "bun";
7
7
  import { createHash, randomBytes, X509Certificate } from "crypto";
8
- import { mkdirSync, lstatSync, chmodSync, unlinkSync, accessSync, readdirSync, realpathSync, constants as fsConstants } from "fs";
9
- import { join, resolve, relative, isAbsolute } from "path";
8
+ import { mkdirSync, lstatSync, statSync, chmodSync, unlinkSync, accessSync, readdirSync, realpathSync, existsSync, readFileSync, constants as fsConstants } from "fs";
9
+ import { join, resolve, relative, isAbsolute, sep } from "path";
10
10
  import { tmpdir } from "os";
11
11
  import {
12
12
  log,
@@ -24,6 +24,7 @@ import {
24
24
  checkTailscaleServe,
25
25
  chromeDataAccessHint,
26
26
  } from "./rechrome.ts";
27
+ import { SecretMasker, parseFillSecretWire, fillSecretOnSession, passwordValuesOnSession, hasSnapshot, maskPasswordLines, withholdSnapshots } from "./fill-secret.ts";
27
28
 
28
29
  const TAILSCALE_BIN = process.env.TAILSCALE_BIN || "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
29
30
  const CERT_RENEW_THRESHOLD_DAYS = 7;
@@ -87,6 +88,18 @@ const sessionTimeouts = new Map<string, number>(); // per-session consecutive-ti
87
88
  // Most-recently-used non-iso sessions, so the deep health probe can target something real
88
89
  // instead of spawning a fresh session (which could open a browser window).
89
90
  const recentSessions = new Map<string, number>();
91
+ // Values typed by `fill-secret`, masked in every output, log line and served text file for a
92
+ // while afterwards: snapshots echo input values (passwords included). See fill-secret.ts.
93
+ const secretMasker = new SecretMasker();
94
+ const TEXT_OUTPUT = /\.(?:ya?ml|json|md|txt|log)$/i;
95
+ // /run commands in flight, with the (real) output dir each writes to once known. A snapshot file
96
+ // exists on disk before its command has checked it for password values, so a text download waits
97
+ // until no command writing to its directory is in flight.
98
+ const runsInFlight = new Map<Promise<void>, string | undefined>();
99
+ // Only the CLI's own artifacts are ever scrubbed or deleted, never a file a page merely names.
100
+ const CLI_TEXT_ARTIFACT = /(^|\/)\.playwright-cli(-multi-tab)?\/[^/]+\.(?:ya?ml|json|md|txt|log)$/;
101
+ // Artifacts that could not be checked AND could not be deleted: never served.
102
+ const deniedFiles = new Set<string>();
90
103
  function noteSession(sess: string, now: number): void {
91
104
  recentSessions.set(sess, now);
92
105
  if (recentSessions.size > 64) {
@@ -738,6 +751,15 @@ export async function serve() {
738
751
  if (!(await f.exists())) return new Response("Not found", { status: 404 });
739
752
  const real = realpathSync(resolved);
740
753
  if (!isUnderDir(realpathSync(workDir), real) || !readable(relative(realpathSync(workDir), real).replaceAll("\\", "/"))) return new Response("Forbidden", { status: 403 });
754
+ if (deniedFiles.has(real)) return new Response("Forbidden", { status: 403 });
755
+ if (TEXT_OUTPUT.test(real)) {
756
+ const busy = () => [...runsInFlight].filter(([, dir]) => !dir || real.startsWith(dir + sep)).map(([p]) => p);
757
+ for (let pending = busy(); pending.length; pending = busy()) await Promise.all(pending); // re-check: new runs may start
758
+ // Synchronous from the last check on: no await, so no new run can start and write here.
759
+ if (deniedFiles.has(real)) return new Response("Forbidden", { status: 403 });
760
+ if (!existsSync(real)) return new Response("Not found", { status: 404 }); // withheld
761
+ return new Response(maskPasswordLines(secretMasker.mask(readFileSync(real, "utf8"))));
762
+ }
741
763
  return new Response(f);
742
764
  }
743
765
 
@@ -782,6 +804,10 @@ export async function serve() {
782
804
  const denied = authCheck(req, key);
783
805
  if (denied) return denied;
784
806
  markActivity(); // a real command: this serve is not idle
807
+ let runDone = () => {};
808
+ const running = new Promise<void>((r) => { runDone = r; });
809
+ runsInFlight.set(running, undefined); // dir not known yet: holds every text download
810
+ try { return await (async () => {
785
811
 
786
812
  let body: any;
787
813
  try { body = await readRequestJson(req); }
@@ -827,6 +853,7 @@ export async function serve() {
827
853
  const outputPrefix = scopedProfile ? profileOutputPrefix(scopedProfile) + (cred?.kind === "device" ? `d-${cred.device.id}/` : "") : "";
828
854
  const runWorkDir = scopedProfile ? join(workDir, outputPrefix) : workDir;
829
855
  mkdirSync(runWorkDir, { recursive: true });
856
+ runsInFlight.set(running, realpathSync(runWorkDir));
830
857
  let args: string[];
831
858
  let sessionId: string;
832
859
  let clientName = "";
@@ -894,6 +921,27 @@ export async function serve() {
894
921
 
895
922
  log(`run: rech ${filteredArgs.join(" ")} (session=${namespacedSession})`);
896
923
 
924
+ // fill-secret: the value arrives in body.secret, never in args; it is handed to the live
925
+ // session over its socket (no child argv) and never logged. See fill-secret.ts.
926
+ if (filteredArgs[0] === "fill-secret") {
927
+ const secret = !Array.isArray(body) && typeof body.secret === "string" ? body.secret : "";
928
+ try {
929
+ const { ref, allowDomains, submit, totp } = parseFillSecretWire(filteredArgs);
930
+ if (!secret) throw new Error("fill-secret: the request carried no secret (this client is older than the daemon?)");
931
+ secretMasker.add(secret, totp ? undefined : Infinity);
932
+ const reply = await fillSecretOnSession({ socketRoot: tmpSocketRoot(), session: namespacedSession, cwd: runWorkDir, ref, value: secret, allowDomains, submit });
933
+ // Drop the echoed run-code body (it embeds the value, masked or not, and is noise).
934
+ const text = secretMasker.mask(reply.text).replace(/### Ran Playwright code\n```js\n[\s\S]*?\n```\n?/, "").trim();
935
+ const status = reply.isError ? 1 : 0;
936
+ log(`exit: ${status} | fill-secret ${ref}`);
937
+ return Response.json(reply.isError ? { status, stdout: "", stderr: `${text}\n`, files: [] } : { status, stdout: `${text}\n`, stderr: "", files: [] });
938
+ } catch (error) {
939
+ const message = secretMasker.mask(secret ? (error instanceof Error ? error.message : String(error)).replaceAll(secret, "***") : (error instanceof Error ? error.message : String(error)));
940
+ log(`exit: 1 | fill-secret: ${message.split("\n")[0]}`);
941
+ return Response.json({ status: 1, stdout: "", stderr: `[rech] ${message}\n`, files: [] });
942
+ }
943
+ }
944
+
897
945
  // For open commands, default to about:blank to avoid leaving connect.html visible
898
946
  const isOpenCmd = filteredArgs[0] === "open";
899
947
  const isOpenNoUrl = isOpenCmd && filteredArgs.length === 1;
@@ -1041,7 +1089,7 @@ export async function serve() {
1041
1089
  reject(new Error("timeout"));
1042
1090
  }, TIMEOUT);
1043
1091
  });
1044
- const [status, stdout, rawStderr] = await Promise.race([
1092
+ let [status, stdout, rawStderr] = await Promise.race([
1045
1093
  Promise.all([
1046
1094
  proc.exited,
1047
1095
  new Response(proc.stdout).text(),
@@ -1058,7 +1106,7 @@ export async function serve() {
1058
1106
  ? configuredHandshakeTimeout
1059
1107
  : 30_000;
1060
1108
  const tccNote = explainExtensionNotFound(`${stdout}\n${rawStderr}`, chromeAccessProblem);
1061
- const stderr = (tccNote ?? "") + inferSilentExtensionFailure({
1109
+ let stderr = (tccNote ?? "") + inferSilentExtensionFailure({
1062
1110
  status,
1063
1111
  stdout,
1064
1112
  stderr: rawStderr,
@@ -1068,6 +1116,24 @@ export async function serve() {
1068
1116
  handshakeTimeoutMs,
1069
1117
  });
1070
1118
 
1119
+ // Snapshots print every input's value, password fields included (e.g. ones Chrome
1120
+ // autofilled). Read the live password values and mask them before anything is logged,
1121
+ // returned or left on disk; the label-based pass catches what the scan misses.
1122
+ // Fails closed: a snapshot that can't be fully checked is withheld, not passed through.
1123
+ const rawOutput = `${stdout}\n${stderr}`; // artifact paths come from the unmasked text
1124
+ const snapshotOut = hasSnapshot(rawOutput);
1125
+ let withheld = "";
1126
+ if (snapshotOut) {
1127
+ try {
1128
+ for (const v of await passwordValuesOnSession({ socketRoot: tmpSocketRoot(), session: namespacedSession, cwd: runWorkDir })) secretMasker.add(v, Infinity);
1129
+ } catch (error) {
1130
+ withheld = "could not check it for password values";
1131
+ log(`snapshot withheld: ${secretMasker.mask(error instanceof Error ? error.message : String(error)).split("\n")[0]}`);
1132
+ }
1133
+ }
1134
+ stdout = maskPasswordLines(secretMasker.mask(stdout));
1135
+ stderr = maskPasswordLines(secretMasker.mask(stderr));
1136
+ if (withheld) { stdout = withholdSnapshots(stdout, withheld); stderr = withholdSnapshots(stderr, withheld); }
1071
1137
  log(`exit: ${status}${stdout.trim() ? ` | ${stdout.trim().slice(0, 200)}` : ""}`);
1072
1138
 
1073
1139
  // Relay self-heal (see notes at SESSION_CLOSE_TIMEOUTS). A command that RETURNS usually
@@ -1105,12 +1171,8 @@ export async function serve() {
1105
1171
  }
1106
1172
 
1107
1173
  // Detect files mentioned in output
1108
- const filePattern = /[\w./-]+\.(?:png|jpe?g|pdf|json|yml)\b/gi;
1109
- const mentionedFiles = [
1110
- ...new Set(
1111
- [...stdout.matchAll(filePattern), ...stderr.matchAll(filePattern)].map((m) => m[0]),
1112
- ),
1113
- ];
1174
+ const filePattern = /[\w./-]+\.(?:png|jpe?g|pdf|json|ya?ml)\b/gi;
1175
+ const mentionedFiles = [...new Set([...rawOutput.matchAll(filePattern)].map((m) => m[0]))];
1114
1176
  const outputFiles: string[] = [];
1115
1177
  for (const f of mentionedFiles) {
1116
1178
  if (!isUnderDir(runWorkDir, f)) continue;
@@ -1130,6 +1192,35 @@ export async function serve() {
1130
1192
  }
1131
1193
  }
1132
1194
 
1195
+ // A file the command was told to write (`snapshot --filename=x.yml`) is its own artifact too.
1196
+ const ownFilenames = filteredArgs.flatMap((a, i) => a.startsWith("--filename=") ? [a.slice(11)] : a === "--filename" && filteredArgs[i + 1] ? [filteredArgs[i + 1]!] : []);
1197
+ // Snapshot files echo input values: scrub them on disk too, not only on download. Only
1198
+ // files this command wrote (a page can merely mention an existing file's name). One that
1199
+ // can't be checked or scrubbed is deleted, or, failing that, never served.
1200
+ // The command's own --filename targets count even when the output doesn't name them.
1201
+ const ownTargets = ownFilenames.filter(n => isUnderDir(runWorkDir, n) && existsSync(join(runWorkDir, n)));
1202
+ if (snapshotOut || secretMasker.active) for (const f of [...new Set([...outputFiles, ...ownTargets])]) {
1203
+ const ownFile = ownFilenames.some(n => resolve(runWorkDir, n) === resolve(runWorkDir, f));
1204
+ if (!ownFile && !CLI_TEXT_ARTIFACT.test(f.replaceAll("\\", "/"))) continue;
1205
+ const path = join(runWorkDir, f);
1206
+ let mtimeMs = 0;
1207
+ try { mtimeMs = statSync(path).mtimeMs; } catch { continue; }
1208
+ if (mtimeMs < commandStartedAt - 1000) continue;
1209
+ try {
1210
+ // Unchecked: withhold every snapshot file, and anything the command was told to write.
1211
+ if (withheld && (ownFile || /\.ya?ml$/i.test(f))) throw new Error("withheld");
1212
+ // Text vs binary by content, not name: `snapshot --filename=x.png` writes text.
1213
+ const bytes = new Uint8Array(await file(path).arrayBuffer());
1214
+ if (bytes.subarray(0, 8192).includes(0)) continue; // binary (e.g. a screenshot)
1215
+ const text = new TextDecoder().decode(bytes);
1216
+ const masked = maskPasswordLines(secretMasker.mask(text));
1217
+ if (masked !== text) await Bun.write(path, masked);
1218
+ } catch {
1219
+ try { unlinkSync(path); } catch { try { deniedFiles.add(realpathSync(path)); } catch {} }
1220
+ if (outputFiles.includes(f)) outputFiles.splice(outputFiles.indexOf(f), 1);
1221
+ }
1222
+ }
1223
+
1133
1224
  const rebrand = (s: string) => s.replaceAll("npx playwright-cli", "rech");
1134
1225
  return Response.json({
1135
1226
  status,
@@ -1139,6 +1230,7 @@ export async function serve() {
1139
1230
  // a cross-OS daemon↔client (e.g. Windows daemon serving a Linux container client).
1140
1231
  files: outputFiles.map((p) => (outputPrefix + p).replaceAll("\\", "/")),
1141
1232
  });
1233
+ })(); } finally { runsInFlight.delete(running); runDone(); }
1142
1234
  };
1143
1235
 
1144
1236
  // WebRTC: the same handler, reached over an encrypted DataChannel. Each request carries the
@@ -5,6 +5,8 @@ description: Set up or repair rechrome access to a selected Chrome profile, espe
5
5
 
6
6
  # Rechrome setup on macOS
7
7
 
8
+ For authorized native Windows UI work over winrpc, use [Windows desktop UI](../windows-desktop-ui/SKILL.md). It documents the delegated winrpc route and profile verification; do not apply the macOS picker shortcuts there.
9
+
8
10
  Use this workflow when the user requests rechrome setup for an existing Chrome profile. Complete the CLI and browser steps together; opening the guide alone is not completion.
9
11
 
10
12
  ## Choose the browser and profile
@@ -0,0 +1,64 @@
1
+ ---
2
+ name: windows-desktop-ui
3
+ description: Operate a remote Windows desktop through a delegated winrpc client, especially to install the rechrome Bridge in an explicitly selected Chrome profile. Use for authorized native Windows UI work, not ordinary browser commands once rech works.
4
+ ---
5
+
6
+ # Windows desktop UI via winrpc
7
+
8
+ ## Route and scope
9
+
10
+ Use the authorized winrpc executor lane on the controller host. The controlling lane sends small, exact AHK v2 scripts; the executor runs each request and returns its result and a private screenshot path. `WINRPC_URL` and `WINRPC_TOKEN` stay on the controller host. Do not copy them to other machines, print them, include them in messages, or invoke CLI help with credential-bearing arguments (a client previously echoed a token in help output). Have the executor read the existing private environment in-process and issue HTTP requests without logging authorization headers.
11
+
12
+ Obtain authorization for the target profile, extension and task. Existing task authorization covers its routine steps; do not repeatedly ask the user to click things or reapprove them. Ask for permission or missing information when scope must change. Never assume authorization to restart Chrome, enable debugging flags, alter policy, access logins, create credentials, or change other profiles. Do not read unrelated tab contents.
13
+
14
+ ## Preflight and locking
15
+
16
+ - Windows SSH gives a non-interactive session, often session 0. It is suitable for diagnostics and CLI calls, not launching GUI automation directly. winrpc must already run on the interactive desktop; use `POST /ahk-eval?gui=1` through the executor.
17
+ - Read the installed winrpc README and implementation when its behavior is uncertain. The observed installation was `C:\tmp\winrpc`; the source is [symval/winrpc](https://github.com/symval/winrpc).
18
+ - Check `GET /health` and `GET /lock`. Normal `/ahk-eval` requests acquire the cross-process `C:\tmp\im-ui.lock` automatically. The AHK lock was observed to be held per request; keep scripts short. The README's 60-second timeout applies to `/shell`, not a documented AHK lock TTL. Never force-unlock or use `readonly=1` to bypass locking for UI actions.
19
+ - The observed API has no acquire/hold endpoint across requests. Use per-action locks, passive screenshots between actions, and coordinator-confirmed exclusive desktop access. If someone requires a continuous lock, explain this limitation before proceeding. Do not silently claim the lock is held between calls. Passive screenshots do not acquire it.
20
+ - Take a screenshot **before** any action. After each small action, capture another screenshot and inspect it before sending the next action. Send scripts as exact UTF-8 files: semicolons in AHK start comments, so do not flatten scripts into semicolon-separated chat prose.
21
+ - The observed `/screenshot` captured only 1280x720 of a 1920x1080 desktop at 150% scaling. If edges are missing, use a DPI-aware passive capture through `/shell`; do not change display settings. Confirm bounds and scaling before using coordinates. In AHK v2, call `DllCall("SetThreadDpiAwarenessContext", "ptr", -4, "ptr")` and use `CoordMode("Mouse", "Screen")` for coordinates measured from a physical-pixel capture.
22
+
23
+ ## Prove the Chrome profile
24
+
25
+ Do not infer the profile from the foreground window or its display-name chip. Navigate the intended window to `chrome://version` and inspect **Profile Path**. For example, `User Data\Profile 1`; tasks must use their explicitly requested folder. Record that window's HWND and Chrome PID for this run. Never reuse old handles or PIDs from this runbook.
26
+
27
+ To navigate reliably, activate the verified HWND, wait about 500 ms, press Ctrl+L, wait about 300 ms, then paste the exact URL from the clipboard. Preserve the previous clipboard with `ClipboardAll()`, wait for the paste to complete, and restore it without printing its contents. Capture and inspect the address bar **before Enter**. Press Enter only when it contains the intended URL exactly and the same verified window remains active.
28
+
29
+ Direct `SendText` immediately after Ctrl+L can lose initial characters from `chrome://extensions/` and submit a search. Clipboard paste with focus delays works reliably. Never click resulting search results as a workaround.
30
+
31
+ ## Load only the requested extension
32
+
33
+ 1. In the verified profile, navigate to `chrome://extensions/` using the paste/check/Enter sequence. Inspect the extension list and Developer mode state. Leave Developer mode unchanged if already enabled; otherwise enable it only as part of the authorized unpacked-install task.
34
+ 2. Confirm the extension is not already installed; do not blindly add or reload it. For rechrome, verify the installed manifest and expected ID. The Bridge ID is `mmlmfjhmonkocbjadbfplnigmagldckm`.
35
+ 3. Click **Load unpacked** once and capture the native folder picker. The usual directory is `C:\Users\<user>\.rechrome\extension`, not `.rechrome\ext`; verify the actual manifest path before selecting it.
36
+ 4. Identify the picker before entering text. A Windows Chrome file picker can be a **different Chrome PID** from the main browser. The observed picker was class `#32770`, had its own HWND/PID, and its owner was the verified Profile HWND. Guard on the freshly observed dialog HWND, exact localized title, class, `chrome.exe`, and **owner HWND**, rather than requiring equality with the main browser PID. `DllCall("GetWindow", "ptr", dialogHwnd, "uint", 4, "ptr")` obtains `GW_OWNER`. For a title mismatch, a read-only title-codepoint probe can distinguish encoding artifacts from a different dialog. If the owner chain is unfamiliar, inspect it rather than weakening the guard.
37
+ 5. Paste the exact directory into the **Folder** field, restoring the clipboard afterward. Do not submit yet. Capture and verify the entire path; Japanese fonts may render backslashes as yen signs.
38
+ 6. Click **Select Folder** once. Capture the result: correct extension name/ID, enabled state, and no load error. A successful AHK exit alone proves none of these.
39
+
40
+ ## Finish setup and verify
41
+
42
+ Keep setup output private: it can contain bearer URLs and extension tokens. Never capture the setup guide. Report sanitized milestones instead.
43
+
44
+ Run `rech setup --profile "Profile 1" --listen local` for a local-only task; preserve the requested listener scope for other tasks. If setup must open GUI pages, run it in the user's interactive session through a **user-level Interactive scheduled task**, not session 0. Use the actual Windows identity SID for the principal; `USERDOMAIN` may be `WORKGROUP` and not a valid account domain. Keep the process alive through token detection, Bridge verification, and registration. Back up configuration before changing its save destination; do not overwrite unrelated defaults or create remote sharing without authorization.
45
+
46
+ Rechrome 1.35.1 passed unsupported `--wait none` to its bundled CLI's setup probe. The corrected probe is `open about:blank` in an isolated session, followed by cleanup of that session. If an old build reports `Unknown option: --wait`, use the reviewed corrected package/source; reloading the extension does not fix this parser error. Never patch `node_modules` in place.
47
+
48
+ After setup verifies the Bridge and saves registration, run **one harmless open** using the installed client and selected profile, for example:
49
+
50
+ ```powershell
51
+ rech --profile "Profile 1" -s=install-check open https://example.com
52
+ ```
53
+
54
+ Use a fresh verification session name when appropriate. Confirm exit 0 and the expected page title. Report the host, exact profile selector, installed version, and whether sharing/defaults changed. A loopback listener on the Windows host is usable by a CLI over SSH on that host; it is not automatically accessible to a remote client. Do not publish a credential-bearing link in the report. Retain only necessary installation/verification evidence and remove other temporary screenshots.
55
+
56
+ ## Stop and recovery rules
57
+
58
+ Stop before acting on another profile, a login/security prompt, an unfamiliar dialog, or unexpected user activity. Preserve the screen, release only locks owned by the request, and report what happened. Do not dismiss prompts, restart Chrome, retry blindly, or change policy. A failed identity guard permits read-only diagnostics within the authorized task; correct the guard only after evidence establishes the dialog's relationship to the verified browser. Respect any stricter retry limit in the current request. If further scope or permission is needed, ask for it; do not default to asking the user to perform routine UI steps manually.
59
+
60
+ ## Routes that did not solve persistent unpacked installation
61
+
62
+ - **CDP `Extensions.loadUnpacked`:** requires the appropriate remote-debugging/unsafe-extension flags. Current Chromium [marks the install as CDP-created](https://github.com/chromium/chromium/blob/main/chrome/browser/devtools/protocol/extensions_handler.cc), then [removes CDP-created extension preferences at startup](https://github.com/chromium/chromium/blob/main/extensions/browser/extension_prefs.cc) (`CleanUpCdpInstalledExtensions`). This is not the persistent install path for the user's existing browser. Do not restart it to test persistence.
63
+ - **`--load-extension`:** branded Chrome removed this switch beginning in Chrome 137; Chromium/Chrome for Testing behavior is different. See the [Chrome team's announcement](https://groups.google.com/a/chromium.org/g/chromium-extensions/c/1-g8EFx2BBY). Do not replace the user's browser/profile with a managed test browser to evade this constraint.
64
+ - **Registry/enterprise policy:** not a single-profile arbitrary unpacked-folder installation mechanism. [External installation](https://developer.chrome.com/docs/extensions/how-to/distribute/install-extensions) uses update URLs; enterprise distribution requires a separate deployment design. Do not add machine-wide policy, host a CRX, or forge Secure Preferences for this task.