git-tm 1.1.2 → 2.0.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/src/server.js CHANGED
@@ -3,11 +3,12 @@
3
3
  // header so other websites cannot read the repository via DNS rebinding.
4
4
 
5
5
  import http from "node:http";
6
- import { createHash } from "node:crypto";
6
+ import { createHash, randomBytes } from "node:crypto";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { GitError } from "./git.js";
11
+ import { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
11
12
 
12
13
  const PUBLIC_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "public");
13
14
 
@@ -32,6 +33,8 @@ const CSP = [
32
33
  ].join("; ");
33
34
 
34
35
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
36
+ const MAX_BODY = 64 * 1024;
37
+ const PLAN_TTL = 10 * 60 * 1000;
35
38
 
36
39
  function md5(s) {
37
40
  return createHash("md5").update(s).digest("hex");
@@ -59,14 +62,22 @@ function attachAvatars(enabled, ...lists) {
59
62
  return map;
60
63
  }
61
64
 
62
- export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {}) {
65
+ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit = false, onEdit, onLog } = {}) {
63
66
  const staticCache = new Map();
64
67
  const checkHost = LOOPBACK.has(host);
68
+ // Changing history from another device is a different risk from reading it: edit mode is local only.
69
+ if (edit && !checkHost) throw new Error("Edit mode only works on a loopback host (127.0.0.1, localhost or ::1)");
70
+
71
+ // Previewed plans, by one-time token, so apply can only move a branch to a tip git-tm computed.
72
+ const plans = new Map();
73
+ const requireEdit = () => {
74
+ if (!edit) throw new GitError("Edit mode is off. Start git-tm with --edit to change history.", 403);
75
+ };
65
76
 
66
77
  const bool = (v) => v === "1" || v === "true";
67
78
 
68
79
  const routes = {
69
- "GET /api/repo": async () => ({ ...(await repo.info()), avatars }),
80
+ "GET /api/repo": async () => ({ ...(await repo.info()), avatars, edit }),
70
81
  "GET /api/state": async () => ({ fingerprint: await repo.fingerprint() }),
71
82
  "GET /api/history": async (q) => {
72
83
  const res = await repo.log({
@@ -103,6 +114,14 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
103
114
  const res = await repo.blame(required(q, "rev"), required(q, "path"));
104
115
  return { ...res, avatars: attachAvatars(avatars, Object.values(res.commits)) };
105
116
  },
117
+ "GET /api/reflog": async (q) => {
118
+ const res = await repo.reflog({
119
+ ref: q.get("rev") || "HEAD",
120
+ skip: Number(q.get("skip")) || 0,
121
+ limit: Number(q.get("limit")) || 200,
122
+ });
123
+ return { ...res, avatars: attachAvatars(avatars, res.entries) };
124
+ },
106
125
  "GET /api/insights": async (q) => {
107
126
  const res = await repo.insights(q.get("rev") || undefined);
108
127
  return { ...res, avatars: attachAvatars(avatars, res.contributors) };
@@ -111,6 +130,52 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
111
130
  await repo.fetch();
112
131
  return { ok: true };
113
132
  },
133
+ "GET /api/edit/backups": async () => {
134
+ requireEdit();
135
+ return { backups: await listBackups(repo) };
136
+ },
137
+ "POST /api/edit/preview": async (q, req) => {
138
+ requireEdit();
139
+ const body = await readJson(req);
140
+ const plan = await planEdit(repo, {
141
+ type: body.op,
142
+ commit: body.commit,
143
+ branch: body.branch || undefined,
144
+ message: body.message,
145
+ author: body.author,
146
+ });
147
+ const now = Date.now();
148
+ for (const [k, v] of plans) if (v.expires < now) plans.delete(k);
149
+ if (plans.size > 50) plans.delete(plans.keys().next().value);
150
+ const token = randomBytes(16).toString("hex");
151
+ plans.set(token, { plan, expires: now + PLAN_TTL });
152
+ return { token, plan };
153
+ },
154
+ "POST /api/edit/apply": async (q, req) => {
155
+ requireEdit();
156
+ const body = await readJson(req);
157
+ const entry = typeof body.token === "string" ? plans.get(body.token) : null;
158
+ if (!entry || entry.expires < Date.now()) throw new GitError("This preview has expired. Preview the edit again.", 400);
159
+ // A double click must not run the same edit twice (duplicate backups and log entries).
160
+ if (entry.busy) throw new GitError("This edit is already being applied.", 409);
161
+ entry.busy = true;
162
+ let result;
163
+ try {
164
+ result = await applyEdit(repo, entry.plan, { allowPushed: body.allowPushed === true });
165
+ } finally {
166
+ entry.busy = false; // a failed apply (for example, unconfirmed pushed commits) can be retried
167
+ }
168
+ plans.delete(body.token);
169
+ onEdit?.({ ...result, op: entry.plan.type, summary: entry.plan.summary, count: entry.plan.rewritten.length || entry.plan.added.length });
170
+ return result;
171
+ },
172
+ "POST /api/edit/undo": async (q, req) => {
173
+ requireEdit();
174
+ const body = await readJson(req);
175
+ const result = await undoEdit(repo, body.id, { newBranch: body.newBranch });
176
+ onEdit?.({ ...result, op: body.newBranch ? "restore" : "undo" });
177
+ return result;
178
+ },
114
179
  };
115
180
 
116
181
  async function serveStatic(res, pathname) {
@@ -138,7 +203,19 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
138
203
  res.end(body);
139
204
  }
140
205
 
206
+ // A broken logger must never fail a request, or get the same request logged twice by the error path.
207
+ const logRequest = (event) => {
208
+ if (!onLog || event.path === "/api/state") return;
209
+ try {
210
+ onLog(event);
211
+ } catch (err) {
212
+ console.error(`onLog failed: ${err?.stack || err}`);
213
+ }
214
+ };
215
+
141
216
  return http.createServer(async (req, res) => {
217
+ let apiUrl = null;
218
+ const started = onLog ? performance.now() : 0;
142
219
  try {
143
220
  if (checkHost) {
144
221
  const h = (req.headers.host || "").toLowerCase().replace(/:\d+$/, "");
@@ -149,21 +226,45 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
149
226
  if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "Method not allowed");
150
227
  return await serveStatic(res, url.pathname);
151
228
  }
229
+ apiUrl = url;
152
230
  const route = routes[`${req.method} ${url.pathname}`];
153
231
  if (!route) return json(res, 404, { error: "Unknown endpoint" });
154
232
  // Simple CSRF guard: browsers will not send this custom header cross-origin without a preflight.
155
233
  if (req.method !== "GET" && req.headers["x-git-tm"] !== "1") return json(res, 403, { error: "Forbidden" });
156
- const data = await route(url.searchParams);
234
+ const data = await route(url.searchParams, req);
157
235
  json(res, 200, data);
236
+ logRequest({ method: req.method, path: url.pathname, query: url.searchParams, status: 200, ms: Math.round(performance.now() - started) });
158
237
  } catch (err) {
159
238
  const status = err instanceof GitError ? err.status : 500;
160
239
  if (status >= 500) console.error(`${req.method} ${req.url}: ${err instanceof GitError ? err.message : err.stack}`);
240
+ if (apiUrl) logRequest({ method: req.method, path: apiUrl.pathname, query: apiUrl.searchParams, status, ms: Math.round(performance.now() - started), error: err.message });
161
241
  if (res.headersSent) res.destroy();
162
- else json(res, status, { error: err.message || "Internal error" });
242
+ else json(res, status, { error: err.message || "Internal error", ...(err.conflicts ? { conflicts: err.conflicts } : {}) });
163
243
  }
164
244
  });
165
245
  }
166
246
 
247
+ /** Read a small JSON object body. Requiring application/json also forces a CORS preflight for cross-site requests. */
248
+ async function readJson(req) {
249
+ if (!/^application\/json(;|$)/i.test(req.headers["content-type"] || "")) throw new GitError("Expected a JSON body", 415);
250
+ const chunks = [];
251
+ let size = 0;
252
+ // Keep reading past the limit (discarding) so the client gets a clean 413 instead of a reset connection.
253
+ for await (const chunk of req) {
254
+ size += chunk.length;
255
+ if (size <= MAX_BODY) chunks.push(chunk);
256
+ }
257
+ if (size > MAX_BODY) throw new GitError("Request body too large", 413);
258
+ let data;
259
+ try {
260
+ data = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
261
+ } catch {
262
+ throw new GitError("Invalid JSON body", 400);
263
+ }
264
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new GitError("Expected a JSON object", 400);
265
+ return data;
266
+ }
267
+
167
268
  function required(q, name) {
168
269
  const v = q.get(name);
169
270
  if (!v) throw new GitError(`Missing parameter: ${name}`, 400);
@@ -0,0 +1,69 @@
1
+ import type { Repo } from "./git.js";
2
+
3
+ /** The kinds of edit edit mode supports. */
4
+ export type EditType = "reword" | "author" | "squash" | "drop" | "revert";
5
+
6
+ export interface EditOptions {
7
+ type: EditType;
8
+ /** The commit to edit (any revision git understands). */
9
+ commit: string;
10
+ /** Local branch whose history changes. Default: the current branch. */
11
+ branch?: string;
12
+ /** New message for reword; optional combined message for squash; optional message for revert. */
13
+ message?: string;
14
+ /** New author for the "author" edit. `date` is Unix seconds; the original time zone is kept. */
15
+ author?: { name: string; email: string; date?: number };
16
+ }
17
+
18
+ export interface EditPlan {
19
+ type: EditType;
20
+ branch: string;
21
+ ref: string;
22
+ oldTip: string;
23
+ newTip: string;
24
+ target: string;
25
+ targetSubject: string;
26
+ summary: string;
27
+ /** Old commits and what replaces them (`new` is null for a dropped commit). */
28
+ rewritten: { old: string; new: string | null; subject: string }[];
29
+ /** New commits that rewrite nothing (revert). */
30
+ added: { new: string; subject: string }[];
31
+ /** True when the final tree is unchanged, so the working tree is never touched. */
32
+ treePreserving: boolean;
33
+ /** Remote branches that already have the affected commits. Applying then needs `allowPushed`. */
34
+ pushed: string[];
35
+ /** Other refs that keep pointing at the old commits. */
36
+ otherRefs: { branches: string[]; tags: string[] };
37
+ /** Number of signed commits that lose their signature. */
38
+ signed: number;
39
+ warnings: string[];
40
+ /** Whether the branch is checked out in this worktree. */
41
+ checkedOut: boolean;
42
+ }
43
+
44
+ export interface EditResult {
45
+ id: string;
46
+ branch: string;
47
+ oldTip: string;
48
+ newTip: string;
49
+ }
50
+
51
+ export interface EditBackup extends EditResult {
52
+ op: EditType | "undo";
53
+ summary: string;
54
+ /** Unix seconds. */
55
+ time: number;
56
+ /** Where the branch is now. */
57
+ current: string | null;
58
+ /** True while the branch is still exactly where the edit left it. */
59
+ canUndo: boolean;
60
+ }
61
+
62
+ /** Work out an edit without changing anything. Throws GitError (409 with `conflicts` for conflicting drops and reverts). */
63
+ export function planEdit(repo: Repo, options: EditOptions): Promise<EditPlan>;
64
+ /** Apply a plan: backs up the old tip, then moves the branch only if it hasn't moved since planning. */
65
+ export function applyEdit(repo: Repo, plan: EditPlan, options?: { allowPushed?: boolean }): Promise<EditResult>;
66
+ /** Edits made by git-tm, newest first. */
67
+ export function listBackups(repo: Repo): Promise<EditBackup[]>;
68
+ /** Undo an edit, or with `newBranch` restore the old timeline as a new branch. */
69
+ export function undoEdit(repo: Repo, id: string, options?: { newBranch?: string }): Promise<{ id?: string; branch: string; newTip: string }>;
@@ -16,12 +16,19 @@ export interface GitOptions {
16
16
  maxBytes?: number;
17
17
  /** Kill git after this many milliseconds. Default 60 000. */
18
18
  timeout?: number;
19
+ /** Extra environment variables for this git process. */
20
+ env?: Record<string, string>;
19
21
  }
20
22
 
21
23
  /** Run git in `cwd` with a clean, non-interactive environment and resolve with its stdout. */
22
24
  export function git(cwd: string, args: string[], options: GitOptions & { raw: true }): Promise<Buffer & { truncated: boolean }>;
25
+ /** With `allowExit`, the listed non-zero exit codes (and 0) resolve with stdout and the code instead of throwing. */
26
+ export function git(cwd: string, args: string[], options: GitOptions & { allowExit: number[] }): Promise<{ stdout: string; code: number }>;
23
27
  export function git(cwd: string, args: string[], options?: GitOptions): Promise<string>;
24
28
 
29
+ /** Validate a user-supplied revision so it can never be read as a git option. Returns it unchanged or throws GitError. */
30
+ export function checkRev(rev: string): string;
31
+
25
32
  /** Open the repository containing `dir` (any folder inside it works). Throws GitError if there is none. */
26
33
  export function openRepo(dir: string): Promise<Repo>;
27
34
 
@@ -166,6 +173,40 @@ export interface Blame {
166
173
  commits: Record<string, { author?: string; email?: string; date?: number; subject?: string }>;
167
174
  }
168
175
 
176
+ export interface ReflogOptions {
177
+ /** Ref whose reflog to read. Default: `"HEAD"`. */
178
+ ref?: string;
179
+ skip?: number;
180
+ /** Page size, 1 to 1000. Default 200. */
181
+ limit?: number;
182
+ }
183
+
184
+ export interface ReflogEntry {
185
+ hash: string;
186
+ /** Selector such as `HEAD@{0}`. */
187
+ selector: string;
188
+ /** Numeric reflog index (0 = newest). */
189
+ index: number;
190
+ /** Parsed action kind such as `commit`, `amend`, `checkout`, `reset`, `rebase`, `merge`, `pull`. */
191
+ action: string;
192
+ /** Reflog message (`%gs`). */
193
+ message: string;
194
+ /** When the movement occurred, Unix seconds. */
195
+ date: number;
196
+ author: string;
197
+ email: string;
198
+ subject: string;
199
+ refs: Ref[];
200
+ /** True when the commit is not reachable from any local branch, remote branch, or tag. */
201
+ orphaned: boolean;
202
+ }
203
+
204
+ export interface ReflogPage {
205
+ entries: ReflogEntry[];
206
+ /** True when there are no more entries. */
207
+ done: boolean;
208
+ }
209
+
169
210
  export interface Insights {
170
211
  total: number;
171
212
  first: number | null;
@@ -209,6 +250,8 @@ export interface Repo {
209
250
  tree(rev: string, dir?: string): Promise<{ rev: string; path: string; entries: TreeEntry[] }>;
210
251
  blob(rev: string, file: string): Promise<Blob>;
211
252
  blame(rev: string, file: string): Promise<Blame>;
253
+ /** Recent reflog entries (default HEAD) with orphaned-commit detection. */
254
+ reflog(options?: ReflogOptions): Promise<ReflogPage>;
212
255
  /** Activity for one revision, or for all branches when omitted. */
213
256
  insights(ref?: string): Promise<Insights>;
214
257
  /** `git fetch --all --prune`. */
@@ -1,5 +1,7 @@
1
1
  export * from "./git.js";
2
2
  export { createServer, listen } from "./server.js";
3
3
  export type { ServerOptions } from "./server.js";
4
+ export { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
5
+ export type { EditType, EditOptions, EditPlan, EditResult, EditBackup } from "./edit.js";
4
6
  export { createLayout, layout } from "./graph.js";
5
7
  export type { GraphRow, LayoutState } from "./graph.js";
@@ -6,6 +6,12 @@ export interface ServerOptions {
6
6
  avatars?: boolean;
7
7
  /** The host you will listen on. For loopback hosts, requests for other host names are rejected. Default "127.0.0.1". */
8
8
  host?: string;
9
+ /** Enable edit mode: the /api/edit/* routes that change history. Only allowed with a loopback host. Default false. */
10
+ edit?: boolean;
11
+ /** Called after each applied edit, undo or restore (for logging). */
12
+ onEdit?: (event: { id?: string; branch: string; newTip: string; op: string; summary?: string; count?: number }) => void;
13
+ /** Called after each handled API request (excluding /api/state polling). */
14
+ onLog?: (event: { method: string; path: string; query: URLSearchParams; status: number; ms: number; error?: string }) => void;
9
15
  }
10
16
 
11
17
  /** An HTTP server for the git-tm web interface and its JSON API. Call listen() to start it. */