@ipul-labs/forge 1.16.5 → 1.16.7

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/bin/cli/repl.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import readline from "node:readline";
2
+ import { execSync } from "node:child_process";
2
3
  import path from "node:path";
3
- import { projectRoot, readPkg, resolvePrimaryRepo } from "./utils.js";
4
+ import { projectRoot, readPkg, resolvePrimaryRepo, relativeAge } from "./utils.js";
5
+ import { getHead, readState, listSessions } from "./sessionStore.js";
4
6
 
5
7
  const COMMANDS = [
6
8
  "ship", "init", "start", "repos", "issues", "issue", "create-issue",
7
9
  "analyze", "show", "refine", "validate", "apply", "watch",
8
10
  "ci-fix", "merge", "resolution-check", "close",
9
- "session", "doctor", "update", "use", "version", "help",
10
- "exit", "quit", "clear",
11
+ "session", "doctor", "update", "use", "status", "open", "log",
12
+ "version", "help", "exit", "quit", "clear",
11
13
  ];
12
14
 
13
15
  class ExitInterrupt extends Error {
@@ -154,6 +156,73 @@ export async function startRepl(dispatch) {
154
156
 
155
157
  const argv = parseInput(trimmed);
156
158
 
159
+ if (argv[0] === "status") {
160
+ process.stdout.write("\n");
161
+ const head = await getHead();
162
+ if (!head) {
163
+ process.stdout.write(`${DIM}No active session. Run: analyze <iid>${RESET}\n`);
164
+ } else {
165
+ const state = await readState(head.repo, head.iid);
166
+ if (!state) {
167
+ process.stdout.write(`${DIM}Session ${head.repo}#${head.iid} — no state${RESET}\n`);
168
+ } else {
169
+ process.stdout.write(`${YELLOW}${state.repo || head.repo}${RESET} ${BOLD}#${state.iid || head.iid}${RESET}\n`);
170
+ process.stdout.write(`${DIM}phase${RESET} ${state.phase || "unknown"}\n`);
171
+ if (state.branch) process.stdout.write(`${DIM}branch${RESET} ${state.branch}\n`);
172
+ if (state.mrUrl) process.stdout.write(`${DIM}mr${RESET} ${state.mrUrl}\n`);
173
+ if (state.lastPipelineStatus) process.stdout.write(`${DIM}ci${RESET} ${state.lastPipelineStatus}\n`);
174
+ if (state.updatedAt) process.stdout.write(`${DIM}updated${RESET} ${relativeAge(state.updatedAt)} ago\n`);
175
+ }
176
+ }
177
+ process.stdout.write("\n");
178
+ showPrompt();
179
+ continue;
180
+ }
181
+
182
+ if (argv[0] === "open") {
183
+ const head = await getHead();
184
+ if (!head) {
185
+ process.stdout.write(`${DIM}No active session.${RESET}\n`);
186
+ } else {
187
+ const state = await readState(head.repo, head.iid);
188
+ const url = argv[1] === "mr" && state?.mrUrl
189
+ ? state.mrUrl
190
+ : state?.issueUrl || state?.mrUrl;
191
+ if (url) {
192
+ try { execSync(`open "${url}"`); } catch {}
193
+ process.stdout.write(`${DIM}Opened ${url}${RESET}\n`);
194
+ } else {
195
+ process.stdout.write(`${DIM}No URL found. Run: analyze <iid>${RESET}\n`);
196
+ }
197
+ }
198
+ showPrompt();
199
+ continue;
200
+ }
201
+
202
+ if (argv[0] === "log") {
203
+ const sessions = await listSessions();
204
+ if (sessions.length === 0) {
205
+ process.stdout.write(`\n${DIM}No sessions.${RESET}\n\n`);
206
+ } else {
207
+ const head = await getHead();
208
+ const limit = Math.min(sessions.length, 10);
209
+ process.stdout.write("\n");
210
+ for (let i = 0; i < limit; i++) {
211
+ const s = sessions[i];
212
+ const isHead = head && s.repo === head.repo && s.iid === head.iid;
213
+ const marker = isHead ? `${GREEN}*${RESET} ` : " ";
214
+ const age = relativeAge(s.updatedAt);
215
+ process.stdout.write(`${marker}${YELLOW}#${s.iid}${RESET} ${s.phase || "?"} ${DIM}${s.repo} ${age}${RESET}\n`);
216
+ }
217
+ if (sessions.length > limit) {
218
+ process.stdout.write(`${DIM} ...${sessions.length - limit} more${RESET}\n`);
219
+ }
220
+ process.stdout.write("\n");
221
+ }
222
+ showPrompt();
223
+ continue;
224
+ }
225
+
157
226
  if (argv[0] === "use") {
158
227
  process.stdout.write("\n");
159
228
  if (!argv[1]) {
@@ -48,17 +48,14 @@ export function sessionDir(repo, iid) {
48
48
  }
49
49
 
50
50
  async function ensureDir(dir) {
51
- await fs.mkdir(dir, { recursive: true });
51
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
52
52
  }
53
53
 
54
54
  export async function writeAnalysis(repo, iid, analysis) {
55
55
  const dir = sessionDir(repo, iid);
56
56
  await ensureDir(dir);
57
- await fs.writeFile(
58
- path.join(dir, "analysis.json"),
59
- JSON.stringify(analysis, null, 2),
60
- "utf8",
61
- );
57
+ const file = path.join(dir, "analysis.json");
58
+ await fs.writeFile(file, JSON.stringify(analysis, null, 2), { encoding: "utf8", mode: 0o600 });
62
59
  }
63
60
 
64
61
  export async function readAnalysis(repo, iid) {
@@ -84,7 +81,7 @@ export async function updateState(repo, iid, partial) {
84
81
  createdAt: now,
85
82
  };
86
83
  const next = { ...prev, ...partial, updatedAt: now };
87
- await fs.writeFile(file, JSON.stringify(next, null, 2), "utf8");
84
+ await fs.writeFile(file, JSON.stringify(next, null, 2), { encoding: "utf8", mode: 0o600 });
88
85
  return next;
89
86
  }
90
87
 
@@ -58,6 +58,9 @@ Commands
58
58
  resolution-check Verify the merged MR actually closes the issue
59
59
  close [<iid>] Close the issue (confirms by default)
60
60
  use <repo> Switch active repo (interactive mode)
61
+ status Show current session (issue, phase, branch, MR)
62
+ open [mr] Open current issue or MR in browser
63
+ log List recent sessions with phase and age
61
64
  session Inspect cached sessions (list | show | clean)
62
65
  doctor Check prerequisites (node, git, claude CLI, token, config)
63
66
  update Pull latest changes + reinstall dependencies
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ipul-labs/forge",
3
- "version": "1.16.5",
3
+ "version": "1.16.7",
4
4
  "description": "AI-powered code change & deploy control panel — connects Claude, GitLab, and Kubernetes",
5
5
  "readmeFilename": "README.md",
6
6
  "type": "module",
7
7
  "main": "server/forge/routes.js",
8
8
  "bin": {
9
- "forge": "./bin/forge-agent.js"
9
+ "forge": "bin/forge-agent.js"
10
10
  },
11
11
  "exports": {
12
12
  ".": "./server/forge/routes.js",
@@ -78,7 +78,7 @@
78
78
  },
79
79
  "repository": {
80
80
  "type": "git",
81
- "url": "https://gitlab.com/ipul-labs/forge.git"
81
+ "url": "git+https://gitlab.com/ipul-labs/forge.git"
82
82
  },
83
83
  "license": "MIT",
84
84
  "readme": "# Forge by iPuL\n\nAI-powered code change & deploy control panel. Connect an issue tracker, let Claude propose a fix, review the diff, approve — and Forge creates the branch, commits the changes, opens the MR/PR, and monitors the CI pipeline.\n\nBuilt on: Claude Code CLI · GitLab / GitHub / Azure DevOps · Kubernetes\n\n---\n\n## Why Forge\n\n**The CI refinement loop is the thing.** Every other AI coding tool hands off after the PR is open. Forge keeps going: when your pipeline fails, it grabs the last 150 lines of the failed job log, feeds them back to Claude with the original fix context, generates a targeted patch, and commits it to the branch — automatically. No human has to read the stack trace, translate it into a prompt, and paste it somewhere. The loop closes itself.\n\nEverything else fills in the gaps that matter for real teams:\n\n- **No per-token cost** — Claude runs via the `claude` CLI using your existing Claude subscription, not API credits. Heavy use doesn't trigger a bill.\n- **Multi-provider** — GitLab, GitHub, and Azure DevOps are all first-class. Switch providers with a single env var; all normalized data shapes stay the same.\n- **Self-hosted** — your code never leaves your infrastructure. The backend runs wherever you deploy it; AI calls go to Anthropic (or a local gateway via OpenClaw).\n- **Two-pass analysis keeps context focused** — Claude first identifies the 6 most relevant files, then reads only those when proposing the fix. This produces sharper diffs than dumping the whole repo into one prompt.\n\n---\n\n## How it works\n\n1. **Connect** — enter your Forge token to authenticate\n2. **Pick an issue** — Forge loads open issues from your project\n3. **Analyze** — Claude reads the repo file tree, identifies relevant files, and proposes a targeted fix\n4. **Review** — inspect the diff file-by-file; refine with natural-language feedback if needed\n5. **Apply** — Forge creates a branch, commits all changes, and opens a merge/pull request\n6. **Monitor** — watch the CI pipeline run; if it fails, click \"Fix with AI\" to iterate\n\n---\n\n## Getting started\n\n### Prerequisites\n\n- Node.js 20+\n- `claude` CLI installed and authenticated (`claude auth login`)\n- Credentials for your SCM provider (see [Configuration](#configuration))\n\n### Install\n\n```bash\ngit clone https://gitlab.com/ipul-labs/forge.git\ncd forge\nnpm install\n```\n\n### Configure\n\n```bash\n# Interactive setup — writes .env and ~/.forge/config.json\nnpx forge init\n```\n\nOr copy the example env and fill in the values manually:\n\n```bash\ncp .env.example .env\n# fill in FORGE_TOKEN plus your provider credentials\n```\n\n### Launch the UI\n\n```bash\nnpm run dev\n# opens http://localhost:5000 (frontend) with API on :5001\n```\n\nFor production:\n\n```bash\nnpm run build:app # builds Vite SPA to dist/\nnpm start # NODE_ENV=production node server.js\n```\n\n### CLI usage\n\nThe `forge` CLI drives the same orchestrator from the terminal. Install globally or use `npx`:\n\n```bash\n# Global install (adds `forge` to PATH)\nnpm install -g @ipul-labs/forge\n\n# Or run via npx from the repo\nnpx forge <command>\n```\n\n#### Interactive mode\n\nRun `forge` with no arguments to enter an interactive terminal session:\n\n```bash\nforge\n```\n\n```\n forge v1.15.1\n\n──────────────────────────────────────────────────\n ❯ issues --limit 5\n──────────────────────────────────────────────────\n group/repo | agent:claude | v1.15.1\n```\n\nTab-completes command names. Type `use <repo>` to switch repos. Commands that error stay in the session — only `exit`, `quit`, or Ctrl+D leave.\n\n#### End-to-end: issue to production\n\n```bash\nforge ship 42\n```\n\nRuns: analyze → review → validate → apply → watch CI → merge → watch deploy → close, with a `y/N` gate at every state-changing step.\n\n#### Step-by-step commands\n\n```bash\nforge issues # List open issues (--label X, --mine, --limit N)\nforge issue 42 # Show full description\nforge create-issue --title \"fix: broken widget\" # Create a new issue\nforge analyze 42 # Run two-pass analysis, cache result\nforge show # Re-render cached analysis\nforge refine --feedback \"...\" # Iterate with feedback\nforge validate # Run lint/typecheck/test against proposed changes\nforge apply # Push branch + open MR\nforge watch # Poll the MR pipeline\nforge ci-fix # Re-analyze with failed-pipeline logs\nforge merge # Merge the MR\nforge resolution-check # Verify merged MR closes the issue\nforge close # Close the issue\nforge use group/other-repo # Switch active repo\nforge update # Pull latest + reinstall dependencies\n```\n\n#### Options\n\n```\n-p, --port <n> Port for start\n--repo <group/repo> Primary repo\n--secondary <repo> Additional repo (repeatable)\n--all-repos Include every configured repo\n--model <id> Claude model override\n--agent <name> Agent backend: claude | openclaw\n--prompt <text> Extra user prompt\n--json JSON output\n--quiet Suppress progress\n--yes Skip confirmation gates\n--validate Run validate before apply\n```\n\n#### Diagnostics\n\n```bash\nforge doctor # Check prerequisites (node, claude CLI, env vars)\nforge session list # List cached sessions\nforge session clean # Remove stale session data\n```\n\nSee [`docs/cli.md`](./docs/cli.md) for the full command reference and [`docs/cli-ship-workflow.md`](./docs/cli-ship-workflow.md) for the workflow design.\n\n---\n\n## Configuration\n\n### Core\n\n| Variable | Required | Description |\n|---|---|---|\n| `FORGE_TOKEN` | Yes | Dashboard password — also auto-fills the UI login form |\n| `FORGE_REPOS` | Yes | Comma-separated repo list; first entry is the primary project |\n| `SCM_PROVIDER` | — | `gitlab` (default) · `github` · `azuredevops` |\n| `ANTHROPIC_API_KEY` | — | Enables live model list from Anthropic; falls back to hardcoded list |\n| `FORGE_MODEL` | — | Override default model (default: `claude-sonnet-4-6`) |\n| `K8S_CLUSTER_TOKEN` | — | K8s service account token for rollout monitoring |\n| `K8S_CLUSTER_SERVER` | — | K8s API server URL |\n| `PORT` | — | HTTP server port (default: `5001`) |\n| `OPENCLAW_GATEWAY_URL` | — | Enables OpenClaw agent backend; point at your local Gateway |\n| `OPENCLAW_TOKEN` | — | Bearer token for OpenClaw Gateway auth |\n\n### Provider credentials\n\nSCM tokens can be set here **or** in the Forge Settings UI (Settings → Connections). The UI value takes precedence over env vars.\n\n#### GitLab (`SCM_PROVIDER=gitlab`, default)\n\n| Variable | Required | Description |\n|---|---|---|\n| `GITLAB_TOKEN` | Yes | Personal access token with `api` + `write_repository` scopes |\n\n#### GitHub (`SCM_PROVIDER=github`)\n\n| Variable | Required | Description |\n|---|---|---|\n| `GITHUB_TOKEN` | Yes | Personal access token with `repo` + `workflow` scopes |\n| `GITHUB_OWNER` | Yes | Organization or user, e.g. `ipul-labs` |\n| `GITHUB_REPO` | Yes | Repository name, e.g. `web-app` |\n| `GITHUB_BASE_BRANCH` | — | Default target branch (default: `main`) |\n\n#### Azure DevOps (`SCM_PROVIDER=azuredevops`)\n\n| Variable | Required | Description |\n|---|---|---|\n| `AZURE_DEVOPS_TOKEN` | Yes | Personal access token (Full access or Code + Work Items) |\n| `AZURE_DEVOPS_ORG` | Yes | Organization name, e.g. `ipul-labs` |\n| `AZURE_DEVOPS_PROJECT` | Yes | Team project name, e.g. `web-app` |\n| `AZURE_DEVOPS_REPO` | — | Git repo name (defaults to project name) |\n| `AZURE_DEVOPS_BASE_BRANCH` | — | Default target branch (default: `main`) |\n\n### Deprecated (still work as fallbacks)\n\n| Variable | Replaced by |\n|---|---|\n| `FORGE_GITLAB_PROJECT` | First entry in `FORGE_REPOS` |\n| `VITE_FORGE_TOKEN` | Auto-derived from `FORGE_TOKEN` |\n| `FORGE_REFINE_REPO_ACCESS` | Settings UI toggle (Settings → Defaults) |\n\nSee `.env.example` for a full annotated list.\n\n---\n\n## Multi-provider support\n\nForge's SCM layer is a clean provider abstraction — all three providers implement the same `ScmProvider` interface and return identical normalized shapes (`NormalIssue`, `NormalMR`, `NormalPipeline`, etc.). The rest of the codebase never knows which provider is active.\n\n### Switching providers\n\n```bash\n# .env\nSCM_PROVIDER=github\nGITHUB_TOKEN=ghp_...\nGITHUB_OWNER=my-org\nGITHUB_REPO=my-repo\n```\n\n### Per-repo prefix (multi-repo mixed-provider setups)\n\n```bash\nFORGE_REPOS=gitlab:ipul/web-app,github:my-org/mobile\n```\n\n### Provider capabilities\n\n| Feature | GitLab | GitHub | Azure DevOps |\n|---|---|---|---|\n| Issues / Work Items | Yes | Yes | Yes (Work Items) |\n| Multi-file commits | Yes | Yes (Git Data API) | Yes (Pushes API) |\n| Merge / Pull Requests | Yes | Yes | Yes |\n| CI pipelines | Yes (GitLab CI) | Yes (GitHub Actions) | Yes (Azure Pipelines) |\n| Job log traces | Yes | Yes | Yes |\n| Server-side rebase | Yes | — | — |\n\n---\n\n## Production deployment\n\n```bash\nnpm run build:app # builds Vite SPA to dist/\nNODE_ENV=production node server.js\n```\n\nOr with Docker:\n\n```bash\ndocker build -t forge .\ndocker run -p 5001:5001 --env-file .env forge\n```\n\n---\n\n## Architecture\n\n```\nbin/\n forge-agent.js # CLI entry point (forge command)\n cli/\n ship.js # End-to-end orchestrator (Ink UI)\n analyze.js # Two-pass issue analysis\n resolution.js # Post-merge resolution check\n sessionStore.js # ~/.forge/sessions/ persistence\n ...\n\nserver/\n forge/\n routes.js # Express router — all /api/forge/* endpoints\n core/\n ForgeAgent.js # Orchestrates the full pipeline (analyze -> apply -> refine)\n claudeClient.js # Shells out to the claude CLI for structured output\n openclawClient.js # OpenClaw Gateway HTTP client\n agentClient.js # Dispatcher: routes to claudeClient or openclawClient\n k8s.js # Kubernetes client for rollout monitoring\n providers/\n base.js # Abstract ScmProvider — normalized shapes + interface\n gitlab.js # GitLab REST API v4\n github.js # GitHub REST API v3 + Git Data API\n azuredevops.js # Azure DevOps REST API\n index.js # createProvider() factory\n\nsrc/\n views/Forge/\n ForgeDashboard.tsx # Root UI component with tabbed issue/MR views\n api.ts # Token management + fetch helper\n types.ts # Shared TypeScript types\n utils.ts # SSE helper + state utilities\n components/ # Analysis progress, pipeline status, diff viewer\n hooks/\n useForgeDashboard.ts # All state, phase transitions, and API calls\n```\n\n### Two-pass analysis\n\n**Pass 1** — `identifyRelevantFiles`: Claude reads the issue + file tree, returns the max-6 most relevant paths.\n\n**Pass 2** — `proposeFix`: Claude reads the actual file contents and proposes a targeted fix as a JSON diff.\n\nBoth passes use `claude --print --output-format json` so cost and service tier are tracked automatically.\n\n### CI refinement\n\nWhen a pipeline fails, Forge fetches the last 150 lines of each failed job's trace log and feeds them to pass 2 with an explicit \"pipeline failed\" framing — not generic reviewer feedback. This improves fix quality for common failures like lint errors and type errors.\n\n### Provider abstraction\n\nAll three SCM providers implement `ScmProvider` from `providers/base.js`. The contract is:\n- **Normalized return types** — all methods return `NormalIssue`, `NormalMR`, `NormalPipeline`, etc., regardless of provider\n- **Instance-scoped** — each provider is instantiated with a repo string; no global state\n- **`supportsRebase`** — providers that don't support server-side rebase return `false`; the UI and API layer check this before showing the rebase button\n\n---\n\n## Programmatic usage\n\nMount the Forge Express router or use the core classes directly:\n\n```js\nimport forgeRouter from \"@ipul-labs/forge\"; // Express router\nimport { ForgeAgent } from \"@ipul-labs/forge/agent\"; // Core pipeline class\nimport { createProvider } from \"@ipul-labs/forge/providers\"; // SCM factory\n```\n\n```js\nconst agent = new ForgeAgent({ project: \"group/repo\" });\nconst result = await agent.analyzeIssue(42, (event) => console.log(event));\nconst { branchName, mr } = await agent.applyFix(result);\n```\n\n---\n\n## License\n\nMIT\n"
@@ -55,9 +55,21 @@ function sanitizeRepo(repo) {
55
55
  }
56
56
 
57
57
  function gitlabCloneUrl(project) {
58
+ return `https://gitlab.com/${project}.git`;
59
+ }
60
+
61
+ function gitEnvWithToken() {
58
62
  const { token } = getConnection("gitlab");
59
63
  if (!token) throw new Error("GitLab token is required to clone the repo locally. Set it in Settings → Connections or via GITLAB_TOKEN env var.");
60
- return `https://oauth2:${token}@gitlab.com/${project}.git`;
64
+ return {
65
+ GIT_ASKPASS: "echo",
66
+ GIT_TERMINAL_PROMPT: "0",
67
+ GIT_CONFIG_COUNT: "2",
68
+ GIT_CONFIG_KEY_0: "credential.helper",
69
+ GIT_CONFIG_VALUE_0: "",
70
+ GIT_CONFIG_KEY_1: "http.extraHeader",
71
+ GIT_CONFIG_VALUE_1: `Authorization: Bearer ${token}`,
72
+ };
61
73
  }
62
74
 
63
75
  function resolveCloneUrl(repoInput) {
@@ -90,16 +102,18 @@ export async function ensureWorkingTree(repo, branchName, onLog) {
90
102
  const hasRepo = await exists(path.join(dir, ".git"));
91
103
  const log = (m) => onLog?.(m);
92
104
 
105
+ const gitEnv = gitEnvWithToken();
106
+ const envOpts = { env: { ...process.env, ...gitEnv } };
93
107
  if (!hasRepo) {
94
108
  log(`Cloning ${repo} → ${dir}`);
95
109
  await fs.mkdir(dir, { recursive: true });
96
- const clone = await runGit(["clone", "--depth=1", resolveCloneUrl(repo), dir], {}, onLog);
110
+ const clone = await runGit(["clone", "--depth=1", resolveCloneUrl(repo), dir], envOpts, onLog);
97
111
  if (clone.code !== 0) throw new Error(`git clone failed (code ${clone.code})`);
98
112
  } else {
99
113
  log(`Reusing clone at ${dir}`);
100
114
  }
101
115
 
102
- const fetch = await runGit(["fetch", "--depth=1", "origin", "main"], { cwd: dir }, onLog);
116
+ const fetch = await runGit(["fetch", "--depth=1", "origin", "main"], { cwd: dir, ...envOpts }, onLog);
103
117
  if (fetch.code !== 0) throw new Error(`git fetch failed (code ${fetch.code})`);
104
118
 
105
119
  const reset = await runGit(["reset", "--hard", "origin/main"], { cwd: dir }, onLog);
@@ -121,9 +135,10 @@ export async function ensureWorkingTree(repo, branchName, onLog) {
121
135
  * @param {(msg: string) => void} [onLog]
122
136
  */
123
137
  export async function overlayChanges(dir, changes, onLog) {
138
+ const realBase = await fs.realpath(dir);
124
139
  for (const c of changes) {
125
- const full = path.join(dir, c.file);
126
- if (!full.startsWith(dir + path.sep) && full !== dir) {
140
+ const full = path.resolve(dir, c.file);
141
+ if (!full.startsWith(realBase + path.sep) && full !== realBase) {
127
142
  throw new Error(`Refusing to write outside clone dir: ${c.file}`);
128
143
  }
129
144
  if (c.action === "delete") {
@@ -26,11 +26,23 @@ function sanitizeRepo(repo) {
26
26
  }
27
27
 
28
28
  function gitlabCloneUrl(project) {
29
+ return `https://gitlab.com/${project}.git`;
30
+ }
31
+
32
+ function gitEnvWithToken() {
29
33
  const { token } = getConnection("gitlab");
30
34
  if (!token) {
31
35
  throw new Error("GitLab token is required to clone the repo for validation. Set it in Settings → Connections or via GITLAB_TOKEN env var.");
32
36
  }
33
- return `https://oauth2:${token}@gitlab.com/${project}.git`;
37
+ return {
38
+ GIT_ASKPASS: "echo",
39
+ GIT_TERMINAL_PROMPT: "0",
40
+ GIT_CONFIG_COUNT: "2",
41
+ GIT_CONFIG_KEY_0: "credential.helper",
42
+ GIT_CONFIG_VALUE_0: "",
43
+ GIT_CONFIG_KEY_1: "http.extraHeader",
44
+ GIT_CONFIG_VALUE_1: `Authorization: Bearer ${token}`,
45
+ };
34
46
  }
35
47
 
36
48
  function resolveCloneUrl(repoInput) {
@@ -54,11 +66,12 @@ export async function ensureClone(repo, branchName, emit) {
54
66
  emit({ type: "progress", step: "clone", status: "running" });
55
67
  emit({ type: "log", step: "clone", message: hasRepo ? `Reusing clone at ${dir}` : `Cloning ${repo} → ${dir}` });
56
68
 
69
+ const gitEnv = gitEnvWithToken();
57
70
  if (!hasRepo) {
58
71
  await fs.mkdir(dir, { recursive: true });
59
72
  const clone = await runCmd(
60
73
  "git", ["clone", "--depth=1", resolveCloneUrl(repo), dir],
61
- {},
74
+ { env: { ...process.env, ...gitEnv } },
62
75
  (l) => emit({ type: "log", step: "clone", message: l }),
63
76
  );
64
77
  if (clone.code !== 0) throw new Error(`git clone failed (code ${clone.code})`);
@@ -66,7 +79,7 @@ export async function ensureClone(repo, branchName, emit) {
66
79
 
67
80
  const fetch = await runCmd(
68
81
  "git", ["fetch", "--depth=1", "origin", "main"],
69
- { cwd: dir },
82
+ { cwd: dir, env: { ...process.env, ...gitEnv } },
70
83
  (l) => emit({ type: "log", step: "clone", message: l }),
71
84
  );
72
85
  if (fetch.code !== 0) throw new Error(`git fetch failed (code ${fetch.code})`);
@@ -8,10 +8,10 @@ import path from "node:path";
8
8
 
9
9
  export async function overlayChanges(dir, changes, emit) {
10
10
  emit({ type: "progress", step: "overlay", status: "running" });
11
+ const realBase = await fs.realpath(dir);
11
12
  for (const c of changes) {
12
- const full = path.join(dir, c.file);
13
- // Defensive: refuse to escape the clone dir.
14
- if (!full.startsWith(dir + path.sep) && full !== dir) {
13
+ const full = path.resolve(dir, c.file);
14
+ if (!full.startsWith(realBase + path.sep) && full !== realBase) {
15
15
  throw new Error(`Refusing to write outside clone dir: ${c.file}`);
16
16
  }
17
17
  if (c.action === "delete") {
@@ -21,6 +21,7 @@ import { Router } from "express";
21
21
  import * as configStore from "./core/configStore.js";
22
22
  import { listDeployments } from "./core/k8s.js";
23
23
  import { ForgeAgent } from "./core/ForgeAgent.js";
24
+ import crypto from "node:crypto";
24
25
  import { probeQuota } from "./core/quotaClient.js";
25
26
  import { validate as runValidation } from "./core/validator.js";
26
27
  import { createProvider } from "./core/providers/index.js";
@@ -45,7 +46,9 @@ function requireAuth(req, res, next) {
45
46
  return res.status(401).json({ error: "Missing Authorization header." });
46
47
  }
47
48
 
48
- if (auth.slice(7) !== token) {
49
+ const provided = Buffer.from(auth.slice(7));
50
+ const expected = Buffer.from(token);
51
+ if (provided.length !== expected.length || !crypto.timingSafeEqual(provided, expected)) {
49
52
  return res.status(403).json({ error: "Invalid token." });
50
53
  }
51
54
 
@@ -54,12 +57,20 @@ function requireAuth(req, res, next) {
54
57
 
55
58
  // ─── Error handler ────────────────────────────────────────────────────────────
56
59
 
60
+ function redactSecrets(text) {
61
+ return text
62
+ .replace(/(?:token|key|secret|password|bearer)[=:\s]+\S+/gi, (m) => m.slice(0, m.indexOf(m.match(/[=:\s]/)[0]) + 1) + "***")
63
+ .replace(/oauth2:[^@]+@/gi, "oauth2:***@")
64
+ .replace(/ghp_\w+/g, "ghp_***")
65
+ .replace(/glpat-\w+/g, "glpat-***");
66
+ }
67
+
57
68
  function handleError(res, error, operation) {
58
69
  const msg = error?.message ?? "Unknown error";
59
- console.error(`[forge] ${operation} failed:`, msg);
70
+ console.error(`[forge] ${operation} failed:`, redactSecrets(msg));
60
71
  const upstream = /^(?:GitLab|GitHub) (\d{3}) on /.exec(msg);
61
72
  const status = error?.status ?? (upstream ? Number(upstream[1]) : 500);
62
- res.status(status).json({ error: msg, operation });
73
+ res.status(status).json({ error: redactSecrets(msg), operation });
63
74
  }
64
75
 
65
76
  // ─── Repo helpers ─────────────────────────────────────────────────────────────