pi-better-server 0.0.0-stage → 0.1.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/README.md +624 -2
- package/codex-plugin/.agents/plugins/marketplace.json +17 -0
- package/codex-plugin/plugins/pi-remote/.codex-plugin/plugin.json +20 -0
- package/codex-plugin/plugins/pi-remote/.mcp.json +13 -0
- package/codex-plugin/plugins/pi-remote/server.mjs +118 -0
- package/codex-plugin/plugins/pi-remote/skills/pi-remote/SKILL.md +19 -0
- package/package.json +60 -4
- package/scripts/bootstrap-host.sh +107 -0
- package/scripts/private-runtime/format.ts +65 -0
- package/scripts/private-runtime/installer.ts +166 -0
- package/scripts/private-runtime/package-lock.json +1491 -0
- package/scripts/private-runtime/package.json +17 -0
- package/scripts/test-on-pi.sh +34 -0
- package/src/cli-args.ts +38 -0
- package/src/cli.ts +90 -0
- package/src/client.ts +152 -0
- package/src/codex/adapter.ts +299 -0
- package/src/codex/app-server.ts +112 -0
- package/src/codex/daemon.ts +232 -0
- package/src/codex/deliver.ts +103 -0
- package/src/codex/preflight.ts +15 -0
- package/src/codex/provider.ts +55 -0
- package/src/codex/return.ts +110 -0
- package/src/codex/rollout.ts +160 -0
- package/src/codex/runtime.ts +126 -0
- package/src/codex/ws-unix.ts +112 -0
- package/src/companion.ts +96 -0
- package/src/control.ts +85 -0
- package/src/core/adapter.ts +109 -0
- package/src/core/bundle.ts +764 -0
- package/src/core/exclusions.ts +53 -0
- package/src/core/move-host.ts +268 -0
- package/src/core/ownership.ts +135 -0
- package/src/core/transfer.ts +73 -0
- package/src/daemon-owner.ts +130 -0
- package/src/detach/detach.ts +150 -0
- package/src/detach/extension.ts +244 -0
- package/src/detach/local-sink.ts +203 -0
- package/src/detach/local-source.ts +133 -0
- package/src/detach/local-state.ts +87 -0
- package/src/detach/recover.ts +53 -0
- package/src/event-log.ts +163 -0
- package/src/git.ts +35 -0
- package/src/handshake.ts +57 -0
- package/src/hosted-session.ts +576 -0
- package/src/index.ts +31 -0
- package/src/lifecycle-config.ts +29 -0
- package/src/maintenance.ts +317 -0
- package/src/move/auth.ts +16 -0
- package/src/move/orchestrate.ts +163 -0
- package/src/move/pi-adapter.ts +181 -0
- package/src/move/preflight.ts +197 -0
- package/src/move/service.ts +16 -0
- package/src/paths.ts +52 -0
- package/src/protocol.ts +212 -0
- package/src/registry.ts +559 -0
- package/src/remote/answer.ts +95 -0
- package/src/remote/attach-codex.ts +41 -0
- package/src/remote/attach.ts +41 -0
- package/src/remote/console.ts +126 -0
- package/src/remote/context.ts +75 -0
- package/src/remote/cursors.ts +36 -0
- package/src/remote/ls.ts +44 -0
- package/src/remote/move.ts +85 -0
- package/src/remote/new.ts +37 -0
- package/src/remote/process-runner.ts +51 -0
- package/src/remote/recover.ts +35 -0
- package/src/remote/return.ts +49 -0
- package/src/remote/sessions.ts +33 -0
- package/src/remote/steer.ts +40 -0
- package/src/remote/tail.ts +91 -0
- package/src/remote/target.ts +313 -0
- package/src/remote-cli.ts +73 -0
- package/src/remote-client/connection-progress.ts +62 -0
- package/src/remote-client/extension.ts +396 -0
- package/src/remote-client/folder-browser.ts +165 -0
- package/src/remote-client/host.ts +130 -0
- package/src/remote-client/local-work.ts +62 -0
- package/src/remote-client/menu.ts +68 -0
- package/src/remote-client/packages.ts +345 -0
- package/src/remote-client/pi-1.2-bridge.ts +542 -0
- package/src/remote-client/profiles.ts +38 -0
- package/src/remote-client/remote-progress.ts +39 -0
- package/src/remote-client/session-browser.ts +270 -0
- package/src/remote-client/session.ts +1205 -0
- package/src/remote-client/ssh-hosts.ts +185 -0
- package/src/remote-client/transfer-command.ts +189 -0
- package/src/remote-client/upgrade-transport.ts +105 -0
- package/src/server.ts +398 -0
- package/src/session-activity.ts +173 -0
- package/src/shared-ssh-core/index.ts +950 -0
- package/src/startup/activation.ts +621 -0
- package/src/startup/admission.ts +98 -0
- package/src/startup/artifact.ts +65 -0
- package/src/startup/commands.ts +37 -0
- package/src/startup/ensure.ts +137 -0
- package/src/startup/install.ts +115 -0
- package/src/startup/managed-types.ts +61 -0
- package/src/startup/runtime.ts +138 -0
- package/src/ui-bridge.ts +124 -0
|
@@ -0,0 +1,764 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session bundle: one tar archive that carries a coding session and its git
|
|
3
|
+
* workspace between hosts. Agent-agnostic (no Pi imports): the caller says which
|
|
4
|
+
* session files and state to include and what agent produced them.
|
|
5
|
+
*
|
|
6
|
+
* Archive layout (all members are regular files; symlinks travel in the manifest):
|
|
7
|
+
* manifest.json BundleManifest, see below
|
|
8
|
+
* git.bundle `git bundle` of the branch (or HEAD) plus the base ref
|
|
9
|
+
* tracked.patch `git diff --binary HEAD` for dirty tracked files (optional)
|
|
10
|
+
* untracked/<path> untracked, non-ignored files that pass the exclusion rules
|
|
11
|
+
* session/<name> session transcript files
|
|
12
|
+
* state/<name> session-scoped harness state
|
|
13
|
+
*
|
|
14
|
+
* The manifest checksums every member and also the full worktree, so a restore can
|
|
15
|
+
* prove the rebuilt tree is the one that left. It never lists credential content.
|
|
16
|
+
*/
|
|
17
|
+
import { execFileSync } from "node:child_process";
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import {
|
|
20
|
+
chmodSync,
|
|
21
|
+
closeSync,
|
|
22
|
+
copyFileSync,
|
|
23
|
+
existsSync,
|
|
24
|
+
lstatSync,
|
|
25
|
+
mkdirSync,
|
|
26
|
+
mkdtempSync,
|
|
27
|
+
openSync,
|
|
28
|
+
readdirSync,
|
|
29
|
+
readFileSync,
|
|
30
|
+
readlinkSync,
|
|
31
|
+
readSync,
|
|
32
|
+
rmSync,
|
|
33
|
+
statSync,
|
|
34
|
+
symlinkSync,
|
|
35
|
+
writeFileSync,
|
|
36
|
+
} from "node:fs";
|
|
37
|
+
import { dirname, isAbsolute, join, posix, resolve, sep } from "node:path";
|
|
38
|
+
import { exclusionReason } from "./exclusions.ts";
|
|
39
|
+
|
|
40
|
+
export const BUNDLE_FORMAT_VERSION = 1;
|
|
41
|
+
|
|
42
|
+
// Match the existing 1 GiB git-output bound; compressed input must not expand beyond it.
|
|
43
|
+
const MAX_BUNDLE_BYTES = 1024 * 1024 * 1024;
|
|
44
|
+
|
|
45
|
+
// Keep the public bundle APIs synchronous, but stream gzip I/O in a Node child so
|
|
46
|
+
// neither compression nor decompression needs to hold the whole archive in memory.
|
|
47
|
+
const GZIP_SCRIPT = `
|
|
48
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
49
|
+
import { Transform } from "node:stream";
|
|
50
|
+
import { pipeline } from "node:stream/promises";
|
|
51
|
+
import { createGzip, createGunzip } from "node:zlib";
|
|
52
|
+
const [mode, source, target, limit] = process.argv.slice(1);
|
|
53
|
+
let bytes = 0;
|
|
54
|
+
const bound = new Transform({
|
|
55
|
+
transform(chunk, encoding, callback) {
|
|
56
|
+
bytes += chunk.length;
|
|
57
|
+
if (bytes > Number(limit)) callback(new Error("Bundle exceeds uncompressed byte limit (" + limit + ")"));
|
|
58
|
+
else callback(null, chunk);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
const codec = mode === "gzip" ? createGzip() : createGunzip();
|
|
62
|
+
try {
|
|
63
|
+
await pipeline(createReadStream(source), ...(mode === "gzip" ? [bound, codec] : [codec, bound]), createWriteStream(target, { flags: "wx", mode: 0o600 }));
|
|
64
|
+
} catch (error) {
|
|
65
|
+
process.stderr.write(error.message);
|
|
66
|
+
process.exitCode = 1;
|
|
67
|
+
}
|
|
68
|
+
`;
|
|
69
|
+
|
|
70
|
+
export type BundleFileRole = "git-bundle" | "tracked-patch" | "untracked" | "session" | "state";
|
|
71
|
+
|
|
72
|
+
export interface BundleFile {
|
|
73
|
+
/** Path inside the archive. */
|
|
74
|
+
path: string;
|
|
75
|
+
role: BundleFileRole;
|
|
76
|
+
sha256: string;
|
|
77
|
+
size: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface WorktreeEntry {
|
|
81
|
+
/** Repo-relative path. */
|
|
82
|
+
path: string;
|
|
83
|
+
/** Hex sha256 of the file content, or of the link target for a symlink. */
|
|
84
|
+
sha256: string;
|
|
85
|
+
mode: "644" | "755" | "symlink";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface BundleManifest {
|
|
89
|
+
formatVersion: typeof BUNDLE_FORMAT_VERSION;
|
|
90
|
+
createdAt: string;
|
|
91
|
+
/** The agent that produced the session files; the importing side decides whether it can read them. */
|
|
92
|
+
agent: { kind: string; version: string; extensions: Record<string, string> };
|
|
93
|
+
session: { id: string; name?: string; model?: string; createdAt?: string; metadata?: Record<string, unknown> };
|
|
94
|
+
/** Logical-session ownership at export time; the importer takes epoch + 1. */
|
|
95
|
+
ownership: { epoch: number; from: string; moveId: string };
|
|
96
|
+
/** False means only session/state files; omission means a legacy full-workspace bundle. */
|
|
97
|
+
workspaceIncluded?: boolean;
|
|
98
|
+
repo: {
|
|
99
|
+
remote?: string;
|
|
100
|
+
branch?: string;
|
|
101
|
+
head: string;
|
|
102
|
+
/** Ref the bundle also carries so the target can diff against it. */
|
|
103
|
+
baseRef?: string;
|
|
104
|
+
baseSha?: string;
|
|
105
|
+
};
|
|
106
|
+
files: BundleFile[];
|
|
107
|
+
/** Untracked symlinks, recreated on restore. */
|
|
108
|
+
symlinks: Array<{ path: string; target: string }>;
|
|
109
|
+
/** Paths left out and why. Never the content. */
|
|
110
|
+
excluded: Array<{ path: string; reason: "credential" | "generated" }>;
|
|
111
|
+
/** Digest of every file the worktree should hold after restore. */
|
|
112
|
+
worktree: WorktreeEntry[];
|
|
113
|
+
totals: { files: number; bytes: number; worktreeFiles: number; worktreeBytes: number };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface CreateBundleOptions {
|
|
117
|
+
/** Top-level directory of the git work tree, or any cwd when includeWorkspace is false. */
|
|
118
|
+
cwd: string;
|
|
119
|
+
outFile: string;
|
|
120
|
+
/** Transfer encoding only; defaults to plain tar for older receivers. The filename need not change. */
|
|
121
|
+
compression?: "gzip" | "none";
|
|
122
|
+
/** Defaults to true. False carries only session/state and never calls git. */
|
|
123
|
+
includeWorkspace?: boolean;
|
|
124
|
+
agent: BundleManifest["agent"];
|
|
125
|
+
session: BundleManifest["session"];
|
|
126
|
+
ownership: BundleManifest["ownership"];
|
|
127
|
+
/** Transcript files to carry, stored as `session/<name>`. */
|
|
128
|
+
sessionFiles?: Array<{ name: string; path: string }>;
|
|
129
|
+
/** Harness state to carry, stored as `state/<name>`. */
|
|
130
|
+
stateFiles?: Array<{ name: string; content: string | Buffer }>;
|
|
131
|
+
/** Branch the work is based on; default: the first of origin/main, origin/master, main, master that exists. */
|
|
132
|
+
baseRef?: string;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class BundleError extends Error {
|
|
136
|
+
constructor(message: string) {
|
|
137
|
+
super(message);
|
|
138
|
+
this.name = "BundleError";
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function git(cwd: string, args: string[], options: { input?: Buffer; allowFailure?: boolean } = {}): Buffer {
|
|
143
|
+
try {
|
|
144
|
+
return execFileSync("git", args, {
|
|
145
|
+
cwd,
|
|
146
|
+
input: options.input,
|
|
147
|
+
maxBuffer: 1024 * 1024 * 1024,
|
|
148
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
149
|
+
env: { ...process.env, GIT_LITERAL_PATHSPECS: "1", GIT_TERMINAL_PROMPT: "0" },
|
|
150
|
+
});
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (options.allowFailure) return Buffer.alloc(0);
|
|
153
|
+
const stderr = (error as { stderr?: Buffer }).stderr?.toString().trim();
|
|
154
|
+
throw new BundleError(`git ${args[0]} failed${stderr ? `: ${stderr}` : ""}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function gitText(cwd: string, args: string[], allowFailure = false): string {
|
|
159
|
+
return git(cwd, args, { allowFailure }).toString("utf8").trim();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function splitNul(buffer: Buffer): string[] {
|
|
163
|
+
return buffer.toString("utf8").split("\0").filter(Boolean);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function sha256File(path: string): string {
|
|
167
|
+
const hash = createHash("sha256");
|
|
168
|
+
const fd = openSync(path, "r");
|
|
169
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
170
|
+
try {
|
|
171
|
+
for (;;) {
|
|
172
|
+
const bytes = readSync(fd, buffer, 0, buffer.length, null);
|
|
173
|
+
if (bytes === 0) break;
|
|
174
|
+
hash.update(buffer.subarray(0, bytes));
|
|
175
|
+
}
|
|
176
|
+
return hash.digest("hex");
|
|
177
|
+
} finally {
|
|
178
|
+
closeSync(fd);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function sha256Of(data: string | Buffer): string {
|
|
183
|
+
return createHash("sha256").update(data).digest("hex");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Paths git considers part of the worktree (tracked + untracked, not ignored) that the bundle policy allows. */
|
|
187
|
+
function worktreePaths(cwd: string): { included: string[]; excluded: Array<{ path: string; reason: "credential" | "generated" }> } {
|
|
188
|
+
const all = splitNul(git(cwd, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]));
|
|
189
|
+
const included: string[] = [];
|
|
190
|
+
const excluded: Array<{ path: string; reason: "credential" | "generated" }> = [];
|
|
191
|
+
for (const path of [...new Set(all)].sort()) {
|
|
192
|
+
const reason = exclusionReason(path);
|
|
193
|
+
if (reason) excluded.push({ path, reason });
|
|
194
|
+
else included.push(path);
|
|
195
|
+
}
|
|
196
|
+
return { included, excluded };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Checksums of the files a restored worktree must hold. Same function runs on both ends.
|
|
201
|
+
* Throws when a listed path is a directory (nested repo / submodule): the move is refused rather than silently omitting it.
|
|
202
|
+
*/
|
|
203
|
+
export function digestWorktree(cwd: string): WorktreeEntry[] {
|
|
204
|
+
const entries: WorktreeEntry[] = [];
|
|
205
|
+
const nested: string[] = [];
|
|
206
|
+
for (const path of worktreePaths(cwd).included) {
|
|
207
|
+
const full = join(cwd, path);
|
|
208
|
+
let info;
|
|
209
|
+
try {
|
|
210
|
+
info = lstatSync(full);
|
|
211
|
+
} catch {
|
|
212
|
+
continue; // tracked but deleted in the work tree
|
|
213
|
+
}
|
|
214
|
+
if (info.isSymbolicLink()) {
|
|
215
|
+
entries.push({ path, sha256: sha256Of(readlinkSync(full)), mode: "symlink" });
|
|
216
|
+
} else if (info.isFile()) {
|
|
217
|
+
entries.push({ path, sha256: sha256File(full), mode: info.mode & 0o111 ? "755" : "644" });
|
|
218
|
+
} else if (info.isDirectory()) {
|
|
219
|
+
// Untracked nested git repo or submodule: its contents are not part of this repo's history or file list.
|
|
220
|
+
nested.push(path);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (nested.length > 0) {
|
|
224
|
+
throw new BundleError(
|
|
225
|
+
`${nested.join(", ")} ${nested.length === 1 ? "is a nested git repository or submodule" : "are nested git repositories or submodules"}; a bundle cannot carry ${nested.length === 1 ? "it" : "them"}. Commit and push ${nested.length === 1 ? "it" : "them"} separately, or move ${nested.length === 1 ? "it" : "them"} out of the workspace, then retry the move.`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
return entries;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function detectBase(cwd: string, branch: string | undefined, requested: string | undefined): string | undefined {
|
|
232
|
+
const candidates = requested ? [requested] : ["origin/main", "origin/master", "main", "master"];
|
|
233
|
+
for (const candidate of candidates) {
|
|
234
|
+
if (candidate === branch) continue;
|
|
235
|
+
if (git(cwd, ["rev-parse", "--verify", "--quiet", `${candidate}^{commit}`], { allowFailure: true }).length > 0) return candidate;
|
|
236
|
+
}
|
|
237
|
+
if (requested) throw new BundleError(`Base ref ${requested} does not exist in ${cwd}`);
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function stageFile(stage: string, archivePath: string, source: string | Buffer, files: BundleFile[], role: BundleFileRole): void {
|
|
242
|
+
const target = join(stage, archivePath);
|
|
243
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
244
|
+
if (typeof source === "string") copyFileSync(source, target);
|
|
245
|
+
else writeFileSync(target, source);
|
|
246
|
+
files.push({ path: archivePath, role, sha256: sha256File(target), size: statSync(target).size });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function tar(args: string[]): void {
|
|
250
|
+
try {
|
|
251
|
+
execFileSync("tar", args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, COPYFILE_DISABLE: "1" } });
|
|
252
|
+
} catch (error) {
|
|
253
|
+
const stderr = (error as { stderr?: Buffer }).stderr?.toString().trim();
|
|
254
|
+
throw new BundleError(`tar failed${stderr ? `: ${stderr}` : ""}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function isBsdTar(): boolean {
|
|
259
|
+
return execFileSync("tar", ["--version"], { encoding: "utf8" }).includes("bsdtar");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Stage workspace data without touching the source worktree. Only full-workspace bundles call this. */
|
|
263
|
+
function stageWorkspace(cwd: string, scratch: string, files: BundleFile[], requestedBase?: string): Pick<BundleManifest, "repo" | "symlinks" | "excluded" | "worktree"> {
|
|
264
|
+
const root = gitText(cwd, ["rev-parse", "--show-toplevel"], true);
|
|
265
|
+
if (!root) throw new BundleError(`${cwd} is not inside a git work tree; a session can only move with a git workspace`);
|
|
266
|
+
if (resolve(root) !== resolve(cwd) && !existsSync(join(cwd, ".git"))) {
|
|
267
|
+
throw new BundleError(`${cwd} is not the top of its git work tree (${root}); move the session from the repository root`);
|
|
268
|
+
}
|
|
269
|
+
const head = gitText(cwd, ["rev-parse", "--verify", "HEAD"], true);
|
|
270
|
+
if (!head) throw new BundleError(`${cwd} has no commits yet; commit once so the history can travel`);
|
|
271
|
+
const branch = gitText(cwd, ["symbolic-ref", "--short", "-q", "HEAD"], true) || undefined;
|
|
272
|
+
const remote = gitText(cwd, ["remote", "get-url", "origin"], true) || undefined;
|
|
273
|
+
const baseRef = detectBase(cwd, branch, requestedBase);
|
|
274
|
+
const baseSha = baseRef ? gitText(cwd, ["rev-parse", `${baseRef}^{commit}`]) : undefined;
|
|
275
|
+
const excluded = new Map<string, "credential" | "generated">();
|
|
276
|
+
|
|
277
|
+
// History: the branch (or detached HEAD) and the base ref, as a git bundle.
|
|
278
|
+
const gitBundle = join(scratch, "git.bundle.tmp");
|
|
279
|
+
const refs = [branch ? `refs/heads/${branch}` : "HEAD", ...(baseRef ? [baseRef] : [])];
|
|
280
|
+
git(cwd, ["bundle", "create", gitBundle, ...refs]);
|
|
281
|
+
stageFile(scratch, "git.bundle", gitBundle, files, "git-bundle");
|
|
282
|
+
rmSync(gitBundle);
|
|
283
|
+
|
|
284
|
+
// Dirty tracked changes (staged and unstaged) against HEAD, minus excluded paths.
|
|
285
|
+
const changed = splitNul(git(cwd, ["diff", "-z", "--name-only", "--no-renames", "HEAD"]));
|
|
286
|
+
const patchPaths: string[] = [];
|
|
287
|
+
for (const path of changed) {
|
|
288
|
+
const reason = exclusionReason(path);
|
|
289
|
+
if (reason) excluded.set(path, reason);
|
|
290
|
+
else patchPaths.push(path);
|
|
291
|
+
}
|
|
292
|
+
if (patchPaths.length > 0) {
|
|
293
|
+
const patch = git(cwd, ["diff", "--binary", "--no-renames", "--no-ext-diff", "HEAD", "--", ...patchPaths]);
|
|
294
|
+
stageFile(scratch, "tracked.patch", patch, files, "tracked-patch");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Untracked, non-ignored files, minus excluded paths.
|
|
298
|
+
const symlinks: BundleManifest["symlinks"] = [];
|
|
299
|
+
for (const path of splitNul(git(cwd, ["ls-files", "-z", "--others", "--exclude-standard"])).sort()) {
|
|
300
|
+
const reason = exclusionReason(path);
|
|
301
|
+
if (reason) {
|
|
302
|
+
excluded.set(path, reason);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
const full = join(cwd, path);
|
|
306
|
+
const info = lstatSync(full);
|
|
307
|
+
if (info.isSymbolicLink()) {
|
|
308
|
+
// Fail here rather than ship a bundle whose link restore would refuse.
|
|
309
|
+
const link = { path, target: readlinkSync(full) };
|
|
310
|
+
assertSafeSymlinkTarget(link);
|
|
311
|
+
symlinks.push(link);
|
|
312
|
+
} else if (info.isFile()) {
|
|
313
|
+
stageFile(scratch, `untracked/${path}`, full, files, "untracked");
|
|
314
|
+
if (info.mode & 0o111) chmodSync(join(scratch, "untracked", path), info.mode & 0o777);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
repo: { ...(remote ? { remote } : {}), ...(branch ? { branch } : {}), head, ...(baseRef ? { baseRef, baseSha } : {}) },
|
|
319
|
+
symlinks,
|
|
320
|
+
excluded: [...excluded].map(([path, reason]) => ({ path, reason })).sort((a, b) => a.path.localeCompare(b.path)),
|
|
321
|
+
worktree: digestWorktree(cwd),
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function gzipFile(mode: "gzip" | "gunzip", source: string, target: string, limit: number): void {
|
|
326
|
+
try {
|
|
327
|
+
execFileSync(process.execPath, ["--input-type=module", "-e", GZIP_SCRIPT, mode, source, target, String(limit)], {
|
|
328
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
329
|
+
maxBuffer: 64 * 1024,
|
|
330
|
+
});
|
|
331
|
+
} catch (error) {
|
|
332
|
+
const stderr = (error as { stderr?: Buffer }).stderr?.toString().trim();
|
|
333
|
+
throw new BundleError(`Bundle gzip ${mode === "gzip" ? "compression" : "decompression"} failed${stderr ? `: ${stderr}` : ""}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Package session/state and, by default, its workspace. Compression never alters session content. */
|
|
338
|
+
export function createBundle(options: CreateBundleOptions): BundleManifest {
|
|
339
|
+
if (options.compression !== undefined && options.compression !== "gzip" && options.compression !== "none") {
|
|
340
|
+
throw new BundleError("Bundle compression must be gzip or none");
|
|
341
|
+
}
|
|
342
|
+
if (options.includeWorkspace !== undefined && typeof options.includeWorkspace !== "boolean") {
|
|
343
|
+
throw new BundleError("Bundle includeWorkspace must be a boolean");
|
|
344
|
+
}
|
|
345
|
+
const cwd = resolve(options.cwd);
|
|
346
|
+
const scratch = mkdtempSync(join(dirname(resolve(options.outFile)), ".bundle-stage-"));
|
|
347
|
+
try {
|
|
348
|
+
const files: BundleFile[] = [];
|
|
349
|
+
const workspace = options.includeWorkspace === false
|
|
350
|
+
? { repo: { head: "" }, symlinks: [], excluded: [], worktree: [] }
|
|
351
|
+
: stageWorkspace(cwd, scratch, files, options.baseRef);
|
|
352
|
+
|
|
353
|
+
for (const file of options.sessionFiles ?? []) {
|
|
354
|
+
assertPlainName(file.name);
|
|
355
|
+
stageFile(scratch, `session/${file.name}`, file.path, files, "session");
|
|
356
|
+
}
|
|
357
|
+
for (const file of options.stateFiles ?? []) {
|
|
358
|
+
assertPlainName(file.name);
|
|
359
|
+
stageFile(scratch, `state/${file.name}`, typeof file.content === "string" ? Buffer.from(file.content) : file.content, files, "state");
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const totals = {
|
|
363
|
+
files: files.length,
|
|
364
|
+
bytes: files.reduce((sum, file) => sum + file.size, 0),
|
|
365
|
+
worktreeFiles: workspace.worktree.length,
|
|
366
|
+
worktreeBytes: workspace.worktree.reduce((sum, entry) => sum + (entry.mode === "symlink" ? 0 : statSync(join(cwd, entry.path)).size), 0),
|
|
367
|
+
};
|
|
368
|
+
const manifest: BundleManifest = {
|
|
369
|
+
formatVersion: BUNDLE_FORMAT_VERSION,
|
|
370
|
+
createdAt: new Date().toISOString(),
|
|
371
|
+
agent: options.agent,
|
|
372
|
+
session: options.session,
|
|
373
|
+
ownership: options.ownership,
|
|
374
|
+
...(options.includeWorkspace === false ? { workspaceIncluded: false } : {}),
|
|
375
|
+
...workspace,
|
|
376
|
+
files,
|
|
377
|
+
totals,
|
|
378
|
+
};
|
|
379
|
+
writeFileSync(join(scratch, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
380
|
+
|
|
381
|
+
const members = ["manifest.json", ...["git.bundle", "tracked.patch", "untracked", "session", "state"].filter((m) => existsSync(join(scratch, m)))];
|
|
382
|
+
const archive = options.compression === "gzip" ? join(scratch, "payload.tar") : resolve(options.outFile);
|
|
383
|
+
// macOS bsdtar would otherwise embed extended attributes that GNU tar warns about on the target.
|
|
384
|
+
tar(["-cf", archive, ...(isBsdTar() ? ["--no-xattrs"] : []), "-C", scratch, ...members]);
|
|
385
|
+
if (options.compression === "gzip") {
|
|
386
|
+
const compressed = join(scratch, "payload.tar.gz");
|
|
387
|
+
gzipFile("gzip", archive, compressed, MAX_BUNDLE_BYTES);
|
|
388
|
+
copyFileSync(compressed, resolve(options.outFile));
|
|
389
|
+
}
|
|
390
|
+
return manifest;
|
|
391
|
+
} finally {
|
|
392
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function assertPlainName(name: string): void {
|
|
397
|
+
if (!name || name.includes("/") || name.includes("\\") || name === "." || name === ".." || name.startsWith("-")) {
|
|
398
|
+
throw new BundleError(`Unsafe bundle member name: ${JSON.stringify(name)}`);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export interface ExtractedBundle {
|
|
403
|
+
manifest: BundleManifest;
|
|
404
|
+
/** Directory holding the verified members; the caller removes it. */
|
|
405
|
+
dir: string;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export interface VerifyBundleOptions {
|
|
409
|
+
/** Limit for decoded tar bytes, including headers; may lower but not raise the 1 GiB bound. */
|
|
410
|
+
maxUncompressedBytes?: number;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Detect gzip by content, not filename, and finish bounded decompression before tar sees it. */
|
|
414
|
+
export function verifyBundle(archive: string, workDir: string, options: VerifyBundleOptions = {}): ExtractedBundle {
|
|
415
|
+
const limit = options.maxUncompressedBytes ?? MAX_BUNDLE_BYTES;
|
|
416
|
+
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_BUNDLE_BYTES) {
|
|
417
|
+
throw new BundleError(`Bundle uncompressed byte limit must be an integer between 1 and ${MAX_BUNDLE_BYTES}`);
|
|
418
|
+
}
|
|
419
|
+
if (statSync(archive).size > MAX_BUNDLE_BYTES) throw new BundleError("Bundle exceeds archive byte limit");
|
|
420
|
+
const fd = openSync(archive, "r");
|
|
421
|
+
const magic = Buffer.alloc(2);
|
|
422
|
+
try {
|
|
423
|
+
readSync(fd, magic, 0, magic.length, 0);
|
|
424
|
+
} finally {
|
|
425
|
+
closeSync(fd);
|
|
426
|
+
}
|
|
427
|
+
if (magic[0] !== 0x1f || magic[1] !== 0x8b) {
|
|
428
|
+
if (statSync(archive).size > limit) throw new BundleError("Bundle exceeds uncompressed byte limit");
|
|
429
|
+
return verifyTarBundle(archive, workDir);
|
|
430
|
+
}
|
|
431
|
+
mkdirSync(workDir, { recursive: true });
|
|
432
|
+
const scratch = mkdtempSync(join(workDir, ".bundle-inflate-"));
|
|
433
|
+
try {
|
|
434
|
+
const plain = join(scratch, "payload.tar");
|
|
435
|
+
gzipFile("gunzip", resolve(archive), plain, limit);
|
|
436
|
+
return verifyTarBundle(plain, workDir);
|
|
437
|
+
} finally {
|
|
438
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// System tar autodetects other compression formats too. Require a tar header so
|
|
443
|
+
// it cannot perform a second, unbounded decompression after our gzip byte check.
|
|
444
|
+
function assertPlainTar(archive: string): void {
|
|
445
|
+
const fd = openSync(archive, "r");
|
|
446
|
+
const header = Buffer.alloc(512);
|
|
447
|
+
let bytes: number;
|
|
448
|
+
try {
|
|
449
|
+
bytes = readSync(fd, header, 0, header.length, 0);
|
|
450
|
+
} finally {
|
|
451
|
+
closeSync(fd);
|
|
452
|
+
}
|
|
453
|
+
if (bytes === 512 && header.every((byte) => byte === 0)) return;
|
|
454
|
+
const checksum = header.toString("ascii", 148, 156).replace(/\0.*$/, "").trim();
|
|
455
|
+
let unsigned = 0;
|
|
456
|
+
let signed = 0;
|
|
457
|
+
for (let i = 0; i < header.length; i++) {
|
|
458
|
+
const byte = i >= 148 && i < 156 ? 32 : header[i]!;
|
|
459
|
+
unsigned += byte;
|
|
460
|
+
signed += byte > 127 ? byte - 256 : byte;
|
|
461
|
+
}
|
|
462
|
+
const expected = Number.parseInt(checksum, 8);
|
|
463
|
+
if (bytes !== 512 || !/^[0-7]+$/.test(checksum) || (expected !== unsigned && expected !== signed)) {
|
|
464
|
+
throw new BundleError("Bundle payload is not a plain tar archive");
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Unpack a plain tar into a fresh directory and check every member, checksum and
|
|
470
|
+
* size against its manifest, retaining the same path and workspace safety checks.
|
|
471
|
+
*/
|
|
472
|
+
function verifyTarBundle(archive: string, workDir: string): ExtractedBundle {
|
|
473
|
+
assertPlainTar(archive); const listing = execFileSync("tar", ["-tvf", archive], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024, env: { ...process.env, COPYFILE_DISABLE: "1" } });
|
|
474
|
+
for (const line of listing.split("\n").filter(Boolean)) {
|
|
475
|
+
if (line[0] !== "-" && line[0] !== "d") throw new BundleError(`Bundle has a member that is not a plain file or directory: ${line}`);
|
|
476
|
+
}
|
|
477
|
+
const names = execFileSync("tar", ["-tf", archive], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }).split("\n").filter(Boolean);
|
|
478
|
+
for (const name of names) {
|
|
479
|
+
if (name.startsWith("/") || name.split("/").includes("..")) throw new BundleError(`Bundle member escapes the archive: ${name}`);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
mkdirSync(workDir, { recursive: true });
|
|
483
|
+
const dir = mkdtempSync(join(workDir, "extract-"));
|
|
484
|
+
try {
|
|
485
|
+
tar(["-xf", archive, "-C", dir]);
|
|
486
|
+
const manifestPath = join(dir, "manifest.json");
|
|
487
|
+
if (!existsSync(manifestPath)) throw new BundleError("Bundle has no manifest.json");
|
|
488
|
+
let manifest: BundleManifest;
|
|
489
|
+
try {
|
|
490
|
+
manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as BundleManifest;
|
|
491
|
+
} catch {
|
|
492
|
+
throw new BundleError("Bundle manifest is not valid JSON");
|
|
493
|
+
}
|
|
494
|
+
if (manifest.formatVersion !== BUNDLE_FORMAT_VERSION) {
|
|
495
|
+
throw new BundleError(`Unsupported bundle format ${String(manifest.formatVersion)}; this build reads format ${BUNDLE_FORMAT_VERSION}`);
|
|
496
|
+
}
|
|
497
|
+
assertWorkspaceIncluded(manifest);
|
|
498
|
+
const listed = new Set<string>();
|
|
499
|
+
let bytes = 0;
|
|
500
|
+
for (const file of manifest.files) {
|
|
501
|
+
if (file.path.startsWith("/") || file.path.split("/").includes("..")) throw new BundleError(`Manifest path escapes the bundle: ${file.path}`);
|
|
502
|
+
const full = join(dir, file.path);
|
|
503
|
+
if (!existsSync(full) || !statSync(full).isFile()) throw new BundleError(`Bundle is missing ${file.path}`);
|
|
504
|
+
if (statSync(full).size !== file.size) throw new BundleError(`Size mismatch for ${file.path}`);
|
|
505
|
+
if (sha256File(full) !== file.sha256) throw new BundleError(`Checksum mismatch for ${file.path}`);
|
|
506
|
+
listed.add(file.path);
|
|
507
|
+
bytes += file.size;
|
|
508
|
+
}
|
|
509
|
+
if (manifest.totals.files !== manifest.files.length || manifest.totals.bytes !== bytes) throw new BundleError("Manifest totals do not match its file list");
|
|
510
|
+
for (const found of walkFiles(dir)) {
|
|
511
|
+
if (found !== "manifest.json" && !listed.has(found)) throw new BundleError(`Bundle holds ${found}, which the manifest does not list`);
|
|
512
|
+
}
|
|
513
|
+
for (const entry of manifest.worktree) {
|
|
514
|
+
const reason = exclusionReason(entry.path);
|
|
515
|
+
if (reason) throw new BundleError(`Bundle worktree lists ${reason} path ${entry.path}`);
|
|
516
|
+
}
|
|
517
|
+
assertSafeWorkspaceEntries(manifest);
|
|
518
|
+
return { manifest, dir };
|
|
519
|
+
} catch (error) {
|
|
520
|
+
rmSync(dir, { recursive: true, force: true });
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function assertWorkspaceIncluded(manifest: BundleManifest): void {
|
|
526
|
+
if (Object.hasOwn(manifest, "workspaceIncluded") && typeof manifest.workspaceIncluded !== "boolean") {
|
|
527
|
+
throw new BundleError("Manifest workspaceIncluded must be a boolean");
|
|
528
|
+
}
|
|
529
|
+
if (manifest.workspaceIncluded !== false) return;
|
|
530
|
+
if (
|
|
531
|
+
!manifest.repo || manifest.repo.head !== "" || Object.keys(manifest.repo).some((key) => key !== "head") ||
|
|
532
|
+
!Array.isArray(manifest.worktree) || manifest.worktree.length !== 0 ||
|
|
533
|
+
!Array.isArray(manifest.symlinks) || manifest.symlinks.length !== 0 ||
|
|
534
|
+
!Array.isArray(manifest.excluded) || manifest.excluded.length !== 0 ||
|
|
535
|
+
!manifest.totals || manifest.totals.worktreeFiles !== 0 || manifest.totals.worktreeBytes !== 0 ||
|
|
536
|
+
!Array.isArray(manifest.files) || manifest.files.some((file) =>
|
|
537
|
+
!file || (file.role !== "session" && file.role !== "state") ||
|
|
538
|
+
typeof file.path !== "string" || !file.path.startsWith(`${file.role}/`) ||
|
|
539
|
+
!/^[^/\\\\]+$/.test(file.path.slice(file.role.length + 1)))
|
|
540
|
+
) {
|
|
541
|
+
throw new BundleError("Session-only bundle must not contain workspace data");
|
|
542
|
+
}
|
|
543
|
+
for (const file of manifest.files) assertPlainName(file.path.slice(file.role.length + 1));
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Bundle paths and link targets use POSIX semantics, as the restoring filesystem does: '/' is the only separator. */
|
|
547
|
+
function pathSegments(path: string): string[] {
|
|
548
|
+
return path.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function hasGitSegment(path: string): boolean {
|
|
552
|
+
return pathSegments(path).some(isDotGitName);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** A segment that names `.git` on some filesystem: case variants, plus the NTFS aliases git's is_ntfs_dotgit refuses ('.git.', '.git ', 'git~1', a ':stream' suffix). */
|
|
556
|
+
function isDotGitName(segment: string): boolean {
|
|
557
|
+
const name = segment.toLowerCase().split(":")[0]!.replace(/[. ]+$/, "");
|
|
558
|
+
return name === ".git" || name === "git~1";
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** The rule restore applies to a symlink's target: present, no backslash, not absolute, not climbing out of the workspace, not into `.git`. */
|
|
562
|
+
function assertSafeSymlinkTarget(link: { path: string; target: string }): void {
|
|
563
|
+
if (typeof link.target !== "string" || link.target === "") throw new BundleError(`Symlink ${link.path} has no target`);
|
|
564
|
+
if (link.target.includes("\\")) throw new BundleError(`Symlink ${link.path} target contains a backslash: ${link.target}`);
|
|
565
|
+
if (isAbsolute(link.target) || link.target.startsWith("/") || /^[A-Za-z]:/.test(link.target)) {
|
|
566
|
+
throw new BundleError(`Symlink ${link.path} has an absolute target: ${link.target}`);
|
|
567
|
+
}
|
|
568
|
+
const resolved = posix.normalize(posix.join(posix.dirname(pathSegments(link.path).join("/")), link.target));
|
|
569
|
+
if (resolved === ".." || resolved.startsWith("../")) throw new BundleError(`Symlink ${link.path} points outside the workspace: ${link.target}`);
|
|
570
|
+
if (hasGitSegment(resolved) || hasGitSegment(link.target)) throw new BundleError(`Symlink ${link.path} points into .git: ${link.target}`);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Refuse, before anything is written, a bundle that could plant or redirect writes into `.git`
|
|
575
|
+
* (a hook, `core.fsmonitor`, ...) or outside the workspace: any `.git` path segment (case-insensitive)
|
|
576
|
+
* in files, worktree entries or symlinks; a backslash in any path or symlink target (a filename character on
|
|
577
|
+
* POSIX that other tools read as a separator); symlinks that are absolute, climb out of the workspace, or
|
|
578
|
+
* point into `.git`; and members whose path runs through another bundled symlink.
|
|
579
|
+
*/
|
|
580
|
+
export function assertSafeWorkspaceEntries(manifest: BundleManifest): void {
|
|
581
|
+
const workspacePath = (path: string, what: string): void => {
|
|
582
|
+
if (path.includes("\\")) throw new BundleError(`${what} contains a backslash: ${path}`);
|
|
583
|
+
if (isAbsolute(path) || path.startsWith("/") || /^[A-Za-z]:/.test(path) || pathSegments(path).includes("..")) {
|
|
584
|
+
throw new BundleError(`${what} escapes the workspace: ${path}`);
|
|
585
|
+
}
|
|
586
|
+
if (hasGitSegment(path)) throw new BundleError(`${what} writes into .git: ${path}`);
|
|
587
|
+
};
|
|
588
|
+
for (const file of manifest.files) {
|
|
589
|
+
if (file.role === "untracked") workspacePath(file.path.slice("untracked/".length), "Untracked path");
|
|
590
|
+
}
|
|
591
|
+
for (const entry of manifest.worktree) workspacePath(entry.path, "Worktree path");
|
|
592
|
+
const linkPaths = new Set<string>();
|
|
593
|
+
for (const link of manifest.symlinks) {
|
|
594
|
+
workspacePath(link.path, "Symlink path");
|
|
595
|
+
assertSafeSymlinkTarget(link);
|
|
596
|
+
linkPaths.add(pathSegments(link.path).join("/"));
|
|
597
|
+
}
|
|
598
|
+
const members = [
|
|
599
|
+
...manifest.files.filter((f) => f.role === "untracked").map((f) => f.path.slice("untracked/".length)),
|
|
600
|
+
...manifest.symlinks.map((l) => l.path),
|
|
601
|
+
];
|
|
602
|
+
for (const member of members) {
|
|
603
|
+
const parts = pathSegments(member);
|
|
604
|
+
for (let i = 1; i < parts.length; i++) {
|
|
605
|
+
if (linkPaths.has(parts.slice(0, i).join("/"))) throw new BundleError(`Bundle path ${member} runs through symlink ${parts.slice(0, i).join("/")}`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Resolve `relative` (a path under `root`) segment by segment with lstat/readlink, following links the way the
|
|
612
|
+
* kernel does ('..' applies to the already-resolved prefix). Returns the segments of the final location relative
|
|
613
|
+
* to `root`, or null when it leaves `root` or a link target holds a backslash. A missing segment ends the walk:
|
|
614
|
+
* the rest is taken literally.
|
|
615
|
+
*/
|
|
616
|
+
function resolveInside(root: string, relative: string): string[] | null {
|
|
617
|
+
const resolved: string[] = [];
|
|
618
|
+
const pending = pathSegments(relative).reverse();
|
|
619
|
+
for (let hops = 0; pending.length > 0; ) {
|
|
620
|
+
const part = pending.pop()!;
|
|
621
|
+
if (part === ".") continue;
|
|
622
|
+
if (part === "..") {
|
|
623
|
+
if (resolved.length === 0) return null;
|
|
624
|
+
resolved.pop();
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
let target: string | undefined;
|
|
628
|
+
try {
|
|
629
|
+
const full = join(root, ...resolved, part);
|
|
630
|
+
if (lstatSync(full).isSymbolicLink()) target = readlinkSync(full);
|
|
631
|
+
} catch {
|
|
632
|
+
// missing: nothing further to follow
|
|
633
|
+
}
|
|
634
|
+
if (target === undefined) {
|
|
635
|
+
resolved.push(part);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
if (++hops > 40) return null;
|
|
639
|
+
if (target.includes("\\") || isAbsolute(target) || target.startsWith("/") || /^[A-Za-z]:/.test(target)) return null;
|
|
640
|
+
pending.push(...pathSegments(target).reverse());
|
|
641
|
+
}
|
|
642
|
+
return resolved;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* After the whole restore (checkout, patch, untracked files, symlinks) every symlink in the work tree must
|
|
647
|
+
* resolve, through any other links, to a place inside the workspace and outside `.git`.
|
|
648
|
+
*/
|
|
649
|
+
function assertSymlinksContained(dest: string, prefix = ""): void {
|
|
650
|
+
for (const entry of readdirSync(join(dest, prefix), { withFileTypes: true })) {
|
|
651
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
652
|
+
if (entry.isDirectory()) {
|
|
653
|
+
if (!prefix && entry.name.toLowerCase() === ".git") continue;
|
|
654
|
+
assertSymlinksContained(dest, relative);
|
|
655
|
+
} else if (entry.isSymbolicLink()) {
|
|
656
|
+
const final = resolveInside(dest, relative);
|
|
657
|
+
if (!final) throw new BundleError(`Symlink ${relative} points outside the workspace`);
|
|
658
|
+
if (final[0]?.toLowerCase() === ".git") throw new BundleError(`Symlink ${relative} points into .git`);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** Refuse to write `relative` under `dest` when a parent directory already is a symlink (e.g. a tracked link into .git). */
|
|
664
|
+
function assertNoSymlinkParent(dest: string, relative: string): void {
|
|
665
|
+
const parts = pathSegments(relative);
|
|
666
|
+
let current = dest;
|
|
667
|
+
for (const part of parts) {
|
|
668
|
+
current = join(current, part);
|
|
669
|
+
let info;
|
|
670
|
+
try {
|
|
671
|
+
info = lstatSync(current);
|
|
672
|
+
} catch {
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (info.isSymbolicLink()) throw new BundleError(`Bundle path ${relative} runs through symlink ${part}`);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function walkFiles(root: string, prefix = ""): string[] {
|
|
680
|
+
const out: string[] = [];
|
|
681
|
+
for (const entry of readdirSync(join(root, prefix), { withFileTypes: true })) {
|
|
682
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
683
|
+
if (entry.isDirectory()) out.push(...walkFiles(root, relative));
|
|
684
|
+
else out.push(relative);
|
|
685
|
+
}
|
|
686
|
+
return out;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
export interface MaterializeResult {
|
|
690
|
+
cwd: string;
|
|
691
|
+
files: number;
|
|
692
|
+
bytes: number;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Rebuild the workspace in `destDir` (absent or empty) from a verified bundle:
|
|
697
|
+
* history, then dirty tracked changes, then untracked files. Fails unless the
|
|
698
|
+
* result matches the manifest's worktree digest; on failure `destDir` is removed.
|
|
699
|
+
*/
|
|
700
|
+
export function materializeWorkspace(extracted: ExtractedBundle, destDir: string): MaterializeResult {
|
|
701
|
+
const { manifest, dir } = extracted;
|
|
702
|
+
assertWorkspaceIncluded(manifest);
|
|
703
|
+
if (manifest.workspaceIncluded === false) throw new BundleError("Cannot materialize a session-only bundle as a workspace");
|
|
704
|
+
const dest = resolve(destDir);
|
|
705
|
+
assertSafeWorkspaceEntries(manifest);
|
|
706
|
+
if (existsSync(dest) && readdirSync(dest).length > 0) throw new BundleError(`Destination ${dest} already exists and is not empty`);
|
|
707
|
+
const created = !existsSync(dest);
|
|
708
|
+
mkdirSync(dest, { recursive: true });
|
|
709
|
+
try {
|
|
710
|
+
const { repo } = manifest;
|
|
711
|
+
git(dest, ["init", "-q", ...(repo.branch ? ["-b", repo.branch] : [])]);
|
|
712
|
+
const bundlePath = join(dir, "git.bundle");
|
|
713
|
+
git(dest, ["fetch", "-q", "--update-head-ok", bundlePath, "+refs/heads/*:refs/heads/*", "+refs/remotes/*:refs/remotes/*"]);
|
|
714
|
+
if (repo.branch) git(dest, ["checkout", "-q", "-f", repo.branch]);
|
|
715
|
+
else git(dest, ["checkout", "-q", "-f", "--detach", repo.head]);
|
|
716
|
+
const head = gitText(dest, ["rev-parse", "HEAD"]);
|
|
717
|
+
if (head !== repo.head) throw new BundleError(`Restored HEAD ${head} is not the bundled ${repo.head}`);
|
|
718
|
+
if (repo.remote) git(dest, ["remote", "add", "origin", repo.remote], { allowFailure: true });
|
|
719
|
+
|
|
720
|
+
const patch = join(dir, "tracked.patch");
|
|
721
|
+
if (existsSync(patch)) git(dest, ["apply", "--binary", "--whitespace=nowarn", patch]);
|
|
722
|
+
|
|
723
|
+
for (const file of manifest.files.filter((f) => f.role === "untracked")) {
|
|
724
|
+
const relative = file.path.slice("untracked/".length);
|
|
725
|
+
const target = join(dest, relative);
|
|
726
|
+
if (!resolve(target).startsWith(dest + sep)) throw new BundleError(`Untracked path escapes the workspace: ${relative}`);
|
|
727
|
+
assertNoSymlinkParent(dest, relative);
|
|
728
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
729
|
+
copyFileSync(join(dir, file.path), target);
|
|
730
|
+
chmodSync(target, statSync(join(dir, file.path)).mode & 0o777);
|
|
731
|
+
}
|
|
732
|
+
for (const link of manifest.symlinks) {
|
|
733
|
+
const target = join(dest, link.path);
|
|
734
|
+
if (!resolve(target).startsWith(dest + sep)) throw new BundleError(`Symlink path escapes the workspace: ${link.path}`);
|
|
735
|
+
assertNoSymlinkParent(dest, link.path);
|
|
736
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
737
|
+
symlinkSync(link.target, target);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
assertSymlinksContained(dest);
|
|
741
|
+
const restored = digestWorktree(dest);
|
|
742
|
+
const mismatches = diffDigests(manifest.worktree, restored);
|
|
743
|
+
if (mismatches.length > 0) {
|
|
744
|
+
throw new BundleError(`Restored workspace differs from the bundle in ${mismatches.length} file(s): ${mismatches.slice(0, 5).join(", ")}`);
|
|
745
|
+
}
|
|
746
|
+
return { cwd: dest, files: restored.length, bytes: manifest.totals.worktreeBytes };
|
|
747
|
+
} catch (error) {
|
|
748
|
+
if (created) rmSync(dest, { recursive: true, force: true });
|
|
749
|
+
else for (const name of readdirSync(dest)) rmSync(join(dest, name), { recursive: true, force: true });
|
|
750
|
+
throw error;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export function diffDigests(expected: WorktreeEntry[], actual: WorktreeEntry[]): string[] {
|
|
755
|
+
const have = new Map(actual.map((entry) => [entry.path, entry]));
|
|
756
|
+
const diff: string[] = [];
|
|
757
|
+
for (const entry of expected) {
|
|
758
|
+
const found = have.get(entry.path);
|
|
759
|
+
if (!found || found.sha256 !== entry.sha256 || found.mode !== entry.mode) diff.push(entry.path);
|
|
760
|
+
have.delete(entry.path);
|
|
761
|
+
}
|
|
762
|
+
diff.push(...have.keys());
|
|
763
|
+
return diff;
|
|
764
|
+
}
|