release-cherry-pick 1.0.0 → 1.0.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.
Files changed (35) hide show
  1. package/.atl/.skill-registry.cache.json +3 -0
  2. package/.atl/skill-registry.md +55 -0
  3. package/.husky/pre-commit +1 -0
  4. package/CLAUDE.md +74 -0
  5. package/README.md +17 -22
  6. package/eslint.config.js +34 -0
  7. package/openspec/changes/archive/.gitkeep +0 -0
  8. package/openspec/changes/node-cli-release-cherry-pick/.openspec.yaml +2 -0
  9. package/openspec/changes/node-cli-release-cherry-pick/design.md +126 -0
  10. package/openspec/changes/node-cli-release-cherry-pick/proposal.md +39 -0
  11. package/openspec/changes/node-cli-release-cherry-pick/specs/branch-selection/spec.md +42 -0
  12. package/openspec/changes/node-cli-release-cherry-pick/specs/cherry-pick-orchestration/spec.md +49 -0
  13. package/openspec/changes/node-cli-release-cherry-pick/specs/cli-core/spec.md +37 -0
  14. package/openspec/changes/node-cli-release-cherry-pick/specs/config-management/spec.md +52 -0
  15. package/openspec/changes/node-cli-release-cherry-pick/specs/documentation-generation/spec.md +38 -0
  16. package/openspec/changes/node-cli-release-cherry-pick/specs/gitlab-integration/spec.md +49 -0
  17. package/openspec/changes/node-cli-release-cherry-pick/specs/release-summary/spec.md +37 -0
  18. package/openspec/changes/node-cli-release-cherry-pick/tasks.md +70 -0
  19. package/openspec/config.yaml +32 -0
  20. package/openspec/specs/.gitkeep +0 -0
  21. package/package.json +8 -24
  22. package/scripts/sandbox/harness.js +130 -0
  23. package/scripts/sandbox/make-sandbox.sh +90 -0
  24. package/scripts/sandbox/run-config.js +26 -0
  25. package/scripts/sandbox/run-release.js +26 -0
  26. package/scripts/sandbox/test-package.js +571 -0
  27. package/skills-lock.json +11 -0
  28. package/src/git/branch-selector.js +2 -2
  29. package/src/git/cherry-pick.js +2 -2
  30. package/src/git/git-auth.js +6 -4
  31. package/src/git/instance.js +17 -0
  32. package/src/git/release-branch.js +2 -2
  33. package/src/git/repo-state.js +2 -2
  34. package/src/gitlab/client.js +2 -2
  35. package/test-e2e.js +56 -0
