@aspruyt/xfg 7.5.2 → 8.1.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/dist/ai/client-factory.js +15 -3
- package/dist/cli/repo-sync-runner.d.ts +2 -0
- package/dist/cli/repo-sync-runner.js +18 -9
- package/dist/cli/secrets-command.js +16 -4
- package/dist/cli/settings-factories.d.ts +2 -1
- package/dist/cli/settings-factories.js +7 -1
- package/dist/cli/settings-report-builder.d.ts +6 -1
- package/dist/cli/settings-report-builder.js +7 -1
- package/dist/cli/settings-runner.js +24 -15
- package/dist/cli/sync-command.js +5 -1
- package/dist/cli/types.d.ts +4 -2
- package/dist/config/env.js +8 -0
- package/dist/config/file-reference-resolver.js +16 -13
- package/dist/config/index.d.ts +1 -1
- package/dist/config/merge.d.ts +9 -5
- package/dist/config/merge.js +148 -67
- package/dist/config/normalizer.js +87 -18
- package/dist/config/types.d.ts +28 -0
- package/dist/config/validator.js +25 -3
- package/dist/config/validators/ai-validator.js +2 -0
- package/dist/config/validators/file-validator.js +4 -1
- package/dist/config/validators/group-validator.js +3 -0
- package/dist/config/validators/ruleset-validator.js +6 -5
- package/dist/config/validators/shared.js +123 -0
- package/dist/output/settings-report.d.ts +6 -1
- package/dist/output/settings-report.js +31 -9
- package/dist/repo/detector.js +15 -24
- package/dist/settings/environments/diff.d.ts +22 -0
- package/dist/settings/environments/diff.js +78 -0
- package/dist/settings/environments/formatter.d.ts +17 -0
- package/dist/settings/environments/formatter.js +62 -0
- package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
- package/dist/settings/environments/github-environments-strategy.js +54 -0
- package/dist/settings/environments/index.d.ts +5 -0
- package/dist/settings/environments/index.js +3 -0
- package/dist/settings/environments/processor.d.ts +21 -0
- package/dist/settings/environments/processor.js +100 -0
- package/dist/settings/environments/types.d.ts +38 -0
- package/dist/settings/environments/types.js +1 -0
- package/dist/settings/index.d.ts +1 -0
- package/dist/settings/index.js +1 -0
- package/dist/settings/secrets/diff.d.ts +2 -0
- package/dist/settings/secrets/formatter.d.ts +4 -0
- package/dist/settings/secrets/formatter.js +17 -4
- package/dist/settings/secrets/index.d.ts +2 -2
- package/dist/settings/secrets/index.js +1 -1
- package/dist/settings/secrets/processor.d.ts +16 -2
- package/dist/settings/secrets/processor.js +132 -28
- package/dist/shared/credential-env.d.ts +10 -0
- package/dist/shared/credential-env.js +50 -0
- package/dist/shared/gh-token-utils.d.ts +7 -1
- package/dist/shared/gh-token-utils.js +14 -1
- package/dist/shared/github-host-policy.d.ts +22 -0
- package/dist/shared/github-host-policy.js +61 -0
- package/dist/shared/path-safety.d.ts +12 -0
- package/dist/shared/path-safety.js +51 -0
- package/dist/shared/retry-utils.js +9 -13
- package/dist/shared/sequential.d.ts +2 -0
- package/dist/shared/sequential.js +4 -0
- package/dist/sync/auth-options-builder.d.ts +3 -1
- package/dist/sync/auth-options-builder.js +4 -1
- package/dist/sync/manifest.js +7 -2
- package/dist/sync/render-writer.js +7 -1
- package/dist/sync/repository-processor.d.ts +2 -0
- package/dist/sync/repository-processor.js +1 -1
- package/dist/vcs/ado-pr-strategy.js +3 -2
- package/dist/vcs/commit-strategy-selector.d.ts +3 -2
- package/dist/vcs/commit-strategy-selector.js +5 -4
- package/dist/vcs/git-ops.d.ts +3 -3
- package/dist/vcs/git-ops.js +29 -8
- package/dist/vcs/github-app-token-manager.d.ts +4 -1
- package/dist/vcs/github-app-token-manager.js +24 -4
- package/dist/vcs/github-pr-strategy.js +3 -2
- package/package.json +3 -2
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ValidationError } from "./errors.js";
|
|
2
|
+
export declare const ALLOWED_GITHUB_HOSTS_ENV = "XFG_ALLOWED_GITHUB_HOSTS";
|
|
3
|
+
/** A bare DNS hostname: no scheme, userinfo, port, path, whitespace or trailing dot. */
|
|
4
|
+
export declare function isValidHostname(host: string): boolean;
|
|
5
|
+
/** Includes the short and hex forms (`1.2.3`, `0x7f.1`) that inet_aton accepts. */
|
|
6
|
+
export declare function isIpLiteral(host: string): boolean;
|
|
7
|
+
export declare class GitHubHostNotAllowedError extends ValidationError {
|
|
8
|
+
constructor(host: string);
|
|
9
|
+
}
|
|
10
|
+
/** Decides which GitHub hosts may receive App JWTs and tokens. */
|
|
11
|
+
export interface IGitHubHostPolicy {
|
|
12
|
+
isAllowed(host: string): boolean;
|
|
13
|
+
isAllowedApiHost(apiHost: string): boolean;
|
|
14
|
+
}
|
|
15
|
+
export declare class GitHubHostPolicy implements IGitHubHostPolicy {
|
|
16
|
+
private readonly hosts;
|
|
17
|
+
constructor(extraHosts?: readonly string[]);
|
|
18
|
+
isAllowed(host: string): boolean;
|
|
19
|
+
isAllowedApiHost(apiHost: string): boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function parseAllowedGitHubHosts(value: string | undefined): string[];
|
|
22
|
+
export declare function createGitHubHostPolicyFromEnv(env: Record<string, string | undefined>): GitHubHostPolicy;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
import { ValidationError } from "./errors.js";
|
|
3
|
+
export const ALLOWED_GITHUB_HOSTS_ENV = "XFG_ALLOWED_GITHUB_HOSTS";
|
|
4
|
+
const GITHUB_DOT_COM = "github.com";
|
|
5
|
+
const GITHUB_DOT_COM_API = "api.github.com";
|
|
6
|
+
const GHES_API_SUFFIX = "/api/v3";
|
|
7
|
+
const HOSTNAME_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
8
|
+
const NUMERIC_HOST = /^(?:0x[0-9a-f]+|\d+)(?:\.(?:0x[0-9a-f]+|\d+)){0,3}$/i;
|
|
9
|
+
/** A bare DNS hostname: no scheme, userinfo, port, path, whitespace or trailing dot. */
|
|
10
|
+
export function isValidHostname(host) {
|
|
11
|
+
if (host.length === 0 || host.length > 253)
|
|
12
|
+
return false;
|
|
13
|
+
return host.split(".").every((label) => HOSTNAME_LABEL.test(label));
|
|
14
|
+
}
|
|
15
|
+
/** Includes the short and hex forms (`1.2.3`, `0x7f.1`) that inet_aton accepts. */
|
|
16
|
+
export function isIpLiteral(host) {
|
|
17
|
+
const unbracketed = host.replace(/^\[(.*)\]$/, "$1");
|
|
18
|
+
return isIP(unbracketed) !== 0 || NUMERIC_HOST.test(host);
|
|
19
|
+
}
|
|
20
|
+
export class GitHubHostNotAllowedError extends ValidationError {
|
|
21
|
+
constructor(host) {
|
|
22
|
+
super(`GitHub host '${host}' is not in ${ALLOWED_GITHUB_HOSTS_ENV}; refusing to send GitHub credentials to it. ` +
|
|
23
|
+
`Only github.com is allowed by default. Set ${ALLOWED_GITHUB_HOSTS_ENV} to trust a GitHub Enterprise Server host.`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class GitHubHostPolicy {
|
|
27
|
+
hosts;
|
|
28
|
+
constructor(extraHosts = []) {
|
|
29
|
+
this.hosts = new Set([
|
|
30
|
+
GITHUB_DOT_COM,
|
|
31
|
+
...extraHosts.map((h) => h.toLowerCase()),
|
|
32
|
+
]);
|
|
33
|
+
}
|
|
34
|
+
isAllowed(host) {
|
|
35
|
+
return isValidHostname(host) && this.hosts.has(host.toLowerCase());
|
|
36
|
+
}
|
|
37
|
+
isAllowedApiHost(apiHost) {
|
|
38
|
+
const lower = apiHost.toLowerCase();
|
|
39
|
+
if (lower === GITHUB_DOT_COM_API)
|
|
40
|
+
return true;
|
|
41
|
+
if (!lower.endsWith(GHES_API_SUFFIX))
|
|
42
|
+
return false;
|
|
43
|
+
const host = lower.slice(0, -GHES_API_SUFFIX.length);
|
|
44
|
+
return host !== GITHUB_DOT_COM && this.isAllowed(host);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function parseAllowedGitHubHosts(value) {
|
|
48
|
+
const entries = (value ?? "").split(/[\s,]+/).filter(Boolean);
|
|
49
|
+
return entries.map((entry) => {
|
|
50
|
+
if (!isValidHostname(entry)) {
|
|
51
|
+
throw new ValidationError(`${ALLOWED_GITHUB_HOSTS_ENV} entries must be bare hostnames (no scheme, userinfo, port or path). Got: ${entry}`);
|
|
52
|
+
}
|
|
53
|
+
if (isIpLiteral(entry)) {
|
|
54
|
+
throw new ValidationError(`${ALLOWED_GITHUB_HOSTS_ENV} entries must be hostnames, not IP addresses. Got: ${entry}`);
|
|
55
|
+
}
|
|
56
|
+
return entry.toLowerCase();
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export function createGitHubHostPolicyFromEnv(env) {
|
|
60
|
+
return new GitHubHostPolicy(parseAllowedGitHubHosts(env[ALLOWED_GITHUB_HOSTS_ENV]));
|
|
61
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches every spelling filesystems resolve to `.git`: any case, Windows
|
|
3
|
+
* trailing dots/spaces, NTFS `::$` streams and the `GIT~1` short name.
|
|
4
|
+
*/
|
|
5
|
+
export declare function hasGitDirSegment(fileName: string): boolean;
|
|
6
|
+
/** True if `path` itself is a symlink, dangling or not. */
|
|
7
|
+
export declare function isSymlink(path: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Writes `content` to `path`, refusing if `path` is a symlink. A cloned repo
|
|
10
|
+
* can commit a symlink where xfg writes its own files.
|
|
11
|
+
*/
|
|
12
|
+
export declare function writeFileNoFollow(path: string, content: string): void;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { closeSync, constants, lstatSync, openSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { ValidationError } from "./errors.js";
|
|
3
|
+
// Characters HFS+ ignores in names, so `.g<ZWNJ>it` opens `.git` on macOS.
|
|
4
|
+
const IGNORABLE_CHARS = /[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF]/g;
|
|
5
|
+
/**
|
|
6
|
+
* Matches every spelling filesystems resolve to `.git`: any case, Windows
|
|
7
|
+
* trailing dots/spaces, NTFS `::$` streams and the `GIT~1` short name.
|
|
8
|
+
*/
|
|
9
|
+
export function hasGitDirSegment(fileName) {
|
|
10
|
+
return fileName.split(/[/\\]/).some((raw) => {
|
|
11
|
+
const segment = raw
|
|
12
|
+
.replace(IGNORABLE_CHARS, "")
|
|
13
|
+
.replace(/:.*$/, "")
|
|
14
|
+
.replace(/[. ]+$/, "")
|
|
15
|
+
.toLowerCase();
|
|
16
|
+
return segment === ".git" || /^git~\d+$/.test(segment);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** True if `path` itself is a symlink, dangling or not. */
|
|
20
|
+
export function isSymlink(path) {
|
|
21
|
+
try {
|
|
22
|
+
return lstatSync(path).isSymbolicLink();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
const code = error.code;
|
|
26
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
27
|
+
return false;
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Writes `content` to `path`, refusing if `path` is a symlink. A cloned repo
|
|
33
|
+
* can commit a symlink where xfg writes its own files.
|
|
34
|
+
*/
|
|
35
|
+
export function writeFileNoFollow(path, content) {
|
|
36
|
+
if (isSymlink(path)) {
|
|
37
|
+
throw new ValidationError(`Refusing to write '${path}': it is a symlink`);
|
|
38
|
+
}
|
|
39
|
+
// O_NOFOLLOW closes the lstat/open race; it is undefined on Windows.
|
|
40
|
+
const flag = constants.O_WRONLY |
|
|
41
|
+
constants.O_CREAT |
|
|
42
|
+
constants.O_TRUNC |
|
|
43
|
+
(constants.O_NOFOLLOW ?? 0);
|
|
44
|
+
const fd = openSync(path, flag, 0o666);
|
|
45
|
+
try {
|
|
46
|
+
writeFileSync(fd, content, "utf-8");
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
closeSync(fd);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -13,10 +13,10 @@ export const CORE_PERMANENT_ERROR_PATTERNS = [
|
|
|
13
13
|
/bad\s*credentials/i,
|
|
14
14
|
/invalid\s*(token|credentials)/i,
|
|
15
15
|
/unauthorized/i,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
/\b401\b/,
|
|
17
|
+
/\b403\b/,
|
|
18
|
+
/\b404\b/,
|
|
19
|
+
/\b422\b/,
|
|
20
20
|
/not\s*found/i,
|
|
21
21
|
/does\s*not\s*exist/i,
|
|
22
22
|
/repository\s*not\s*found/i,
|
|
@@ -61,11 +61,11 @@ const DEFAULT_TRANSIENT_ERROR_PATTERNS = [
|
|
|
61
61
|
/network\s*(error|unreachable)/i,
|
|
62
62
|
/rate\s*limit/i,
|
|
63
63
|
/too\s*many\s*requests/i,
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
64
|
+
/\b429\b/,
|
|
65
|
+
/\b500\b/,
|
|
66
|
+
/\b502\b/,
|
|
67
|
+
/\b503\b/,
|
|
68
|
+
/\b504\b/,
|
|
69
69
|
/service\s*unavailable/i,
|
|
70
70
|
/temporarily\s*unavailable/i,
|
|
71
71
|
/internal\s*server\s*error/i,
|
|
@@ -114,7 +114,6 @@ export function isPermanentError(error, patterns = DEFAULT_PERMANENT_ERROR_PATTE
|
|
|
114
114
|
}
|
|
115
115
|
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
116
116
|
const combined = `${message} ${getStderr(error)}`;
|
|
117
|
-
// Check permanent patterns first - these always stop retries
|
|
118
117
|
for (const pattern of patterns) {
|
|
119
118
|
if (pattern.test(combined)) {
|
|
120
119
|
return true;
|
|
@@ -155,7 +154,6 @@ export async function withRetry(fn, options) {
|
|
|
155
154
|
if (error instanceof Error &&
|
|
156
155
|
!isTransientError(error, options?.transientErrorPatterns) &&
|
|
157
156
|
isPermanentError(error, permanentPatterns)) {
|
|
158
|
-
// Wrap in AbortError to stop retrying immediately
|
|
159
157
|
throw new AbortError(error);
|
|
160
158
|
}
|
|
161
159
|
throw error;
|
|
@@ -163,14 +161,12 @@ export async function withRetry(fn, options) {
|
|
|
163
161
|
}, {
|
|
164
162
|
retries,
|
|
165
163
|
onFailedAttempt: async (context) => {
|
|
166
|
-
// Apply rate-limit-specific delay before the next retry
|
|
167
164
|
if (context.retriesLeft > 0 && isRateLimitError(context.error)) {
|
|
168
165
|
const retryAfterSeconds = context.error.retryAfter ??
|
|
169
166
|
RATE_LIMIT_FALLBACK_DELAY_SECONDS;
|
|
170
167
|
options?.log?.info(`Rate limited. Waiting ${retryAfterSeconds}s before retry...`);
|
|
171
168
|
await (options?._delay ?? delay)(retryAfterSeconds * 1000);
|
|
172
169
|
}
|
|
173
|
-
// Log the failure (existing behavior)
|
|
174
170
|
if (context.retriesLeft > 0) {
|
|
175
171
|
const msg = sanitizeCredentials(context.error.message) || "Unknown error";
|
|
176
172
|
options?.log?.info(`Attempt ${context.attemptNumber}/${retries + 1} failed: ${msg}. Retrying...`);
|
|
@@ -2,11 +2,13 @@ import { type RepoInfo } from "../repo/index.js";
|
|
|
2
2
|
import type { GitHubAppTokenManager } from "../vcs/index.js";
|
|
3
3
|
import type { AuthResult, IAuthOptionsBuilder } from "./types.js";
|
|
4
4
|
import type { ILogger } from "../shared/logger.js";
|
|
5
|
+
import type { IGitHubHostPolicy } from "../shared/github-host-policy.js";
|
|
5
6
|
export declare class AuthOptionsBuilder implements IAuthOptionsBuilder {
|
|
6
7
|
private readonly tokenManager;
|
|
7
8
|
private readonly log?;
|
|
8
9
|
private readonly envToken?;
|
|
9
|
-
|
|
10
|
+
private readonly hostPolicy?;
|
|
11
|
+
constructor(tokenManager: GitHubAppTokenManager | null, log?: ILogger | undefined, envToken?: string | undefined, hostPolicy?: IGitHubHostPolicy | undefined);
|
|
10
12
|
resolve(repoInfo: RepoInfo, repoName: string, token?: string): Promise<AuthResult>;
|
|
11
13
|
private buildAuthOptions;
|
|
12
14
|
}
|
|
@@ -4,10 +4,12 @@ export class AuthOptionsBuilder {
|
|
|
4
4
|
tokenManager;
|
|
5
5
|
log;
|
|
6
6
|
envToken;
|
|
7
|
-
|
|
7
|
+
hostPolicy;
|
|
8
|
+
constructor(tokenManager, log, envToken, hostPolicy) {
|
|
8
9
|
this.tokenManager = tokenManager;
|
|
9
10
|
this.log = log;
|
|
10
11
|
this.envToken = envToken;
|
|
12
|
+
this.hostPolicy = hostPolicy;
|
|
11
13
|
}
|
|
12
14
|
async resolve(repoInfo, repoName, token) {
|
|
13
15
|
if (!isGitHubRepo(repoInfo)) {
|
|
@@ -25,6 +27,7 @@ export class AuthOptionsBuilder {
|
|
|
25
27
|
context: repoName,
|
|
26
28
|
log: this.log,
|
|
27
29
|
envToken: this.envToken,
|
|
30
|
+
hostPolicy: this.hostPolicy,
|
|
28
31
|
});
|
|
29
32
|
if (resolved.skipped) {
|
|
30
33
|
return {
|
package/dist/sync/manifest.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { readFileSync,
|
|
1
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { isSymlink, writeFileNoFollow } from "../shared/path-safety.js";
|
|
3
4
|
import { toErrorMessage, isPlainObject } from "../shared/type-guards.js";
|
|
4
5
|
import { SyncError } from "../shared/errors.js";
|
|
5
6
|
export const MANIFEST_FILENAME = ".xfg.json";
|
|
@@ -81,6 +82,10 @@ export function createEmptyManifest() {
|
|
|
81
82
|
*/
|
|
82
83
|
export function loadManifest(workDir, log) {
|
|
83
84
|
const manifestPath = join(workDir, MANIFEST_FILENAME);
|
|
85
|
+
if (isSymlink(manifestPath)) {
|
|
86
|
+
log?.warn(`Ignoring manifest ${manifestPath}: it is a symlink`);
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
84
89
|
if (!existsSync(manifestPath)) {
|
|
85
90
|
return null;
|
|
86
91
|
}
|
|
@@ -129,7 +134,7 @@ export function saveManifest(workDir, manifest) {
|
|
|
129
134
|
const manifestPath = join(workDir, MANIFEST_FILENAME);
|
|
130
135
|
const content = JSON.stringify(manifest, null, 2) + "\n";
|
|
131
136
|
try {
|
|
132
|
-
|
|
137
|
+
writeFileNoFollow(manifestPath, content);
|
|
133
138
|
}
|
|
134
139
|
catch (error) {
|
|
135
140
|
throw new SyncError(`Failed to save manifest ${manifestPath}: ${toErrorMessage(error)}`, { cause: error });
|
|
@@ -14,6 +14,10 @@ function readIndex(indexPath) {
|
|
|
14
14
|
throw error;
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
+
// Not localeCompare: render.json must be byte-stable across machines and locales
|
|
18
|
+
function compareCodeUnits(a, b) {
|
|
19
|
+
return Number(a > b) - Number(a < b);
|
|
20
|
+
}
|
|
17
21
|
function resolveInside(root, path) {
|
|
18
22
|
const target = resolve(root, path);
|
|
19
23
|
const rel = relative(root, target);
|
|
@@ -48,7 +52,9 @@ export class RenderWriter {
|
|
|
48
52
|
}
|
|
49
53
|
const indexPath = resolve(root, RENDER_INDEX_FILE);
|
|
50
54
|
const index = readIndex(indexPath);
|
|
51
|
-
|
|
55
|
+
files.sort(compareCodeUnits);
|
|
56
|
+
deleted.sort(compareCodeUnits);
|
|
57
|
+
index.repos[repoName] = { files, deleted };
|
|
52
58
|
mkdirSync(root, { recursive: true });
|
|
53
59
|
writeFileSync(indexPath, JSON.stringify(index, null, 2) + "\n", {
|
|
54
60
|
mode: FILE_MODE,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RepoConfig } from "../config/index.js";
|
|
2
2
|
import type { RepoInfo } from "../repo/index.js";
|
|
3
3
|
import type { ILogger } from "../shared/logger.js";
|
|
4
|
+
import type { IGitHubHostPolicy } from "../shared/github-host-policy.js";
|
|
4
5
|
import { type GitHubAppTokenManager } from "../vcs/index.js";
|
|
5
6
|
import { type FetchFn, type IChangeDescriber } from "../ai/index.js";
|
|
6
7
|
import type { IFileWriter, IManifestManager, IRenderWriter, IBranchManager, IAuthOptionsBuilder, IRepositorySession, ICommitPushManager, IFileSyncOrchestrator, IPRMergeHandler, ISyncWorkflow, IRepositoryProcessor, GitOpsFactory, ProcessorOptions, ProcessorResult } from "./types.js";
|
|
@@ -24,6 +25,7 @@ export declare class RepositoryProcessor implements IRepositoryProcessor {
|
|
|
24
25
|
changeDescriber?: IChangeDescriber;
|
|
25
26
|
tokenManager?: GitHubAppTokenManager | null;
|
|
26
27
|
envToken?: string;
|
|
28
|
+
hostPolicy?: IGitHubHostPolicy;
|
|
27
29
|
/** Environment the AI client reads API keys from */
|
|
28
30
|
aiEnv?: Record<string, string | undefined>;
|
|
29
31
|
fetch?: FetchFn;
|
|
@@ -35,7 +35,7 @@ export class RepositoryProcessor {
|
|
|
35
35
|
const manifestManager = components?.manifestManager ?? new ManifestManager(log);
|
|
36
36
|
const branchManager = components?.branchManager ?? new BranchManager(log);
|
|
37
37
|
const authOptionsBuilder = components?.authOptionsBuilder ??
|
|
38
|
-
new AuthOptionsBuilder(tokenManager, log, components?.envToken);
|
|
38
|
+
new AuthOptionsBuilder(tokenManager, log, components?.envToken, components?.hostPolicy);
|
|
39
39
|
const repositorySession = components?.repositorySession ?? new RepositorySession(factory, log);
|
|
40
40
|
const commitPushManager = components?.commitPushManager ?? new CommitPushManager(log);
|
|
41
41
|
const prMergeHandler = components?.prMergeHandler ?? new PRMergeHandler(log);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { writeFileNoFollow } from "../shared/path-safety.js";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { assertAzureDevOpsRepo, } from "../repo/index.js";
|
|
4
5
|
import { SyncError } from "../shared/errors.js";
|
|
@@ -189,7 +190,7 @@ export class AdoPRStrategy extends BasePRStrategy {
|
|
|
189
190
|
const orgUrl = this.getOrgUrl(azureRepoInfo);
|
|
190
191
|
const descFile = join(workDir, this.bodyFilePath);
|
|
191
192
|
try {
|
|
192
|
-
|
|
193
|
+
writeFileNoFollow(descFile, body);
|
|
193
194
|
}
|
|
194
195
|
catch (err) {
|
|
195
196
|
throw new SyncError(`Failed to write PR description to ${descFile}: ${toErrorMessage(err)}`, { cause: err });
|
|
@@ -2,6 +2,7 @@ import { type RepoInfo } from "../repo/index.js";
|
|
|
2
2
|
import type { ICommitStrategy } from "./types.js";
|
|
3
3
|
import { GitHubAppTokenManager } from "./github-app-token-manager.js";
|
|
4
4
|
import type { ICommandExecutor } from "../shared/command-executor.js";
|
|
5
|
+
import { type IGitHubHostPolicy } from "../shared/github-host-policy.js";
|
|
5
6
|
interface GitHubAppCredentials {
|
|
6
7
|
clientId: string;
|
|
7
8
|
privateKey: string;
|
|
@@ -9,8 +10,8 @@ interface GitHubAppCredentials {
|
|
|
9
10
|
/**
|
|
10
11
|
* Creates a GitHubAppTokenManager from credentials, or null if not provided.
|
|
11
12
|
*/
|
|
12
|
-
export declare function createTokenManager(credentials?: GitHubAppCredentials): GitHubAppTokenManager | null;
|
|
13
|
-
export declare function createTokenManagerFromEnv(env: NodeJS.ProcessEnv): GitHubAppTokenManager | null;
|
|
13
|
+
export declare function createTokenManager(credentials?: GitHubAppCredentials, hostPolicy?: IGitHubHostPolicy): GitHubAppTokenManager | null;
|
|
14
|
+
export declare function createTokenManagerFromEnv(env: NodeJS.ProcessEnv, hostPolicy?: IGitHubHostPolicy): GitHubAppTokenManager | null;
|
|
14
15
|
/**
|
|
15
16
|
* Returns FileModeFixupCommitStrategy (decorating GraphQLCommitStrategy) for
|
|
16
17
|
* GitHub repos with App credentials (verified commits + executable file mode
|
|
@@ -3,19 +3,20 @@ import { GitCommitStrategy } from "./git-commit-strategy.js";
|
|
|
3
3
|
import { GraphQLCommitStrategy } from "./graphql-commit-strategy.js";
|
|
4
4
|
import { FileModeFixupCommitStrategy } from "./file-mode-fixup-commit-strategy.js";
|
|
5
5
|
import { GitHubAppTokenManager } from "./github-app-token-manager.js";
|
|
6
|
+
import { createGitHubHostPolicyFromEnv, } from "../shared/github-host-policy.js";
|
|
6
7
|
/**
|
|
7
8
|
* Creates a GitHubAppTokenManager from credentials, or null if not provided.
|
|
8
9
|
*/
|
|
9
|
-
export function createTokenManager(credentials) {
|
|
10
|
+
export function createTokenManager(credentials, hostPolicy) {
|
|
10
11
|
if (!credentials) {
|
|
11
12
|
return null;
|
|
12
13
|
}
|
|
13
|
-
return new GitHubAppTokenManager(credentials.clientId, credentials.privateKey);
|
|
14
|
+
return new GitHubAppTokenManager(credentials.clientId, credentials.privateKey, hostPolicy);
|
|
14
15
|
}
|
|
15
|
-
export function createTokenManagerFromEnv(env) {
|
|
16
|
+
export function createTokenManagerFromEnv(env, hostPolicy = createGitHubHostPolicyFromEnv(env)) {
|
|
16
17
|
const clientId = env.XFG_GITHUB_CLIENT_ID;
|
|
17
18
|
const privateKey = env.XFG_GITHUB_APP_PRIVATE_KEY;
|
|
18
|
-
return createTokenManager(clientId && privateKey ? { clientId, privateKey } : undefined);
|
|
19
|
+
return createTokenManager(clientId && privateKey ? { clientId, privateKey } : undefined, hostPolicy);
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* Returns FileModeFixupCommitStrategy (decorating GraphQLCommitStrategy) for
|
package/dist/vcs/git-ops.d.ts
CHANGED
|
@@ -16,11 +16,11 @@ export declare class GitOps implements ILocalGitOps {
|
|
|
16
16
|
constructor(options: GitOpsOptions);
|
|
17
17
|
private exec;
|
|
18
18
|
/**
|
|
19
|
-
*
|
|
20
|
-
* @returns The
|
|
21
|
-
* @throws ValidationError if path traversal is detected
|
|
19
|
+
* Rejects traversal, `.git` segments and symlinks: a cloned repo can commit a symlink to anywhere.
|
|
20
|
+
* @returns The absolute file path
|
|
22
21
|
*/
|
|
23
22
|
private validatePath;
|
|
23
|
+
private assertNoSymlinks;
|
|
24
24
|
cleanWorkspace(): void;
|
|
25
25
|
/**
|
|
26
26
|
* Create a new branch from the current HEAD.
|
package/dist/vcs/git-ops.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { rmSync, existsSync, statSync, mkdirSync,
|
|
2
|
-
import { join, resolve, relative, isAbsolute, dirname } from "node:path";
|
|
1
|
+
import { rmSync, existsSync, statSync, mkdirSync, readFileSync, chmodSync, lstatSync, } from "node:fs";
|
|
2
|
+
import { join, resolve, relative, isAbsolute, dirname, sep } from "node:path";
|
|
3
|
+
import { hasGitDirSegment, writeFileNoFollow } from "../shared/path-safety.js";
|
|
3
4
|
import { toErrorMessage } from "../shared/type-guards.js";
|
|
4
5
|
import { ValidationError, SyncError } from "../shared/errors.js";
|
|
5
6
|
export class GitOps {
|
|
@@ -17,9 +18,8 @@ export class GitOps {
|
|
|
17
18
|
return this.executor.exec(executable, args, cwd ?? this.workDir);
|
|
18
19
|
}
|
|
19
20
|
/**
|
|
20
|
-
*
|
|
21
|
-
* @returns The
|
|
22
|
-
* @throws ValidationError if path traversal is detected
|
|
21
|
+
* Rejects traversal, `.git` segments and symlinks: a cloned repo can commit a symlink to anywhere.
|
|
22
|
+
* @returns The absolute file path
|
|
23
23
|
*/
|
|
24
24
|
validatePath(fileName) {
|
|
25
25
|
const filePath = join(this.workDir, fileName);
|
|
@@ -29,8 +29,31 @@ export class GitOps {
|
|
|
29
29
|
if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
|
|
30
30
|
throw new ValidationError(`Path traversal detected: ${fileName}`);
|
|
31
31
|
}
|
|
32
|
+
if (hasGitDirSegment(relativePath)) {
|
|
33
|
+
throw new ValidationError(`Refusing to access '${fileName}': path is inside a '.git' directory`);
|
|
34
|
+
}
|
|
35
|
+
this.assertNoSymlinks(resolvedWorkDir, relativePath, fileName);
|
|
32
36
|
return filePath;
|
|
33
37
|
}
|
|
38
|
+
assertNoSymlinks(root, relativePath, fileName) {
|
|
39
|
+
let current = root;
|
|
40
|
+
for (const segment of relativePath.split(sep).filter(Boolean)) {
|
|
41
|
+
current = join(current, segment);
|
|
42
|
+
let stats;
|
|
43
|
+
try {
|
|
44
|
+
stats = lstatSync(current);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
const code = error.code;
|
|
48
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
49
|
+
return;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
if (stats.isSymbolicLink()) {
|
|
53
|
+
throw new ValidationError(`Refusing to access '${fileName}': '${relative(root, current)}' is a symlink`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
34
57
|
cleanWorkspace() {
|
|
35
58
|
try {
|
|
36
59
|
if (existsSync(this.workDir)) {
|
|
@@ -64,7 +87,7 @@ export class GitOps {
|
|
|
64
87
|
try {
|
|
65
88
|
mkdirSync(dirname(filePath), { recursive: true });
|
|
66
89
|
const normalized = content.endsWith("\n") ? content : content + "\n";
|
|
67
|
-
|
|
90
|
+
writeFileNoFollow(filePath, normalized);
|
|
68
91
|
}
|
|
69
92
|
catch (error) {
|
|
70
93
|
throw new SyncError(`Failed to write file '${fileName}': ${toErrorMessage(error)}`, { cause: error });
|
|
@@ -155,10 +178,8 @@ export class GitOps {
|
|
|
155
178
|
*/
|
|
156
179
|
wouldChange(fileName, content) {
|
|
157
180
|
const filePath = this.validatePath(fileName);
|
|
158
|
-
// Normalize trailing newline - ensure exactly one
|
|
159
181
|
const newContent = content.endsWith("\n") ? content : content + "\n";
|
|
160
182
|
if (!existsSync(filePath)) {
|
|
161
|
-
// File doesn't exist, so writing it would be a change
|
|
162
183
|
return true;
|
|
163
184
|
}
|
|
164
185
|
try {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { GitHubRepoInfo } from "../repo/index.js";
|
|
2
|
+
import { type IGitHubHostPolicy } from "../shared/github-host-policy.js";
|
|
2
3
|
/**
|
|
3
4
|
* Manages GitHub App authentication tokens for multiple organizations.
|
|
4
5
|
* Handles JWT generation, installation discovery, and token caching.
|
|
@@ -12,7 +13,9 @@ export declare class GitHubAppTokenManager {
|
|
|
12
13
|
private discoveredHosts;
|
|
13
14
|
/** Map of "apiHost:owner" -> cached token */
|
|
14
15
|
private tokenCache;
|
|
15
|
-
|
|
16
|
+
private readonly hostPolicy;
|
|
17
|
+
constructor(clientId: string, privateKey: string, hostPolicy?: IGitHubHostPolicy);
|
|
18
|
+
private assertApiHostAllowed;
|
|
16
19
|
/**
|
|
17
20
|
* Generates a JWT for GitHub App authentication.
|
|
18
21
|
* The JWT is signed with RS256 and valid for 10 minutes.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createSign } from "node:crypto";
|
|
2
2
|
import { withRetry } from "../shared/retry-utils.js";
|
|
3
3
|
import { SyncError } from "../shared/errors.js";
|
|
4
|
+
import { GitHubHostNotAllowedError, GitHubHostPolicy, } from "../shared/github-host-policy.js";
|
|
4
5
|
/** Duration to cache tokens (45 minutes in milliseconds) */
|
|
5
6
|
const TOKEN_CACHE_DURATION_MS = 45 * 60 * 1000;
|
|
6
7
|
async function assertOkResponse(res, context) {
|
|
@@ -22,9 +23,16 @@ export class GitHubAppTokenManager {
|
|
|
22
23
|
discoveredHosts = new Set();
|
|
23
24
|
/** Map of "apiHost:owner" -> cached token */
|
|
24
25
|
tokenCache = new Map();
|
|
25
|
-
|
|
26
|
+
hostPolicy;
|
|
27
|
+
constructor(clientId, privateKey, hostPolicy = new GitHubHostPolicy()) {
|
|
26
28
|
this.clientId = clientId;
|
|
27
29
|
this.privateKey = privateKey;
|
|
30
|
+
this.hostPolicy = hostPolicy;
|
|
31
|
+
}
|
|
32
|
+
assertApiHostAllowed(apiHost) {
|
|
33
|
+
if (!this.hostPolicy.isAllowedApiHost(apiHost)) {
|
|
34
|
+
throw new GitHubHostNotAllowedError(apiHost);
|
|
35
|
+
}
|
|
28
36
|
}
|
|
29
37
|
/**
|
|
30
38
|
* Generates a JWT for GitHub App authentication.
|
|
@@ -55,9 +63,16 @@ export class GitHubAppTokenManager {
|
|
|
55
63
|
* Stores installations in an internal map for later lookup.
|
|
56
64
|
*/
|
|
57
65
|
async discoverInstallations(apiHost) {
|
|
66
|
+
this.assertApiHostAllowed(apiHost);
|
|
58
67
|
const jwt = this.generateJWT();
|
|
59
|
-
|
|
68
|
+
const firstUrl = `https://${apiHost}/app/installations?per_page=100`;
|
|
69
|
+
const origin = new URL(firstUrl).origin;
|
|
70
|
+
let url = firstUrl;
|
|
60
71
|
while (url) {
|
|
72
|
+
const pageOrigin = new URL(url).origin;
|
|
73
|
+
if (pageOrigin !== origin) {
|
|
74
|
+
throw new SyncError(`GitHub App installations: refusing to follow a pagination link to ${pageOrigin}`);
|
|
75
|
+
}
|
|
61
76
|
const pageUrl = url;
|
|
62
77
|
const response = await withRetry(async () => {
|
|
63
78
|
const res = await fetch(pageUrl, {
|
|
@@ -91,6 +106,7 @@ export class GitHubAppTokenManager {
|
|
|
91
106
|
* Tokens are cached for 45 minutes.
|
|
92
107
|
*/
|
|
93
108
|
async getTokenForOwner(apiHost, owner) {
|
|
109
|
+
this.assertApiHostAllowed(apiHost);
|
|
94
110
|
const installationId = this.getInstallationId(apiHost, owner);
|
|
95
111
|
if (installationId === undefined) {
|
|
96
112
|
return null;
|
|
@@ -130,6 +146,9 @@ export class GitHubAppTokenManager {
|
|
|
130
146
|
* Derives the API host from the repository host.
|
|
131
147
|
*/
|
|
132
148
|
async getTokenForRepo(repoInfo) {
|
|
149
|
+
if (!this.hostPolicy.isAllowed(repoInfo.host)) {
|
|
150
|
+
throw new GitHubHostNotAllowedError(repoInfo.host);
|
|
151
|
+
}
|
|
133
152
|
const apiHost = deriveApiHost(repoInfo.host);
|
|
134
153
|
// Auto-discover if needed
|
|
135
154
|
if (!this.discoveredHosts.has(apiHost)) {
|
|
@@ -172,8 +191,9 @@ function base64UrlEncode(data) {
|
|
|
172
191
|
* - ghe.example.com -> ghe.example.com/api/v3
|
|
173
192
|
*/
|
|
174
193
|
function deriveApiHost(host) {
|
|
175
|
-
|
|
194
|
+
const lower = host.toLowerCase();
|
|
195
|
+
if (lower === "github.com") {
|
|
176
196
|
return "api.github.com";
|
|
177
197
|
}
|
|
178
|
-
return `${
|
|
198
|
+
return `${lower}/api/v3`;
|
|
179
199
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { writeFileNoFollow } from "../shared/path-safety.js";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { escapeRegExp } from "../shared/regex-utils.js";
|
|
4
5
|
import { assertGitHubRepo } from "../repo/index.js";
|
|
@@ -105,7 +106,7 @@ export class GitHubPRStrategy extends BasePRStrategy {
|
|
|
105
106
|
assertGitHubRepo(repoInfo, "GitHub PR strategy");
|
|
106
107
|
const bodyFile = join(workDir, this.bodyFilePath);
|
|
107
108
|
try {
|
|
108
|
-
|
|
109
|
+
writeFileNoFollow(bodyFile, body);
|
|
109
110
|
}
|
|
110
111
|
catch (err) {
|
|
111
112
|
throw new SyncError(`Failed to write PR description to ${bodyFile}: ${toErrorMessage(err)}`, { cause: err });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aspruyt/xfg",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.1.0",
|
|
4
4
|
"description": "Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab — declaratively, from a single YAML config",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -38,7 +38,8 @@
|
|
|
38
38
|
"docs:generate": "tsx scripts/docs/generate-docs.ts",
|
|
39
39
|
"docs:check": "tsx scripts/docs/generate-docs.ts --check",
|
|
40
40
|
"test": "node --import tsx scripts/run-tests.js",
|
|
41
|
-
"test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='test/integration/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/settings/collaborators/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
|
|
41
|
+
"test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='test/integration/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/settings/collaborators/types.ts' --exclude='src/settings/environments/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
|
|
42
|
+
"test:integration:ci": "node --import tsx --test",
|
|
42
43
|
"test:integration:github": "npm run build && node --import tsx --test test/integration/github.test.ts",
|
|
43
44
|
"test:integration:ado": "npm run build && node --import tsx --test test/integration/ado.test.ts",
|
|
44
45
|
"test:integration:gitlab": "npm run build && node --import tsx --test test/integration/gitlab.test.ts",
|