worktrust 0.10.37 → 0.11.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/LICENSE +43 -18
- package/README.md +59 -2
- package/SECURITY.md +25 -0
- package/chat-exports.mjs +20 -20
- package/engine-release.json +1 -1
- package/export-facts.mjs +71 -0
- package/log-session.mjs +15 -15
- package/package-release.json +1 -1
- package/package.json +36 -2
- package/remote-adapter-claude-code.mjs +111 -0
- package/remote-adapter-codex.mjs +119 -0
- package/remote-approval-bridge.mjs +122 -0
- package/remote-approvals.mjs +124 -0
- package/remote-attachments.mjs +129 -0
- package/remote-changes.mjs +94 -0
- package/remote-claude-events.mjs +212 -0
- package/remote-claude-progress.mjs +328 -0
- package/remote-cli.mjs +325 -0
- package/remote-coalesce.mjs +40 -0
- package/remote-codex-events.mjs +153 -0
- package/remote-daemon.mjs +205 -0
- package/remote-inventory.mjs +132 -0
- package/remote-journal.mjs +155 -0
- package/remote-pairing.mjs +104 -0
- package/remote-pipeline-config.mjs +177 -0
- package/remote-pipeline-parsers.mjs +121 -0
- package/remote-pipeline.mjs +234 -0
- package/remote-policy.mjs +199 -0
- package/remote-preview.mjs +146 -0
- package/remote-projects.mjs +87 -0
- package/remote-protocol.mjs +3881 -0
- package/remote-qr.mjs +175 -0
- package/remote-release-plans.mjs +88 -0
- package/remote-releases.mjs +297 -0
- package/remote-run.mjs +174 -0
- package/remote-service.mjs +101 -0
- package/remote-session-list.mjs +25 -0
- package/remote-sessions.mjs +348 -0
- package/remote-steered.mjs +114 -0
- package/remote-steering.mjs +97 -0
- package/remote-store.mjs +123 -0
- package/remote-transport.mjs +88 -0
- package/worktrust.mjs +13 -6
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHAT A PHONE MAY REACH ON THIS COMPUTER (2026-11-07; owner decisions, binding). The computer's own policy, never the
|
|
3
|
+
* phone's: the phone shows what this file decided and the computer refuses anything else however well it is signed.
|
|
4
|
+
*
|
|
5
|
+
* PROJECTS. A phone may steer an agent only inside a folder the person granted at this keyboard
|
|
6
|
+
* (`worktrust remote projects add`). A grant is the folder's canonical path (realpath: every symlink resolved), a
|
|
7
|
+
* directory, and never the home folder itself, a parent of it, the root, or a place that holds secrets (~/.ssh, ~/.gnupg,
|
|
8
|
+
* keychains, browser profiles, wallets, cloud credentials).
|
|
9
|
+
*
|
|
10
|
+
* APPROVALS. Every permission request an agent makes is put in ONE of the protocol's APPROVAL_CLASSES here. Only two
|
|
11
|
+
* may reach the phone (owner decision 6): `project_edit`, a file edit inside the granted project that touches no secret
|
|
12
|
+
* and no rule file, and `reviewed_command`, a command from the short reviewed list below (tests, builds, linters), run
|
|
13
|
+
* exactly as listed, with no shell syntax. Everything else is decided at the keyboard or not at all: an install from the
|
|
14
|
+
* network, git push, a deploy, deleting outside the project, reading a secret path, any "always allow" rule, and
|
|
15
|
+
* whatever this file cannot name (`other`). Unknown fails closed.
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
19
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
|
+
import * as P from "./remote-protocol.mjs";
|
|
21
|
+
|
|
22
|
+
const HOME = () => realpathOr(homedir());
|
|
23
|
+
function realpathOr(path) { try { return realpathSync(path); } catch { return resolve(path); } }
|
|
24
|
+
|
|
25
|
+
/** Inside `root` (both canonical): equal to it or below it, never through `..`. */
|
|
26
|
+
export const isInside = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
27
|
+
|
|
28
|
+
/** Folders that hold secrets or another program's private state, relative to the home folder. */
|
|
29
|
+
const SECRET_DIRS = [".ssh", ".gnupg", ".aws", ".azure", ".config/gcloud", ".kube", ".docker", ".password-store", ".worktrust",
|
|
30
|
+
"Library/Keychains", "Library/Application Support/Google/Chrome", "Library/Application Support/Firefox", "Library/Application Support/BraveSoftware",
|
|
31
|
+
"Library/Application Support/Microsoft Edge", "Library/Safari", "Library/Cookies", ".mozilla", ".config/google-chrome", ".config/chromium",
|
|
32
|
+
".config/BraveSoftware", ".local/share/keyrings", ".electrum", ".bitcoin", ".ethereum", "Library/Ethereum", "Library/Application Support/Exodus", ".config/solana"];
|
|
33
|
+
/** File names that are secrets wherever they lie. `.env` and its variants, keys, credentials, token stores. */
|
|
34
|
+
const SECRET_FILE = /^(\.env(\..*)?|\.envrc|\.netrc|\.npmrc|\.pypirc|\.git-credentials|id_(rsa|ecdsa|ed25519|dsa)(\.pub)?|.*\.(pem|key|p12|pfx|keystore|jks|kdbx|ovpn)|credentials(\.json)?|secrets?\.(json|ya?ml|toml)|service-account.*\.json|wallet\.dat|keystore)$/i;
|
|
35
|
+
/** Files that change what an agent may do by itself: permission rules, hooks, MCP servers. Editing one is an "always allow". */
|
|
36
|
+
/** Files that change what an agent or a tool may do by itself: permission rules, hooks, MCP servers, the repository's own
|
|
37
|
+
* configuration (core.fsmonitor and sshCommand run code), editor tasks. Editing one is an "always allow". Case-insensitive:
|
|
38
|
+
* macOS and Windows disks are, and a path typed as .CLAUDE/SETTINGS.JSON is the same file (review 2026-11-07, P1-a). */
|
|
39
|
+
const RULE_FILE = /(^|[\\/])(\.claude[\\/].*|\.mcp\.json|\.claude\.json|\.codex[\\/].*|\.cursor[\\/].*|\.git([\\/].*)?|\.husky[\\/].*|\.vscode[\\/].*|\.idea[\\/].*|\.envrc|\.npmrc|\.yarnrc(\.yml)?|\.gitattributes|\.gitmodules)$/i;
|
|
40
|
+
/** Files that say what a reviewed command runs (scripts, targets, test setup): an edit to one from a phone would turn the next
|
|
41
|
+
* "npm test" into anything, so it is decided at the keyboard (P2-a). */
|
|
42
|
+
const SCRIPT_FILE = /(^|[\\/])(package\.json|makefile|gnumakefile|justfile|taskfile\.ya?ml|pyproject\.toml|setup\.py|setup\.cfg|tox\.ini|noxfile\.py|conftest\.py|pytest\.ini|cargo\.toml|build\.rs|go\.mod|deno\.jsonc?|bunfig\.toml|turbo\.json|nx\.json|(jest|vitest|vite|webpack|rollup|babel|eslint|prettier)\.config\.[cm]?[jt]s|\.eslintrc(\.[a-z]+)?)$/i;
|
|
43
|
+
|
|
44
|
+
export function isSecretPath(path) {
|
|
45
|
+
const canonical = realpathOr(path), home = HOME();
|
|
46
|
+
if (SECRET_FILE.test(basename(canonical))) return true;
|
|
47
|
+
return SECRET_DIRS.some((dir) => isInside(join(home, dir), canonical));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A folder a person asks to grant: its canonical form, or the reason it cannot be granted. */
|
|
51
|
+
export function canonicalProject(path) {
|
|
52
|
+
if (typeof path !== "string" || path.trim() === "") return { ok: false, reason: "name a folder" };
|
|
53
|
+
const given = resolve(path.replace(/^~(?=$|[\\/])/, homedir()));
|
|
54
|
+
if (!existsSync(given)) return { ok: false, reason: "that folder does not exist" };
|
|
55
|
+
const canonical = realpathSync(given);
|
|
56
|
+
if (!statSync(canonical).isDirectory()) return { ok: false, reason: "that is a file, not a folder" };
|
|
57
|
+
const home = HOME();
|
|
58
|
+
if (dirname(canonical) === canonical) return { ok: false, reason: "the root of the disk cannot be granted" };
|
|
59
|
+
if (isInside(canonical, home)) return { ok: false, reason: "your home folder, or a folder above it, cannot be granted: grant one project folder" };
|
|
60
|
+
if (isSecretPath(canonical) || SECRET_DIRS.some((dir) => isInside(canonical, join(home, dir)))) return { ok: false, reason: "that folder holds secrets (keys, keychains, browser profiles, wallets, credentials)" };
|
|
61
|
+
return { ok: true, path: canonical };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The project a path is in, by the canonical path of the path itself or, for a file not yet written, of its folder. */
|
|
65
|
+
export function canonicalTarget(path, cwd) {
|
|
66
|
+
if (typeof path !== "string" || path === "") return null;
|
|
67
|
+
// The nearest folder that exists, every symlink in it resolved, then the rest added back: a new file under a link that
|
|
68
|
+
// points outside the project is outside it (review 2026-11-07, P1-b).
|
|
69
|
+
let existing = resolve(cwd, path);
|
|
70
|
+
const rest = [];
|
|
71
|
+
while (!existsSync(existing) && dirname(existing) !== existing) { rest.unshift(basename(existing)); existing = dirname(existing); }
|
|
72
|
+
let base;
|
|
73
|
+
try { base = realpathSync.native(existing); } catch { base = realpathOr(existing); }
|
|
74
|
+
return rest.length ? join(base, ...rest) : base;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* THE REVIEWED COMMANDS: tests, builds and linters, exactly. A command is approvable from a phone only when its words,
|
|
79
|
+
* split on spaces, match one line here with nothing after it but plain arguments ([A-Za-z0-9_./:=@,+-], no `..`).
|
|
80
|
+
* No package runner that may download (`npx`, `pnpm dlx`, `bunx`), no install, no script that names a deploy.
|
|
81
|
+
*/
|
|
82
|
+
export const REVIEWED_COMMANDS = Object.freeze([
|
|
83
|
+
"npm test", "npm run test", "npm run build", "npm run lint", "npm run typecheck",
|
|
84
|
+
"pnpm test", "pnpm run test", "pnpm build", "pnpm run build", "pnpm lint", "pnpm run lint", "pnpm typecheck", "pnpm run typecheck",
|
|
85
|
+
"yarn test", "yarn build", "yarn lint", "bun test", "bun run test", "bun run build", "bun run lint",
|
|
86
|
+
"node --test", "pytest", "python -m pytest", "python3 -m pytest", "cargo test --offline", "cargo build --offline", "cargo check --offline", "cargo clippy --offline",
|
|
87
|
+
"make test", "make build", "make lint", "make check", "tsc --noEmit", "eslint", "ruff check", "mypy", "prettier --check",
|
|
88
|
+
]);
|
|
89
|
+
/** An argument after a reviewed line is a relative path or a test name inside the project: no flag, no assignment, no absolute
|
|
90
|
+
* path, no way up (review 2026-11-07, P2-a: `make test -C /x`, `npm test --prefix=/x`, `node --test --require=/x`). */
|
|
91
|
+
const PLAIN_ARG = /^[A-Za-z0-9_][A-Za-z0-9_./:@,+-]*$/;
|
|
92
|
+
const SHELL_SYNTAX = /[;&|`$<>(){}\\\n\r'"*?!~#]/;
|
|
93
|
+
const NETWORK = /^(npm|pnpm|yarn|bun)\s+(i|install|add|ci|update|upgrade|dlx|x|create|init)\b|^(npx|bunx|pip3?|pipx|uv|poetry|gem|brew|apt(-get)?|dnf|yum|cargo\s+install|go\s+(get|install)|curl|wget|git\s+(clone|fetch|pull)|docker\s+(pull|run))\b/;
|
|
94
|
+
const PUSH = /^git\s+push\b/;
|
|
95
|
+
const DEPLOY = /^(vercel|netlify|fly|flyctl|firebase|heroku|wrangler|serverless|sls|kubectl|helm|terraform|pulumi|eas|gcloud|aws|az|railway|render)\b|^(npm|pnpm|yarn)\s+(publish|run\s+deploy|deploy)\b|\bdeploy\b/;
|
|
96
|
+
|
|
97
|
+
export function reviewedCommand(command) {
|
|
98
|
+
if (typeof command !== "string" || SHELL_SYNTAX.test(command)) return false;
|
|
99
|
+
const words = command.trim().split(/\s+/);
|
|
100
|
+
return REVIEWED_COMMANDS.some((line) => {
|
|
101
|
+
const head = line.split(" ");
|
|
102
|
+
if (head.some((word, i) => words[i] !== word)) return false;
|
|
103
|
+
return words.slice(head.length).every((arg) => PLAIN_ARG.test(arg) && !arg.split("/").includes(".."));
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function classifyCommand(command, project) {
|
|
108
|
+
const text = String(command ?? "").trim();
|
|
109
|
+
if (PUSH.test(text)) return "git_push";
|
|
110
|
+
if (DEPLOY.test(text)) return "deploy";
|
|
111
|
+
if (NETWORK.test(text)) return "network_install";
|
|
112
|
+
if (/^(rm|rmdir|unlink|trash|shred)\b/.test(text)) {
|
|
113
|
+
const targets = text.split(/\s+/).slice(1).filter((w) => !w.startsWith("-"));
|
|
114
|
+
return targets.some((t) => !isInside(project, canonicalTarget(t, project) ?? "/")) ? "delete_outside_project" : "other";
|
|
115
|
+
}
|
|
116
|
+
if (/(^|\s)(cat|less|more|head|tail|grep|rg|cp|scp|base64)\s/.test(` ${text} `) && text.split(/\s+/).some((w) => SECRET_FILE.test(basename(w)) || w.includes(".ssh"))) return "secret_read";
|
|
117
|
+
return reviewedCommand(text) ? "reviewed_command" : "other";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* AN OUTWARD MESSAGE (owner, 2026-11-07): a connector tool (mcp__<server>__<tool>) whose tool name says it sends (send,
|
|
122
|
+
* reply, post, publish) is `outward_message` ONLY when every field of the message can be read from its input and nothing
|
|
123
|
+
* else is in it: recipients (to, or a channel), cc, bcc, subject, the text, attachment names, and a thread to answer in.
|
|
124
|
+
* An input with any other field, no recipient, no text, or attachments it cannot name is `other`, denied locally: the
|
|
125
|
+
* phone must see the whole message it approves. Claude Code's permission request names the tool, not its description,
|
|
126
|
+
* so the name decides.
|
|
127
|
+
*/
|
|
128
|
+
const SENDS = /(^|_)(send|reply|post|publish)(_|$)/;
|
|
129
|
+
const MESSAGE_KEYS = new Set(["to", "recipients", "recipient", "channel", "cc", "bcc", "subject", "body", "text", "message", "content", "attachments", "thread_id", "threadId", "in_reply_to", "inReplyTo"]);
|
|
130
|
+
const snake = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
131
|
+
const addresses = (value) => (value === undefined ? [] : typeof value === "string" ? value.split(",").map((a) => a.trim()).filter(Boolean) : Array.isArray(value) && value.every((a) => typeof a === "string") ? value : null);
|
|
132
|
+
export function outwardMessageOf(tool, args, project) {
|
|
133
|
+
const m = /^mcp__([A-Za-z0-9_-]+?)__([A-Za-z0-9_-]+)$/.exec(String(tool));
|
|
134
|
+
if (!m || !SENDS.test(snake(m[2]))) return null;
|
|
135
|
+
if (Object.keys(args).some((k) => !MESSAGE_KEYS.has(k))) return { refused: "the message has fields the phone could not be shown" };
|
|
136
|
+
const to = addresses(args.to ?? args.recipients ?? args.recipient ?? args.channel), cc = addresses(args.cc), bcc = addresses(args.bcc);
|
|
137
|
+
const text = [args.body, args.text, args.message, args.content].filter((v) => v !== undefined);
|
|
138
|
+
const attachments = args.attachments === undefined ? [] : Array.isArray(args.attachments) ? args.attachments.map((a) => (typeof a === "string" ? a : a?.filename ?? a?.name ?? a?.path)) : null;
|
|
139
|
+
if (!to || to.length === 0 || to.length > 100 || !cc || !bcc || cc.length > 100 || bcc.length > 100) return { refused: "the message's recipients cannot all be shown" };
|
|
140
|
+
if (text.length !== 1 || typeof text[0] !== "string" || text[0].length > 65_536) return { refused: "the message's text cannot be shown whole" };
|
|
141
|
+
if (!attachments || attachments.length > 50 || attachments.some((a) => typeof a !== "string" || !a)) return { refused: "the message's attachments cannot all be named" };
|
|
142
|
+
if (attachments.some((a) => isSecretPath(canonicalTarget(a, project) ?? a) || !isInside(project, canonicalTarget(a, project) ?? "/"))) return { refused: "an attachment is a secret file or lies outside the project" };
|
|
143
|
+
if (args.subject !== undefined && (typeof args.subject !== "string" || args.subject.length > 998)) return { refused: "the message's subject cannot be shown" };
|
|
144
|
+
if ([...to, ...cc, ...bcc].some((a) => a.length > 320)) return { refused: "a recipient is too long to show" };
|
|
145
|
+
return { message: { channel: m[1].slice(0, 128), to, cc, bcc, subject: args.subject ?? null, text: text[0], attachments } };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
149
|
+
const READ_TOOLS = new Set(["Read", "Glob", "Grep", "LS", "NotebookRead"]);
|
|
150
|
+
export const MAX_SHOWN_INPUT = 16_384;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* One permission request → the action the phone would see, with its class. `tool` is the agent's own tool name, `input`
|
|
154
|
+
* its exact arguments, `project` the canonical project folder. Pure apart from reading which paths exist.
|
|
155
|
+
*/
|
|
156
|
+
export function classifyAction(adapter, tool, input, project, rationale = null) {
|
|
157
|
+
const args = input && typeof input === "object" ? input : {};
|
|
158
|
+
const shown = JSON.stringify(args);
|
|
159
|
+
let kind = "tool", cls = "other", files = [];
|
|
160
|
+
if (tool === "Bash") {
|
|
161
|
+
kind = "command";
|
|
162
|
+
cls = classifyCommand(args.command, project);
|
|
163
|
+
} else if (EDIT_TOOLS.has(tool)) {
|
|
164
|
+
const target = canonicalTarget(args.file_path ?? args.notebook_path, project);
|
|
165
|
+
files = target ? [target] : [];
|
|
166
|
+
kind = tool === "Write" && target && !existsSync(target) ? "write" : "edit";
|
|
167
|
+
cls = !target ? "other" : RULE_FILE.test(target) ? "persistent_rule" : isSecretPath(target) ? "secret_read" : !isInside(project, target) ? "other" : SCRIPT_FILE.test(target) ? "other" : "project_edit";
|
|
168
|
+
} else if (READ_TOOLS.has(tool)) {
|
|
169
|
+
const target = canonicalTarget(args.file_path ?? args.path ?? args.notebook_path, project);
|
|
170
|
+
files = target ? [target] : [];
|
|
171
|
+
kind = "tool";
|
|
172
|
+
cls = target && isSecretPath(target) ? "secret_read" : "other";
|
|
173
|
+
} else if (tool === "WebFetch" || tool === "WebSearch") kind = "network";
|
|
174
|
+
const outward = outwardMessageOf(tool, args, project);
|
|
175
|
+
if (outward) {
|
|
176
|
+
const base = { kind: "message", adapter, tool: String(tool).slice(0, 128), files: [], rationale };
|
|
177
|
+
if (outward.refused || shown.length > MAX_SHOWN_INPUT) return { action: { ...base, class: "other", input: shown.slice(0, MAX_SHOWN_INPUT) }, reason: outward.refused ?? "the message is too long to show exactly" };
|
|
178
|
+
return { action: { ...base, class: "outward_message", input: shown, message: outward.message }, reason: null };
|
|
179
|
+
}
|
|
180
|
+
// What the phone shows is the exact input. When it cannot be shown whole, it cannot be approved from a phone.
|
|
181
|
+
if (shown.length > MAX_SHOWN_INPUT) return { action: { kind, class: "other", adapter, tool: String(tool).slice(0, 128) || "unknown", input: `${shown.slice(0, MAX_SHOWN_INPUT - 40)} [cut: too long to show exactly]`, files: files.slice(0, 100), rationale }, reason: "the request is too long to show exactly" };
|
|
182
|
+
const action = { kind, class: P.APPROVAL_CLASSES.includes(cls) ? cls : "other", adapter, tool: String(tool).slice(0, 128) || "unknown", input: shown.length > 0 ? shown : "{}", files: files.slice(0, 100), rationale };
|
|
183
|
+
return { action, reason: P.isRemoteApprovable(action.class) ? null : REASONS[action.class] };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const REASONS = Object.freeze({
|
|
187
|
+
network_install: "installs from the network are approved at the computer, never from a phone",
|
|
188
|
+
git_push: "git push is approved at the computer, never from a phone",
|
|
189
|
+
deploy: "deploys are approved at the computer, never from a phone",
|
|
190
|
+
delete_outside_project: "deleting outside the project is never approved from a phone",
|
|
191
|
+
secret_read: "secret files (keys, .env, credentials) are never opened from a phone",
|
|
192
|
+
persistent_rule: "rules that let an agent act alone later are set at the computer, never from a phone",
|
|
193
|
+
other: "only edits inside the project, reviewed test, build and lint commands, and messages shown whole are approved from a phone",
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
/** The one gate between a classified action and the phone. Nothing else in the daemon may decide this. */
|
|
197
|
+
export const phoneMayDecide = (action) => P.APPROVAL_CLASSES.includes(action?.class) && P.isRemoteApprovable(action.class);
|
|
198
|
+
|
|
199
|
+
export const SEP = sep;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A LOCAL PREVIEW FOR THE PHONE (owner, 2026-11-07: the phone's "Deploy" segment is a LOCAL preview, never a production
|
|
3
|
+
* deploy). docs/remote-agents/PROTOCOL.md "Local preview".
|
|
4
|
+
*
|
|
5
|
+
* The person grants, per project and at the keyboard, the dev-server PORTS and the built HTML FILES a phone may preview
|
|
6
|
+
* (`worktrust remote preview allow <port|file> <folder>`; ~/.worktrust/remote/previews.json). `preview.render` renders one
|
|
7
|
+
* of them with the person's installed Chrome or Chromium, headless (`--headless=new --screenshot --window-size`), in a
|
|
8
|
+
* throw-away profile, and answers with the PNG in sealed chunks and the page's title and HTTP status as the computer saw
|
|
9
|
+
* them. The URL is always built here: `http://127.0.0.1:<granted port><path>`, never a host or URL from the phone. A file
|
|
10
|
+
* is served to Chrome by a one-shot server on 127.0.0.1 that answers only files inside the project (no dotfile, no secret
|
|
11
|
+
* path, no link out), so Chrome never opens file:// and a page cannot pull another file of the computer into the picture.
|
|
12
|
+
* No browser installed: refused (`unsupported`); nothing is installed. One render at a time.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
17
|
+
import { createServer, get } from "node:http";
|
|
18
|
+
import { connect } from "node:net";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { delimiter, extname, join, relative, sep } from "node:path";
|
|
21
|
+
import * as P from "./remote-protocol.mjs";
|
|
22
|
+
import { isSecretPath } from "./remote-policy.mjs";
|
|
23
|
+
|
|
24
|
+
const MAC_BROWSERS = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"];
|
|
25
|
+
const PATH_BROWSERS = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"];
|
|
26
|
+
const TYPES = { ".html": "text/html", ".htm": "text/html", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".woff2": "font/woff2", ".woff": "font/woff", ".ico": "image/x-icon" };
|
|
27
|
+
const RENDER_MS = 30_000;
|
|
28
|
+
|
|
29
|
+
/** The person's own Chrome-family browser, or null. WORKTRUST_PREVIEW_BROWSER (the daemon's own environment) is for tests. */
|
|
30
|
+
export function findBrowser(env = process.env) {
|
|
31
|
+
const forced = process.env.WORKTRUST_PREVIEW_BROWSER;
|
|
32
|
+
if (forced) return existsSync(forced) ? forced : null;
|
|
33
|
+
// The repo's named Chromium (CI installs Playwright's and names it here, as every browser check does), then the computer's own.
|
|
34
|
+
const named = process.env.WORKTRUST_CHROME_BIN;
|
|
35
|
+
if (named && existsSync(named)) return named;
|
|
36
|
+
if (process.platform === "darwin") for (const f of MAC_BROWSERS) if (existsSync(f)) return f;
|
|
37
|
+
for (const dir of (env.PATH ?? "").split(delimiter)) for (const b of PATH_BROWSERS) if (dir && existsSync(join(dir, b))) return join(dir, b);
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Something listens on 127.0.0.1:port. */
|
|
42
|
+
export const listening = (port, ms = 500) => new Promise((resolve) => {
|
|
43
|
+
const s = connect({ host: "127.0.0.1", port });
|
|
44
|
+
const done = (v) => { s.destroy(); resolve(v); };
|
|
45
|
+
s.once("connect", () => done(true)); s.once("error", () => done(false)); s.setTimeout(ms, () => done(false));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const inside = (root, p) => { const rel = relative(root, p); return rel === "" || (!rel.startsWith("..") && !rel.startsWith(sep) && !/^[A-Za-z]:/.test(rel)); };
|
|
49
|
+
|
|
50
|
+
/** A one-shot server for a project's files: inside the project only, no dotfile, no secret, no link out. */
|
|
51
|
+
export function serveProject(root) {
|
|
52
|
+
const base = realpathSync(root);
|
|
53
|
+
const server = createServer((req, res) => {
|
|
54
|
+
const path = decodeURIComponent(new URL(req.url, "http://127.0.0.1").pathname);
|
|
55
|
+
const file = join(base, path);
|
|
56
|
+
let ok = false;
|
|
57
|
+
try { ok = !path.split("/").some((seg) => seg.startsWith(".")) && existsSync(file) && lstatSync(file).isFile() && inside(base, realpathSync(file)) && !isSecretPath(realpathSync(file)); } catch { ok = false; }
|
|
58
|
+
if (!ok) { res.writeHead(404).end(); return; }
|
|
59
|
+
res.writeHead(200, { "content-type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream" }).end(readFileSync(file));
|
|
60
|
+
});
|
|
61
|
+
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve({ port: server.address().port, close: () => server.close() })));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The status and <title> of the page as the computer reads it (256 KiB at most). */
|
|
65
|
+
export const pageFacts = (url) => new Promise((resolve) => {
|
|
66
|
+
const req = get(url, { timeout: 5000 }, (res) => {
|
|
67
|
+
let body = "";
|
|
68
|
+
res.setEncoding("utf8");
|
|
69
|
+
res.on("data", (c) => { if (body.length < 262_144) body += c; });
|
|
70
|
+
res.on("end", () => resolve({ status: res.statusCode ?? null, title: /<title[^>]*>([^<]{1,300})<\/title>/i.exec(body)?.[1]?.trim() || null }));
|
|
71
|
+
});
|
|
72
|
+
req.on("timeout", () => req.destroy());
|
|
73
|
+
req.on("error", () => resolve({ status: null, title: null }));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** A PNG's own width and height (its IHDR), or null. */
|
|
77
|
+
export function pngSize(b) {
|
|
78
|
+
if (b.length < 24 || b.readUInt32BE(0) !== 0x89504e47 || b.toString("latin1", 12, 16) !== "IHDR") return null;
|
|
79
|
+
return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The fixed command line: headless, a throw-away profile, no first run, the window, the screenshot file, the URL. */
|
|
83
|
+
export function browserArgs({ profile, out, width, height, url }) {
|
|
84
|
+
return ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--mute-audio", "--disable-sync",
|
|
85
|
+
`--user-data-dir=${profile}`, `--screenshot=${out}`, `--window-size=${width},${height}`, "--virtual-time-budget=5000", url];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createPreview(ctx) {
|
|
89
|
+
// ctx: { emit, projects(), grants() → { [project_id]: { ports: [], files: [] } }, env(), log }
|
|
90
|
+
let busy = false;
|
|
91
|
+
const grantOf = (projectId) => ctx.grants()[projectId] ?? { ports: [], files: [] };
|
|
92
|
+
|
|
93
|
+
async function targets(env, p) {
|
|
94
|
+
const project = ctx.projects().find((x) => x.project_id === p.project_id);
|
|
95
|
+
if (!project) return "not_found";
|
|
96
|
+
const g = grantOf(p.project_id);
|
|
97
|
+
const ports = await Promise.all((g.ports ?? []).slice(0, 20).map(async (port) => ({ port, listening: await listening(port) })));
|
|
98
|
+
ctx.emit(null, "preview.targets", { project_id: p.project_id, ports, files: (g.files ?? []).slice(0, 50), browser: findBrowser(ctx.env()) !== null }, env.command_id);
|
|
99
|
+
return "taken";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function render(env, p) {
|
|
103
|
+
const project = ctx.projects().find((x) => x.project_id === p.project_id);
|
|
104
|
+
if (!project) return "not_found";
|
|
105
|
+
const g = grantOf(p.project_id);
|
|
106
|
+
if (p.target === "port" ? !(g.ports ?? []).includes(p.port) : !(g.files ?? []).includes(p.path)) return "unsupported"; // granted at the keyboard only
|
|
107
|
+
const browser = findBrowser(ctx.env());
|
|
108
|
+
if (!browser) return "unsupported";
|
|
109
|
+
if (busy) return "busy";
|
|
110
|
+
if (p.target === "port" && !(await listening(p.port))) return "not_found";
|
|
111
|
+
busy = true;
|
|
112
|
+
const profile = mkdtempSync(join(tmpdir(), "wt-preview-"));
|
|
113
|
+
let server = null;
|
|
114
|
+
try {
|
|
115
|
+
let url;
|
|
116
|
+
if (p.target === "port") url = `http://127.0.0.1:${p.port}${p.path}`;
|
|
117
|
+
else { server = await serveProject(project.path); url = `http://127.0.0.1:${server.port}/${p.path}`; }
|
|
118
|
+
const facts = await pageFacts(url);
|
|
119
|
+
const vp = P.PREVIEW_VIEWPORTS[p.viewport];
|
|
120
|
+
const height = p.full_page ? Math.min(vp.height * 4, 6000) : vp.height; // a tall window, not a measured page: see PROTOCOL.md
|
|
121
|
+
const out = join(profile, "shot.png");
|
|
122
|
+
const code = await new Promise((resolve) => {
|
|
123
|
+
const child = spawn(browser, browserArgs({ profile: join(profile, "p"), out, width: vp.width, height, url }), { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true, env: ctx.env() });
|
|
124
|
+
const timer = setTimeout(() => { try { process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); } }, RENDER_MS);
|
|
125
|
+
child.on("error", () => { clearTimeout(timer); resolve(-1); });
|
|
126
|
+
child.on("exit", (c) => { clearTimeout(timer); resolve(c ?? -1); });
|
|
127
|
+
});
|
|
128
|
+
const png = existsSync(out) ? readFileSync(out) : null;
|
|
129
|
+
const size = png && pngSize(png);
|
|
130
|
+
if (code !== 0 || !png || !size || png.length > P.MAX_PREVIEW_BYTES) { ctx.log("preview_failed", { code }); return "unsupported"; }
|
|
131
|
+
const chunks = Math.ceil(png.length / P.PREVIEW_CHUNK_BYTES);
|
|
132
|
+
for (let n = 0; n < chunks; n += 1)
|
|
133
|
+
ctx.emit(null, "preview.image", { preview_id: p.preview_id, chunk: n, chunks, data: P.toBase64Url(png.subarray(n * P.PREVIEW_CHUNK_BYTES, (n + 1) * P.PREVIEW_CHUNK_BYTES)) }, env.command_id);
|
|
134
|
+
ctx.emit(null, "preview.rendered", { preview_id: p.preview_id, project_id: p.project_id, viewport: p.viewport, width: Math.min(size.width, 4096), height: Math.min(size.height, 16_384),
|
|
135
|
+
title: facts.title ? facts.title.slice(0, 300) : null, http_status: p.target === "port" && facts.status >= 100 && facts.status <= 599 ? facts.status : null, bytes: png.length,
|
|
136
|
+
sha256: P.toBase64Url(createHash("sha256").update(png).digest()), chunks }, env.command_id);
|
|
137
|
+
return "taken";
|
|
138
|
+
} finally {
|
|
139
|
+
server?.close();
|
|
140
|
+
rmSync(profile, { recursive: true, force: true });
|
|
141
|
+
busy = false;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return { handle: (env, payload) => (env.type === "preview.targets" ? targets(env, payload) : render(env, payload)) };
|
|
146
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ROOTS AND NEW PROJECTS (owner, 2026-11-07: the phone's projects, each with its sessions, and a "New session" sheet
|
|
3
|
+
* whose project may be New, with a storage location). docs/remote-agents/PROTOCOL.md "Projects and sessions".
|
|
4
|
+
*
|
|
5
|
+
* A ROOT is a parent folder the person added at the keyboard (`worktrust remote roots add <dir> [--git-init]`), held to
|
|
6
|
+
* the same rule as a granted project (canonical, every symlink resolved, never the disk's root, the home folder or above
|
|
7
|
+
* it, never a folder of secrets). A phone may ask for ONE new, empty folder inside a root (`project.create`): a single
|
|
8
|
+
* name of [A-Za-z0-9._-] that does not start with a dot and does not exist yet. The computer makes that folder and nothing
|
|
9
|
+
* else (no parents, no files), checks after making it that it sits directly inside the root, grants it as a project, and
|
|
10
|
+
* runs `git init` in it only when the person enabled that for the root. Nothing a phone sends names a path.
|
|
11
|
+
*/
|
|
12
|
+
import { execFileSync } from "node:child_process";
|
|
13
|
+
import { createHmac } from "node:crypto";
|
|
14
|
+
import { existsSync, lstatSync, mkdirSync, realpathSync, rmdirSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { basename, dirname, join, relative, sep } from "node:path";
|
|
17
|
+
import * as P from "./remote-protocol.mjs";
|
|
18
|
+
import { canonicalProject } from "./remote-policy.mjs";
|
|
19
|
+
import { projectIdOf } from "./remote-store.mjs";
|
|
20
|
+
|
|
21
|
+
export const MAX_ROOTS = 20;
|
|
22
|
+
/** The inventory lists 30 projects; a phone creates no more than that (review 2026-11-07, P3-9). */
|
|
23
|
+
export const MAX_PROJECTS = 30;
|
|
24
|
+
|
|
25
|
+
export const rootIdOf = (projectSecret, canonicalPath) =>
|
|
26
|
+
`rot_${P.toBase64Url(createHmac("sha256", Buffer.from(projectSecret)).update(`worktrust-remote/v1/root\n${canonicalPath}`).digest().subarray(0, 16))}`;
|
|
27
|
+
|
|
28
|
+
/** "Desktop/WorkTrust" for a folder under the home folder; else its last two segments. Sealed, for the phone's picker. */
|
|
29
|
+
export function rootLabel(path) {
|
|
30
|
+
const home = homedir();
|
|
31
|
+
const inside = path.startsWith(home + sep) ? relative(home, path) : path.split(sep).filter(Boolean).slice(-2).join("/");
|
|
32
|
+
return (inside || basename(path) || path).split(sep).join("/").slice(0, 256);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `roots add`: the folder's canonical path under the project rule, or why not. */
|
|
36
|
+
export function checkRoot(dir) {
|
|
37
|
+
const canonical = canonicalProject(dir);
|
|
38
|
+
return canonical.ok ? { ok: true, path: canonical.path } : { ok: false, reason: canonical.reason.replace("granted: grant one project folder", "a root: add the folder your projects go in") };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The main repository a project's folder is a git WORKTREE of (owner, 2026-11-08: a worktree's sessions sit under its
|
|
43
|
+
* main repository on the phone), or null: the main checkout itself, a folder outside git, or git not answering in time.
|
|
44
|
+
* `git rev-parse --git-common-dir` names the main repository's .git for a worktree and the folder's own for the main
|
|
45
|
+
* checkout. Asked once per folder per run of the daemon; never a path a phone sent.
|
|
46
|
+
*/
|
|
47
|
+
const mains = new Map();
|
|
48
|
+
export function worktreeMain(path) {
|
|
49
|
+
if (mains.has(path)) return mains.get(path);
|
|
50
|
+
let main = null;
|
|
51
|
+
try {
|
|
52
|
+
const ask = (flag) => execFileSync("git", ["rev-parse", "--path-format=absolute", flag], { cwd: path, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5_000, windowsHide: true }).trim();
|
|
53
|
+
const common = ask("--git-common-dir");
|
|
54
|
+
const top = realpathSync(ask("--show-toplevel"));
|
|
55
|
+
if (basename(common) === ".git") { const repo = realpathSync(dirname(common)); if (repo !== top) main = repo; }
|
|
56
|
+
} catch { main = null; }
|
|
57
|
+
mains.set(path, main);
|
|
58
|
+
return main;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* project.create: → { ok: true, project, git } or { ok: false, reason } with a protocol reject reason. `o`: { name,
|
|
63
|
+
* root (a roots.json entry), projectSecret, projects, saveProjects, now }.
|
|
64
|
+
*/
|
|
65
|
+
export function createProject(o) {
|
|
66
|
+
if (!P.projectNameOk(o.name)) return { ok: false, reason: "unsupported" };
|
|
67
|
+
if (!o.root) return { ok: false, reason: "not_found" };
|
|
68
|
+
if (o.projects().length >= MAX_PROJECTS) return { ok: false, reason: "busy" };
|
|
69
|
+
const root = checkRoot(o.root.path);
|
|
70
|
+
if (!root.ok || root.path !== o.root.path) return { ok: false, reason: "not_found" }; // moved, gone, or now a link elsewhere
|
|
71
|
+
const target = join(root.path, o.name);
|
|
72
|
+
let exists = existsSync(target);
|
|
73
|
+
try { lstatSync(target); exists = true; } catch { /* free */ }
|
|
74
|
+
if (exists) return { ok: false, reason: "conflict" };
|
|
75
|
+
try { mkdirSync(target, { mode: 0o755 }); } catch { return { ok: false, reason: "conflict" }; } // one folder, no parents
|
|
76
|
+
const made = realpathSync(target);
|
|
77
|
+
if (dirname(made) !== root.path || basename(made) !== o.name) { try { rmdirSync(target); } catch { /* left empty */ } return { ok: false, reason: "conflict" }; }
|
|
78
|
+
let git = false;
|
|
79
|
+
if (o.root.git_init === true) {
|
|
80
|
+
try { execFileSync("git", ["init", "-q"], { cwd: made, stdio: "ignore", timeout: 15_000, windowsHide: true }); git = true; } catch { git = false; }
|
|
81
|
+
}
|
|
82
|
+
const list = o.projects();
|
|
83
|
+
const project_id = projectIdOf(o.projectSecret, made); // the id `worktrust remote projects add` gives the folder
|
|
84
|
+
o.saveProjects([...list.filter((p) => p.project_id !== project_id), { project_id, path: made, added_at: o.now(), root_id: o.root.root_id }]);
|
|
85
|
+
return { ok: true, git, project: { project_id, label: o.name.slice(0, 256), path: made.slice(0, 4096), root_id: o.root.root_id } };
|
|
86
|
+
}
|
|
87
|
+
|