@@ -0,0 +1,571 @@
1
+ 'use strict';
2
+
3
+ // End-to-end test of the *published* npm artifact (the registry tarball), not the local checkout:
4
+ // Phase 1 SEGURIDAD download the tarball, verify registry integrity, scan its contents for
5
+ // leaked files/secrets, install-time lifecycle scripts and license drift
6
+ // Phase 2 INSTALACIÓN install it for real (lifecycle scripts enabled), exercise the bin and make
7
+ // sure `config --show` never touches the real ~/.release-cherry-pick, audit deps
8
+ // Phase 3 CHERRY-PICK run the release flow against the mutated sandbox repo (conflict,
9
+ // already-applied, duplicate task ID, untagged commit, staging moved on) and
10
+ // assert the git state it leaves behind
11
+ //
12
+ // Usage:
13
+ // node scripts/sandbox/test-package.js [--version 1.0.0] [--sandbox <dir>] [--keep]
14
+ // npm run test:package
15
+
16
+ const { spawnSync } = require('child_process');
17
+ const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const os = require('os');
20
+ const path = require('path');
21
+
22
+ const PKG_NAME = 'release-cherry-pick';
23
+ const REPO_ROOT = path.resolve(__dirname, '..', '..');
24
+ const DEFAULT_SANDBOX = fs.existsSync('/tmp/opencode')
25
+ ? '/tmp/opencode/release-cherry-pick-package-test'
26
+ : path.join(os.tmpdir(), 'release-cherry-pick-package-test');
27
+
28
+ const SECRET_PATTERNS = [
29
+ ['GitLab PAT', /glpat-[A-Za-z0-9_-]{10,}/],
30
+ ['Anthropic API key', /sk-ant-[A-Za-z0-9_-]{10,}/],
31
+ ['GitHub token', /gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}/],
32
+ ['AWS access key', /AKIA[0-9A-Z]{16}/],
33
+ ['Slack token', /xox[baprs]-[A-Za-z0-9-]{10,}/],
34
+ ['Private key block', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
35
+ ['Hardcoded secret', /["'](password|passwd|secret|api[_-]?key|token)["']\s*[:=]\s*["'][^"']{8,}["']/i]
36
+ ];
37
+
38
+ const results = [];
39
+ function check(phase, name, ok, detail = '') {
40
+ results.push({ phase, name, ok: Boolean(ok), detail });
41
+ console.log(` [${phase}] ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`);
42
+ }
43
+ function warn(phase, name, detail = '') {
44
+ results.push({ phase, name: `WARN ${name}`, ok: true, detail });
45
+ console.log(` [${phase}] WARN ${name}${detail ? ` — ${detail}` : ''}`);
46
+ }
47
+ function note(phase, text) {
48
+ console.log(` [${phase}] ${text}`);
49
+ }
50
+
51
+ function run(cmd, args, opts = {}) {
52
+ const res = spawnSync(cmd, args, {
53
+ encoding: 'utf8',
54
+ cwd: opts.cwd || REPO_ROOT,
55
+ env: { ...process.env, ...(opts.env || {}) },
56
+ timeout: opts.timeout || 180000,
57
+ maxBuffer: 32 * 1024 * 1024
58
+ });
59
+ if (res.error) throw res.error;
60
+ return { code: res.status, out: `${res.stdout || ''}${res.stderr || ''}` };
61
+ }
62
+
63
+ function listFiles(dir) {
64
+ const out = [];
65
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
66
+ const full = path.join(dir, entry.name);
67
+ if (entry.isDirectory()) out.push(...listFiles(full));
68
+ else out.push(full);
69
+ }
70
+ return out;
71
+ }
72
+
73
+ function homeConfigSnapshot() {
74
+ const dir = path.join(os.homedir(), '.release-cherry-pick');
75
+ if (!fs.existsSync(dir)) return { existed: false };
76
+ const entries = fs.readdirSync(dir).sort().map((name) => {
77
+ const stat = fs.statSync(path.join(dir, name));
78
+ return `${name}:${stat.mtimeMs}`;
79
+ });
80
+ return { existed: true, entries: entries.join('|') };
81
+ }
82
+
83
+ // --------------------------------------------------------------------------- phase 1: seguridad
84
+
85
+ async function phaseSecurity(root, version) {
86
+ const phase = '1-seguridad';
87
+ const metaRes = await fetch(`https://registry.npmjs.org/${PKG_NAME}/${version}`);
88
+ if (metaRes.status !== 200) {
89
+ check(phase, `version ${version} exists in the registry`, false, `HTTP ${metaRes.status}`);
90
+ return null;
91
+ }
92
+ const meta = await metaRes.json();
93
+ check(phase, `version ${version} exists in the registry`, true, meta.dist.tarball);
94
+
95
+ const tarballPath = path.join(root, `${PKG_NAME}-${version}.tgz`);
96
+ const tarballRes = await fetch(meta.dist.tarball);
97
+ const tarball = Buffer.from(await tarballRes.arrayBuffer());
98
+ fs.writeFileSync(tarballPath, tarball);
99
+ const digest = `sha512-${crypto.createHash('sha512').update(tarball).digest('base64')}`;
100
+ check(phase, 'tarball matches registry dist.integrity', digest === meta.dist.integrity, digest.slice(0, 28) + '…');
101
+
102
+ const extractDir = path.join(root, 'extracted');
103
+ fs.mkdirSync(extractDir, { recursive: true });
104
+ const extract = run('tar', ['-xzf', tarballPath, '-C', extractDir]);
105
+ check(phase, 'tarball extracts cleanly', extract.code === 0, extract.out.trim());
106
+ const pkgDir = path.join(extractDir, 'package');
107
+
108
+ const entries = run('tar', ['-tzf', tarballPath]).out.trim().split('\n').filter(Boolean);
109
+ check(phase, 'fileCount matches dist.fileCount', entries.length === meta.dist.fileCount,
110
+ `${entries.length} vs ${meta.dist.fileCount}`);
111
+
112
+ // Credentials / key material must never ship in a tarball
113
+ const leaked = entries.filter((e) =>
114
+ /(^|\/)(\.env(\..*)?|\.npmrc|\.netrc|\.gitconfig|id_rsa|id_ed25519|[^/]*\.(pem|key|p12|pfx|jks))$/i.test(e));
115
+ check(phase, 'no credential/key files in the tarball', leaked.length === 0, leaked.join(', '));
116
+
117
+ const dotEntries = entries.filter((e) => /(^|\/)\.[^/]/.test(e));
118
+ const dangerousDots = dotEntries.filter((e) => /\.git\//.test(e) || /\.env/.test(e));
119
+ check(phase, 'no .git/ or .env* entries in the tarball', dangerousDots.length === 0, dangerousDots.join(', '));
120
+ if (dotEntries.length > 0 && dangerousDots.length === 0) warn(phase, 'dotfiles shipped', dotEntries.join(', '));
121
+
122
+ const devEntries = entries.filter((e) => /^package\/(scripts|tests?|openspec|\.github)\//.test(e));
123
+ if (devEntries.length > 0) warn(phase, 'dev/test files shipped', `${devEntries.length} files (scripts/, tests/, .github/)`);
124
+ else note(phase, 'only runtime files shipped (src/, README, LICENSE, package.json)');
125
+
126
+ const pub = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8'));
127
+ const installScripts = ['preinstall', 'install', 'postinstall'].filter((s) => pub.scripts && pub.scripts[s]);
128
+ check(phase, 'no install-time lifecycle scripts (RCE surface)', installScripts.length === 0,
129
+ installScripts.map((s) => `${s}: ${pub.scripts[s]}`).join(', '));
130
+ if (pub.scripts && pub.scripts.prepare) {
131
+ warn(phase, 'prepare script shipped', `"${pub.scripts.prepare}" — runs on git installs and on pack/publish, not on registry installs`);
132
+ }
133
+ check(phase, 'published license field is MIT', pub.license === 'MIT', String(pub.license));
134
+ const licenseFile = fs.readFileSync(path.join(pkgDir, 'LICENSE'), 'utf8');
135
+ check(phase, 'LICENSE file is MIT', licenseFile.trimStart().startsWith('MIT License'));
136
+
137
+ const binRel = pub.bin && pub.bin[PKG_NAME];
138
+ check(phase, 'bin entry points at an existing file with a shebang', Boolean(binRel) && fs.existsSync(path.join(pkgDir, binRel)) &&
139
+ fs.readFileSync(path.join(pkgDir, binRel), 'utf8').startsWith('#!/usr/bin/env node'), String(binRel));
140
+
141
+ // Every Inquirer prompt that collects a secret must be password-type with a mask (inquirer 8
142
+ // ignores `mask` on plain input prompts, which would echo the secret in clear)
143
+ const srcFiles = listFiles(path.join(pkgDir, 'src')).filter((f) => f.endsWith('.js'));
144
+ const secretPrompts = [];
145
+ for (const file of srcFiles) {
146
+ const content = fs.readFileSync(file, 'utf8');
147
+ for (const match of content.matchAll(/type: 'password'/g)) {
148
+ const block = content.slice(match.index, match.index + 300);
149
+ secretPrompts.push({ file: path.relative(pkgDir, file), masked: /mask: '\*'/.test(block) });
150
+ }
151
+ }
152
+ check(phase, 'secret prompts are password-type with a mask',
153
+ secretPrompts.length >= 3 && secretPrompts.every((p) => p.masked),
154
+ secretPrompts.map((p) => `${p.file}:${p.masked ? 'masked' : 'NOT MASKED'}`).join(', '));
155
+
156
+ // Secret scan over every shipped file. Matches that are clearly documentation placeholders
157
+ // (maskSecret's own example, "your-token", "xxxx…") are not secrets.
158
+ const PLACEHOLDER = /(x{4,}|example|placeholder|your[_-]?|AbCdEf|123456|<[^>]+>|\.\.\.)/i;
159
+ const hits = [];
160
+ for (const file of listFiles(pkgDir)) {
161
+ const content = fs.readFileSync(file, 'utf8');
162
+ for (const [label, re] of SECRET_PATTERNS) {
163
+ const match = content.match(re);
164
+ if (match && !PLACEHOLDER.test(match[0])) {
165
+ hits.push(`${path.relative(pkgDir, file)}: ${label} (${match[0].slice(0, 12)}…)`);
166
+ }
167
+ }
168
+ }
169
+ check(phase, 'no secrets hardcoded in shipped files', hits.length === 0, hits.join('; '));
170
+
171
+ // npm requires an author/maintainer and a repository; nothing secret, but assert no stray env file
172
+ check(phase, 'dependencies are declared (no bundled node_modules)', !entries.some((e) => e.includes('node_modules/')),
173
+ entries.filter((e) => e.includes('node_modules/')).slice(0, 3).join(', '));
174
+
175
+ return { meta, tarballPath, pkgDir, version };
176
+ }
177
+
178
+ // ------------------------------------------------------------------------ phase 2: instalación
179
+
180
+ function phaseInstall(root, tarballPath, version) {
181
+ const phase = '2-instalación';
182
+ const installDir = path.join(root, 'install');
183
+ fs.mkdirSync(installDir, { recursive: true });
184
+
185
+ const homeBefore = homeConfigSnapshot();
186
+ const install = run('npm', ['install', '--prefix', installDir, '--no-fund', tarballPath], { cwd: root });
187
+ check(phase, 'npm install <tarball> succeeds', install.code === 0, install.out.trim().split('\n').slice(-3).join(' | '));
188
+
189
+ const lifecycle = install.out.split('\n').filter((l) => /^\s*>\s*(preinstall|install|postinstall|prepare)\b/.test(l));
190
+ check(phase, 'no lifecycle script output during install', lifecycle.length === 0, lifecycle.join(' | '));
191
+
192
+ const bin = path.join(installDir, 'node_modules', '.bin', PKG_NAME);
193
+ check(phase, 'bin shim created', fs.existsSync(bin));
194
+
195
+ const ver = run(bin, ['--version'], { cwd: root });
196
+ check(phase, 'CLI --version reports the published version', ver.code === 0 && ver.out.trim() === version, ver.out.trim());
197
+
198
+ const help = run(bin, ['--help'], { cwd: root });
199
+ check(phase, 'CLI --help lists release and config', help.code === 0 && /release/.test(help.out) && /config/.test(help.out),
200
+ help.out.split('\n').filter((l) => /^\s+\w/.test(l)).slice(0, 4).join(' | '));
201
+
202
+ const configDir = path.join(root, 'config');
203
+ const cfg = run(bin, ['config', '--show'], { cwd: root, env: { RELEASE_CHERRY_PICK_CONFIG_DIR: configDir } });
204
+ check(phase, 'config --show runs with a sandboxed config dir', cfg.code === 0 && /No configuration found/.test(cfg.out),
205
+ cfg.out.trim().split('\n')[0]);
206
+
207
+ const homeAfter = homeConfigSnapshot();
208
+ check(phase, 'real ~/.release-cherry-pick untouched', JSON.stringify(homeBefore) === JSON.stringify(homeAfter),
209
+ homeBefore.existed ? 'entries unchanged' : 'directory not created');
210
+
211
+ const audit = run('npm', ['audit', '--prefix', installDir, '--json'], { cwd: root });
212
+ let report = null;
213
+ try {
214
+ report = JSON.parse(audit.out);
215
+ } catch { /* npm audit --json output unparseable */ }
216
+ const vulns = report && report.metadata && report.metadata.vulnerabilities;
217
+ const SEVERITIES = ['info', 'low', 'moderate', 'high', 'critical'];
218
+ const total = vulns ? SEVERITIES.reduce((sum, s) => sum + (vulns[s] || 0), 0) : null;
219
+ if (total === null) warn(phase, 'npm audit result not parseable', audit.out.slice(0, 200));
220
+ else if (total === 0) check(phase, 'npm audit: 0 vulnerabilities', true);
221
+ else {
222
+ const serious = Object.entries((report && report.vulnerabilities) || {})
223
+ .filter(([, v]) => v.severity === 'high' || v.severity === 'critical')
224
+ .map(([name, v]) => `${name} (${v.severity})`);
225
+ warn(phase, `npm audit: ${total} vulnerabilities`,
226
+ `${JSON.stringify(vulns)}${serious.length ? ` — ${serious.join(', ')}` : ''}`);
227
+ }
228
+
229
+ return { installDir, toolDir: path.join(installDir, 'node_modules', PKG_NAME) };
230
+ }
231
+
232
+ // ----------------------------------------------------------------------- phase 3: cherry-pick
233
+
234
+ function branches(repo, pattern = 'refs/heads') {
235
+ const out = run('git', ['-C', repo, 'for-each-ref', '--format=%(refname:short)', pattern]).out.trim();
236
+ return out ? out.split('\n') : [];
237
+ }
238
+
239
+ function gitOut(repo, args) {
240
+ return run('git', ['-C', repo, ...args]);
241
+ }
242
+
243
+ // Fresh mutated repo + release run from tasks.txt. Extra args go to run-release.js.
244
+ function runFlow(root, toolDir, name, extra = []) {
245
+ const repoDir = path.join(root, name);
246
+ const mk = run('bash', [path.join(REPO_ROOT, 'scripts', 'sandbox', 'make-sandbox.sh'), repoDir]);
247
+ if (mk.code !== 0) throw new Error(`make-sandbox failed: ${mk.out}`);
248
+ const workDir = path.join(repoDir, 'work');
249
+ const release = run('node', [
250
+ path.join(REPO_ROOT, 'scripts', 'sandbox', 'run-release.js'),
251
+ '-f', 'tasks.txt', '--work', workDir, '--tool', toolDir, ...extra
252
+ ]);
253
+ return { repoDir, workDir, out: release.out, code: release.code };
254
+ }
255
+
256
+ // One mutated scenario per branch: normal / conflict / already-applied / duplicate task ID
257
+ function assertSummary(phase, out) {
258
+ const expectations = [
259
+ ['PB-100', 'PROCEDE'],
260
+ ['PB-I200', 'PROCEDE'],
261
+ ['PB-300', 'CONFLICT'],
262
+ ['PB-400', 'SKIPPED'],
263
+ ['PB-500', 'PROCEDE']
264
+ ];
265
+ const lines = out.split('\n');
266
+ for (const [taskId, status] of expectations) {
267
+ const line = lines.find((l) => l.includes(`[${taskId}]`) && /— (PROCEDE|NO PROCEDE|CONFLICT|SKIPPED)/.test(l));
268
+ check(phase, `${taskId} -> ${status}`, Boolean(line) && line.includes(status), line ? line.trim() : 'summary line not found');
269
+ }
270
+ check(phase, 'summary totals are 5/3/0/1/1',
271
+ /Total: 5 \| PROCEDE: 3 \| NO PROCEDE: 0 \| CONFLICT: 1 \| SKIPPED: 1/.test(out));
272
+ }
273
+
274
+ // git state: the run must leave the workspace exactly as it found it
275
+ function assertCleanState(phase, workDir) {
276
+ const porcelain = run('git', ['-C', workDir, 'status', '--porcelain']).out.trim();
277
+ check(phase, 'work tree clean after the run', porcelain === '', porcelain);
278
+ check(phase, 'no cherry-pick left in progress', !fs.existsSync(path.join(workDir, '.git', 'CHERRY_PICK_HEAD')));
279
+ const head = run('git', ['-C', workDir, 'rev-parse', '--abbrev-ref', 'HEAD']).out.trim();
280
+ check(phase, 'back on the starting branch (staging)', head === 'staging', head);
281
+ }
282
+
283
+ // autoCreateMR=false (the shipped sandbox default): cherry-pick only, nothing leaves the machine
284
+ function phaseCherryPickNoPush(root, toolDir) {
285
+ const phase = '3-cherry-pick (sin MR)';
286
+ const { repoDir, workDir, out, code } = runFlow(root, toolDir, 'repo');
287
+ check(phase, 'release flow exits 0', code === 0, out.split('\n').filter((l) => /error|ERR/i.test(l)).slice(0, 2).join(' | '));
288
+ assertSummary(phase, out);
289
+ assertCleanState(phase, workDir);
290
+
291
+ const originBranches = branches(path.join(repoDir, 'origin.git'));
292
+ check(phase, 'nothing pushed to origin (autoCreateMR=false)',
293
+ !originBranches.some((b) => b.startsWith('release/')), originBranches.join(', '));
294
+
295
+ const localRelease = branches(workDir, 'refs/heads/release/*');
296
+ for (const branch of ['release/PB-100-list-user', 'release/PB-I200-favicon', 'release/PB-500-one']) {
297
+ check(phase, `kept locally: ${branch}`, localRelease.includes(branch), localRelease.join(', '));
298
+ }
299
+ check(phase, 'no local leftovers for CONFLICT/SKIPPED',
300
+ !localRelease.some((b) => b.includes('PB-300') || b.includes('PB-400')), localRelease.join(', '));
301
+
302
+ // The cherry-pick really mutated the release branch — and only the tagged commits
303
+ const picked = gitOut(workDir, ['log', 'release/PB-100-list-user', '--grep=\\[PB-100\\]', '--oneline']).out.trim().split('\n').filter(Boolean);
304
+ check(phase, 'PB-100: exactly 2 tagged commits cherry-picked', picked.length === 2, picked.join(' | '));
305
+ const onStaging = gitOut(workDir, ['log', 'staging', '--grep=\\[PB-100\\]', '--oneline']).out.trim();
306
+ check(phase, 'PB-100: staging untouched', onStaging === '');
307
+ const noise = gitOut(workDir, ['show', 'release/PB-100-list-user:noise.txt']);
308
+ check(phase, 'untagged commit was not picked', noise.code !== 0);
309
+ const conflicted = gitOut(workDir, ['show', 'release/PB-300-conflict:shared.txt']);
310
+ check(phase, 'CONFLICT branch not created from a resolved state', conflicted.code !== 0);
311
+ }
312
+
313
+ // The tool reads the origin remote with `git remote get-url`, which applies url.*.insteadOf and
314
+ // would hand it the local bare path (parseRemoteUrl then fails and every GitLab call dies). The
315
+ // shim prints the raw configured URL instead; every other git command passes through untouched.
316
+ function installGitShim(root) {
317
+ const binDir = path.join(root, 'bin');
318
+ fs.mkdirSync(binDir, { recursive: true });
319
+ const realGit = spawnSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).stdout.trim() || 'git';
320
+ const shim = `#!/usr/bin/env bash
321
+ real_git=${JSON.stringify(realGit)}
322
+ args=("$@")
323
+ for ((i = 0; i + 1 < \${#args[@]}; i++)); do
324
+ if [ "\${args[i]}" = "remote" ] && [ "\${args[i+1]}" = "get-url" ]; then
325
+ exec "$real_git" config --get remote.origin.url
326
+ fi
327
+ done
328
+ exec "$real_git" "$@"
329
+ `;
330
+ fs.writeFileSync(path.join(binDir, 'git'), shim, { mode: 0o755 });
331
+ return binDir;
332
+ }
333
+
334
+ // Point origin at a GitLab-looking URL (so getProjectPathId works) while url.*.insteadOf keeps
335
+ // fetch/push talking to the local bare repo — nothing ever leaves the machine.
336
+ function fakeGitlabRemote(repoDir, workDir) {
337
+ const fakeRemote = 'https://gitlab.example.com/sandbox/project.git';
338
+ run('git', ['-C', workDir, 'remote', 'set-url', 'origin', fakeRemote]);
339
+ fs.appendFileSync(path.join(workDir, '.git', 'config'),
340
+ `\n[url "${path.join(repoDir, 'origin.git')}"]\n\tinsteadOf = ${fakeRemote}\n`);
341
+ return fakeRemote;
342
+ }
343
+
344
+ function shimEnv(binDir) {
345
+ return { PATH: `${binDir}${path.delimiter}${process.env.PATH}` };
346
+ }
347
+
348
+ // autoCreateMR=true + --fake-gitlab: push to origin and MR creation through the real REST client
349
+ function phaseCherryPickWithMR(root, toolDir) {
350
+ const phase = '3b-cherry-pick (con MR)';
351
+ const repoDir = path.join(root, 'repo-mr');
352
+ const mk = run('bash', [path.join(REPO_ROOT, 'scripts', 'sandbox', 'make-sandbox.sh'), repoDir]);
353
+ check(phase, 'mutated sandbox repo created', mk.code === 0, mk.out.trim().split('\n').pop());
354
+
355
+ const workDir = path.join(repoDir, 'work');
356
+ const binDir = installGitShim(root);
357
+ fakeGitlabRemote(repoDir, workDir);
358
+
359
+ // Rewrite the sandbox config through the *installed* loader (the project key is derived from the
360
+ // origin remote, so it changes with the remote URL): push + MR calls against the fake API host.
361
+ const flipConfig = [
362
+ 'process.env.RELEASE_CHERRY_PICK_CONFIG_DIR = process.argv[1];',
363
+ 'const loader = require(process.argv[2] + "/src/config/loader");',
364
+ 'const config = loader.loadConfig() || {};',
365
+ 'config.release = Object.assign({}, config.release, { autoCreateMR: true });',
366
+ 'config.gitlab = Object.assign({}, config.gitlab, { host: "https://gitlab.example.com" });',
367
+ 'loader.saveConfig(config);',
368
+ 'console.log("config: " + loader.getConfigPath());'
369
+ ].join('\n');
370
+ const flip = run('node', ['-e', flipConfig, path.join(repoDir, 'config'), toolDir],
371
+ { cwd: workDir, env: shimEnv(binDir) });
372
+ check(phase, 'config flipped to autoCreateMR=true', flip.code === 0, flip.out.trim());
373
+ const release = run('node', [
374
+ path.join(REPO_ROOT, 'scripts', 'sandbox', 'run-release.js'),
375
+ '-f', 'tasks.txt', '--work', workDir, '--tool', toolDir, '--fake-gitlab'
376
+ ], { env: shimEnv(binDir) });
377
+ const out = release.out;
378
+ check(phase, 'release flow exits 0', release.code === 0, out.split('\n').filter((l) => /error|ERR/i.test(l)).slice(0, 2).join(' | '));
379
+ assertSummary(phase, out);
380
+ assertCleanState(phase, workDir);
381
+
382
+ const originBranches = branches(path.join(repoDir, 'origin.git'));
383
+ for (const branch of ['release/PB-100-list-user', 'release/PB-I200-favicon', 'release/PB-500-one']) {
384
+ check(phase, `pushed: ${branch}`, originBranches.includes(branch), originBranches.join(', '));
385
+ }
386
+ for (const branch of ['release/PB-300-conflict', 'release/PB-400-already']) {
387
+ check(phase, `not pushed: ${branch}`, !originBranches.includes(branch));
388
+ }
389
+
390
+ const posts = out.split('\n').filter((l) => l.includes('[fake-gitlab] POST') && l.includes('/merge_requests'));
391
+ check(phase, 'one MR per PROCEDE branch', posts.length === 3, posts.join(' | '));
392
+ check(phase, 'MR source_branch is the release branch',
393
+ posts.some((l) => l.includes('"source_branch":"release/PB-100-list-user"')));
394
+ check(phase, 'reviewer_ids sent to the API', posts.some((l) => l.includes('"reviewer_ids"')));
395
+ }
396
+
397
+ // Secrets must never leak: not to the console, not to generated reports, not to git metadata, and
398
+ // the config file itself must be private (0600/0700) and outside the target repo.
399
+ function phaseSecrets(root, toolDir) {
400
+ const phase = '4-secretos';
401
+ const TOKEN = 'glpat-9QwErTyUiOpAsDfGhJkLz';
402
+ const AIKEY = 'sk-ant-api03-Ab12Cd34Ef56Gh78Ij90';
403
+
404
+ const repoDir = path.join(root, 'repo-secret');
405
+ const mk = run('bash', [path.join(REPO_ROOT, 'scripts', 'sandbox', 'make-sandbox.sh'), repoDir]);
406
+ check(phase, 'sandbox created', mk.code === 0, mk.out.trim().split('\n').pop());
407
+ const workDir = path.join(repoDir, 'work');
408
+ const binDir = installGitShim(root);
409
+ fakeGitlabRemote(repoDir, workDir);
410
+
411
+ const configDir = path.join(repoDir, 'config');
412
+ const writeConfig = [
413
+ 'process.env.RELEASE_CHERRY_PICK_CONFIG_DIR = process.argv[1];',
414
+ 'const loader = require(process.argv[2] + "/src/config/loader");',
415
+ 'const config = loader.loadConfig() || {};',
416
+ 'config.release = Object.assign({}, config.release, { autoCreateMR: true });',
417
+ 'config.gitlab = Object.assign({}, config.gitlab, { host: "https://gitlab.example.com", token: process.argv[3] });',
418
+ 'config.ai = Object.assign({}, config.ai, { apiKey: process.argv[4] });',
419
+ 'loader.saveConfig(config);',
420
+ 'console.log(loader.getConfigPath());'
421
+ ].join('\n');
422
+ const saved = run('node', ['-e', writeConfig, configDir, toolDir, TOKEN, AIKEY],
423
+ { cwd: workDir, env: shimEnv(binDir) });
424
+ const configPath = saved.out.trim().split('\n').pop();
425
+ check(phase, 'config written outside the target repo', fs.existsSync(configPath) && configPath.startsWith(configDir), configPath);
426
+
427
+ const mode = (p) => (fs.statSync(p).mode & 0o777).toString(8);
428
+ check(phase, 'config file is 0600', mode(configPath) === '600', mode(configPath));
429
+ check(phase, 'config dir is 0700', mode(configDir) === '700', mode(configDir));
430
+
431
+ const release = run('node', [
432
+ path.join(REPO_ROOT, 'scripts', 'sandbox', 'run-release.js'),
433
+ '-f', 'tasks.txt', '--work', workDir, '--tool', toolDir, '--fake-gitlab', '--answer', 'saveReport=true'
434
+ ], { env: shimEnv(binDir) });
435
+ const out = release.out;
436
+ check(phase, 'release flow exits 0', release.code === 0, out.split('\n').filter((l) => /error|ERR/i.test(l)).slice(0, 2).join(' | '));
437
+ assertSummary(phase, out);
438
+ assertCleanState(phase, workDir);
439
+
440
+ // Nothing in the workspace (console output, reports, git metadata) may contain a raw secret
441
+ const leaks = [];
442
+ if (out.includes(TOKEN)) leaks.push('console output');
443
+ if (out.includes(AIKEY)) leaks.push('console output (ai key)');
444
+ for (const file of listFiles(workDir)) {
445
+ if (file.startsWith(configDir)) continue;
446
+ let content;
447
+ try {
448
+ content = fs.readFileSync(file, 'utf8');
449
+ } catch {
450
+ continue;
451
+ }
452
+ if (content.includes(TOKEN) || content.includes(AIKEY)) leaks.push(`file: ${path.relative(workDir, file)}`);
453
+ }
454
+ check(phase, 'no raw secret in output, reports or git metadata', leaks.length === 0, leaks.join(', '));
455
+
456
+ const summaryPath = path.join(workDir, 'release-summary.md');
457
+ const summary = fs.existsSync(summaryPath) ? fs.readFileSync(summaryPath, 'utf8') : '';
458
+ check(phase, 'release-summary.md written and free of secrets', summary.includes('PROCEDE') && !summary.includes(TOKEN) && !summary.includes(AIKEY));
459
+
460
+ const show = run(path.join(root, 'install', 'node_modules', '.bin', PKG_NAME), ['config', '--show'],
461
+ { cwd: workDir, env: { ...shimEnv(binDir), RELEASE_CHERRY_PICK_CONFIG_DIR: configDir } });
462
+ check(phase, 'config --show never prints raw secrets',
463
+ show.code === 0 && !show.out.includes(TOKEN) && !show.out.includes(AIKEY));
464
+ check(phase, 'config --show masks the token as glpat-****', /glpat-\*{4}/.test(show.out),
465
+ (show.out.match(/glpat-[^\s"]*/) || ['not found'])[0]);
466
+ check(phase, 'config --show masks the AI key as sk-ant-****', /sk-ant-\*{4}/.test(show.out),
467
+ (show.out.match(/sk-ant-[^\s"]*/) || ['not found'])[0]);
468
+ }
469
+
470
+ function phaseCherryPick(root, toolDir) {
471
+ phaseCherryPickNoPush(root, toolDir);
472
+ phaseCherryPickWithMR(root, toolDir);
473
+ phaseSecrets(root, toolDir);
474
+ }
475
+
476
+ // simple-git v4 strips ambient GIT_* variables from the git child process; git-auth.js depends on
477
+ // GIT_CONFIG_* getting through, so verify both halves: the token reaches git via createGit(), and a
478
+ // plain instance would drop it (i.e. the allow-list in src/git/instance.js is load-bearing).
479
+ function phaseGitAuthEnv(root) {
480
+ const phase = '5-git-auth (simple-git v4, código local)';
481
+ const toolDir = REPO_ROOT;
482
+ const sgPkgPath = findInstalled('simple-git', path.join(REPO_ROOT, 'node_modules'));
483
+ const version = sgPkgPath ? JSON.parse(fs.readFileSync(sgPkgPath, 'utf8')).version : 'missing';
484
+ check(phase, 'local simple-git is >= 4.0.2 (fixes the criticals)',
485
+ version !== 'missing' && !/^4\.0\.[01]$/.test(version) && Number(version.split('.')[0]) >= 4, version);
486
+
487
+ const repo = path.join(root, 'repo', 'work');
488
+ const script = [
489
+ 'const path = require("path");',
490
+ 'const tool = process.argv[1];',
491
+ 'const repo = process.argv[2];',
492
+ 'process.env.GIT_CONFIG_COUNT = "1";',
493
+ 'process.env.GIT_CONFIG_KEY_0 = "http.extraheader";',
494
+ 'process.env.GIT_CONFIG_VALUE_0 = "Authorization: Basic c2FuZGJveA==";',
495
+ 'const { createGit } = require(path.join(tool, "src/git/instance"));',
496
+ 'const { simpleGit } = require(require.resolve("simple-git", { paths: [tool] }));',
497
+ '(async () => {',
498
+ ' const allowed = await createGit().raw(["config", "--list"]);',
499
+ ' const guarded = await simpleGit({ baseDir: repo }).raw(["config", "--list"]);',
500
+ ' console.log(JSON.stringify({',
501
+ ' allowed: /http\\.extraheader/.test(allowed) && /Authorization: Basic/.test(allowed),',
502
+ ' guarded: /http\\.extraheader/.test(guarded)',
503
+ ' }));',
504
+ '})().catch((e) => { console.error(e); process.exit(1); });'
505
+ ].join('\n');
506
+ const res = run('node', ['-e', script, toolDir, repo], { cwd: repo });
507
+ let out = null;
508
+ try {
509
+ out = JSON.parse(res.out.trim().split('\n').pop());
510
+ } catch { /* unparseable */ }
511
+ check(phase, 'GIT_CONFIG_* token header reaches git through createGit()',
512
+ Boolean(out && out.allowed), res.out.trim().slice(0, 160));
513
+ check(phase, 'plain instance strips it (allow-list is required)',
514
+ Boolean(out && out.guarded === false));
515
+ }
516
+
517
+ // Locates <pkg>/package.json walking up from a node_modules dir (handles hoisted and nested layouts)
518
+ function findInstalled(pkg, fromDir) {
519
+ let dir = fromDir;
520
+ for (let i = 0; i < 5; i++) {
521
+ const candidate = path.join(dir, pkg, 'package.json');
522
+ if (fs.existsSync(candidate)) return candidate;
523
+ const parent = path.dirname(dir);
524
+ if (parent === dir) break;
525
+ dir = parent;
526
+ }
527
+ return null;
528
+ }
529
+
530
+ // ----------------------------------------------------------------------------------------- main
531
+
532
+ async function main() {
533
+ const argv = process.argv.slice(2);
534
+ let version = '1.0.0';
535
+ let sandbox = DEFAULT_SANDBOX;
536
+ let keep = false;
537
+ for (let i = 0; i < argv.length; i++) {
538
+ if (argv[i] === '--version') version = argv[++i];
539
+ else if (argv[i] === '--sandbox') sandbox = path.resolve(argv[++i]);
540
+ else if (argv[i] === '--keep') keep = true;
541
+ }
542
+
543
+ fs.rmSync(sandbox, { recursive: true, force: true });
544
+ fs.mkdirSync(sandbox, { recursive: true });
545
+ const root = fs.realpathSync(sandbox);
546
+ console.log(`\nSandbox: ${root}\n`);
547
+
548
+ const artifact = await phaseSecurity(root, version);
549
+ let installed = null;
550
+ if (artifact) installed = phaseInstall(root, artifact.tarballPath, version);
551
+ if (installed) {
552
+ phaseCherryPick(root, installed.toolDir);
553
+ phaseGitAuthEnv(root);
554
+ }
555
+
556
+ const failed = results.filter((r) => !r.ok);
557
+ const warnings = results.filter((r) => r.name.startsWith('WARN '));
558
+ console.log(`\n${'='.repeat(70)}`);
559
+ console.log(`Resultado: ${results.length - failed.length}/${results.length} checks OK` +
560
+ (warnings.length ? `, ${warnings.length} warning(s)` : '') +
561
+ (failed.length ? `, ${failed.length} FALLIDO(S)` : ''));
562
+ for (const f of failed) console.log(` FAIL [${f.phase}] ${f.name}${f.detail ? ` — ${f.detail}` : ''}`);
563
+ console.log(`Artefacto y config viven en: ${root}`);
564
+ if (!keep) console.log('(usa --keep para no borrarlo en la próxima corrida)');
565
+ process.exit(failed.length ? 1 : 0);
566
+ }
567
+
568
+ main().catch((error) => {
569
+ console.error(error);
570
+ process.exit(1);
571
+ });
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 1,
3
+ "skills": {
4
+ "nodejs-backend-patterns": {
5
+ "source": "wshobson/agents",
6
+ "sourceType": "github",
7
+ "skillPath": "plugins/javascript-typescript/skills/nodejs-backend-patterns/SKILL.md",
8
+ "computedHash": "b63b54d09c77cec0e84cdd42424c12909785f14bdb286c835c45420b885ff1f3"
9
+ }
10
+ }
11
+ }
@@ -1,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  const inquirer = require('inquirer');
4
- const simpleGit = require('simple-git');
4
+ const { createGit } = require('./instance');
5
5
  const logger = require('../utils/logger');
6
6
  const { searchableCheckbox } = require('../utils/prompts');
7
7
  const { defaultConfig } = require('../config/defaults');
8
8
 
9
- const git = simpleGit();
9
+ const git = createGit();
10
10
 
11
11
  // Prefixes of the branches a release can be cut from (every configured prefix except release)
12
12
  // (falls back to the defaults when none are configured).
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- const simpleGit = require('simple-git');
3
+ const { createGit } = require('./instance');
4
4
  const logger = require('../utils/logger');
5
5
  const { GitError } = require('../utils/errors');
6
6
 
7
- const git = simpleGit();
7
+ const git = createGit();
8
8
 
9
9
  // Cherry-picks `commits` (in order) onto the current branch; when not given, the ones tagged
10
10
  // "[taskId]" on sourceBranch that aren't on baseBranch (see getCommitsToCherryPick).
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const simpleGit = require('simple-git');
3
+ const { createGit } = require('./instance');
4
4
 
5
5
  function getToken(config) {
6
6
  return (config && config.gitlab && config.gitlab.token) || process.env.GITLAB_TOKEN || '';
@@ -12,8 +12,10 @@ function getToken(config) {
12
12
  // not be asked for credentials again. SSH origins already authenticate via the user's key and are
13
13
  // left untouched. The header is injected only for this process, through env vars git itself reads
14
14
  // (GIT_CONFIG_COUNT/KEY/VALUE, supported since Git 2.31) — it is never written to .git/config, so
15
- // the token never lingers in the target repo once the CLI exits. GitLab's git-over-HTTP Basic auth
16
- // validates the token itself and doesn't check the username, so any non-blank placeholder works.
15
+ // the token never lingers in the target repo once the CLI exits. simple-git v4 strips ambient GIT_*
16
+ // variables from the child process, so those three are allow-listed in ./instance.js — without it
17
+ // this header would be dropped silently. GitLab's git-over-HTTP Basic auth validates the token
18
+ // itself and doesn't check the username, so any non-blank placeholder works.
17
19
  // No-op without a token configured, or when origin isn't http(s).
18
20
  async function configureGitCredentials(config) {
19
21
  const token = getToken(config);
@@ -23,7 +25,7 @@ async function configureGitCredentials(config) {
23
25
 
24
26
  let remoteUrl;
25
27
  try {
26
- remoteUrl = (await simpleGit().raw(['remote', 'get-url', 'origin'])).trim();
28
+ remoteUrl = (await createGit().raw(['remote', 'get-url', 'origin'])).trim();
27
29
  } catch {
28
30
  return;
29
31
  }
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ const { simpleGit } = require('simple-git');
4
+
5
+ // simple-git v4 strips ambient `GIT_*` variables from the environment of the git child process
6
+ // (they can change which program git runs), so they must be allowed explicitly. git-auth.js hands
7
+ // the GitLab token to git through GIT_CONFIG_COUNT/KEY/VALUE — injected per process, never written
8
+ // to disk — and those three would otherwise be dropped silently, sending every HTTPS fetch/pull/push
9
+ // back to git's interactive username/password prompt.
10
+ const ALLOWED_ENVIRONMENT = ['GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0'];
11
+
12
+ // Every simple-git instance in the app is created here so the allow-list above always applies.
13
+ function createGit() {
14
+ return simpleGit({ allowEnvironment: ALLOWED_ENVIRONMENT });
15
+ }
16
+
17
+ module.exports = { createGit, ALLOWED_ENVIRONMENT };