@aspruyt/xfg 7.5.1 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/ai/client-factory.js +15 -3
  2. package/dist/cli/repo-sync-runner.d.ts +2 -0
  3. package/dist/cli/repo-sync-runner.js +18 -9
  4. package/dist/cli/secrets-command.js +4 -2
  5. package/dist/cli/sync-command.js +5 -1
  6. package/dist/config/env.js +8 -0
  7. package/dist/config/file-reference-resolver.js +16 -13
  8. package/dist/config/validator.js +8 -0
  9. package/dist/config/validators/ai-validator.js +2 -0
  10. package/dist/config/validators/file-validator.js +4 -1
  11. package/dist/config/validators/group-validator.js +3 -0
  12. package/dist/repo/detector.js +15 -24
  13. package/dist/shared/credential-env.d.ts +10 -0
  14. package/dist/shared/credential-env.js +50 -0
  15. package/dist/shared/gh-token-utils.d.ts +7 -1
  16. package/dist/shared/gh-token-utils.js +14 -1
  17. package/dist/shared/github-host-policy.d.ts +22 -0
  18. package/dist/shared/github-host-policy.js +61 -0
  19. package/dist/shared/path-safety.d.ts +12 -0
  20. package/dist/shared/path-safety.js +51 -0
  21. package/dist/shared/retry-utils.js +9 -13
  22. package/dist/sync/auth-options-builder.d.ts +3 -1
  23. package/dist/sync/auth-options-builder.js +4 -1
  24. package/dist/sync/manifest.js +7 -2
  25. package/dist/sync/render-writer.js +7 -1
  26. package/dist/sync/repository-processor.d.ts +2 -0
  27. package/dist/sync/repository-processor.js +1 -1
  28. package/dist/vcs/ado-pr-strategy.js +3 -2
  29. package/dist/vcs/commit-strategy-selector.d.ts +3 -2
  30. package/dist/vcs/commit-strategy-selector.js +5 -4
  31. package/dist/vcs/git-ops.d.ts +3 -3
  32. package/dist/vcs/git-ops.js +29 -8
  33. package/dist/vcs/github-app-token-manager.d.ts +4 -1
  34. package/dist/vcs/github-app-token-manager.js +24 -4
  35. package/dist/vcs/github-pr-strategy.js +3 -2
  36. package/package.json +3 -2
@@ -1,9 +1,22 @@
1
1
  import { ValidationError } from "../shared/errors.js";
2
+ import { assertAiKeyEnvAllowed, defaultAiKeyEnv, isDefaultAiBaseUrl, } from "../shared/credential-env.js";
2
3
  import { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
3
4
  import { DEFAULT_OPENAI_BASE_URL, OpenAICompatibleClient, } from "./openai-compatible-client.js";
5
+ /** The default key env only applies to the provider's own API. */
6
+ function keyEnvFor(options) {
7
+ if (options.apiKeyEnv !== undefined)
8
+ return options.apiKeyEnv;
9
+ return isDefaultAiBaseUrl(options.provider, options.baseUrl)
10
+ ? defaultAiKeyEnv(options.provider)
11
+ : undefined;
12
+ }
4
13
  export function createAiClient(options, env, fetch) {
14
+ assertAiKeyEnvAllowed(options.provider, options.apiKeyEnv, options.baseUrl);
15
+ const keyEnv = keyEnvFor(options);
5
16
  if (options.provider === "anthropic") {
6
- const keyEnv = options.apiKeyEnv ?? "ANTHROPIC_API_KEY";
17
+ if (keyEnv === undefined) {
18
+ throw new ValidationError("prOptions.ai.apiKeyEnv is required for provider 'anthropic' with a custom baseUrl");
19
+ }
7
20
  const apiKey = env[keyEnv];
8
21
  if (!apiKey) {
9
22
  throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'anthropic')`);
@@ -18,8 +31,7 @@ export function createAiClient(options, env, fetch) {
18
31
  if (!options.model) {
19
32
  throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
20
33
  }
21
- const keyEnv = options.apiKeyEnv ?? "OPENAI_API_KEY";
22
- const apiKey = env[keyEnv];
34
+ const apiKey = keyEnv === undefined ? undefined : env[keyEnv];
23
35
  // A custom baseUrl (Ollama, local LiteLLM) often needs no key at all.
24
36
  if (!apiKey && !options.baseUrl) {
25
37
  throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'openai' without baseUrl)`);
@@ -3,6 +3,7 @@ import type { createTokenManager } from "../vcs/index.js";
3
3
  import type { IRepositoryProcessor } from "../sync/index.js";
4
4
  import type { ProcessExecutor } from "../shared/command-executor.js";
5
5
  import type { Logger } from "../shared/logger.js";
6
+ import type { IGitHubHostPolicy } from "../shared/github-host-policy.js";
6
7
  import { type IRepoLifecycleManager } from "../lifecycle/index.js";
7
8
  import type { SyncOptions, SyncResultEntry, SettingsProcessorFactories } from "./types.js";
8
9
  import type { ResultsCollector } from "./results-collector.js";
@@ -14,6 +15,7 @@ export interface RepoIterationContext {
14
15
  processor: IRepositoryProcessor;
15
16
  lifecycleManager: IRepoLifecycleManager;
16
17
  tokenManager: ReturnType<typeof createTokenManager>;
18
+ hostPolicy?: IGitHubHostPolicy;
17
19
  reportResults: SyncResultEntry[];
18
20
  lifecycleReportInputs: LifecycleAction[];
19
21
  settingsCollector: ResultsCollector;
@@ -128,15 +128,24 @@ export async function runSingleRepo(repoConfig, index, ctx) {
128
128
  }
129
129
  const repoName = getRepoDisplayName(repoInfo);
130
130
  const workDir = resolve(join(options.workDir ?? "./tmp", generateWorkspaceName(index)));
131
- const repoToken = isGitHubRepo(repoInfo)
132
- ? (await resolveGitHubToken({
133
- repoInfo: repoInfo,
134
- tokenManager: ctx.tokenManager,
135
- context: repoName,
136
- log: logger,
137
- envToken: process.env.GH_TOKEN,
138
- })).token
139
- : undefined;
131
+ let repoToken;
132
+ try {
133
+ repoToken = isGitHubRepo(repoInfo)
134
+ ? (await resolveGitHubToken({
135
+ repoInfo: repoInfo,
136
+ tokenManager: ctx.tokenManager,
137
+ context: repoName,
138
+ log: logger,
139
+ envToken: process.env.GH_TOKEN,
140
+ hostPolicy: ctx.hostPolicy,
141
+ })).token
142
+ : undefined;
143
+ }
144
+ catch (error) {
145
+ logger.error(repoNumber, repoName, toErrorMessage(error));
146
+ pushFailure(ctx.reportResults, repoName, error);
147
+ return;
148
+ }
140
149
  const repo = {
141
150
  repoConfig: effectiveRepoConfig,
142
151
  repoInfo,
@@ -4,6 +4,7 @@ import { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "../se
4
4
  import { EnvResolver } from "../shared/env-resolver.js";
5
5
  import { ProcessExecutor } from "../shared/command-executor.js";
6
6
  import { createTokenManagerFromEnv } from "../vcs/index.js";
7
+ import { createGitHubHostPolicyFromEnv } from "../shared/github-host-policy.js";
7
8
  import { GitHubTokenProvider, } from "../shared/gh-token-utils.js";
8
9
  import { parseGitUrl, getRepoDisplayName } from "../repo/index.js";
9
10
  import { Logger } from "../shared/logger.js";
@@ -44,10 +45,11 @@ export async function runSecretsSync(options, deps = {}) {
44
45
  validateSecretsConfig(rawConfig);
45
46
  const config = normalizeConfig(rawConfig, process.env);
46
47
  validateNormalizedConfig(config);
48
+ const hostPolicy = createGitHubHostPolicyFromEnv(process.env);
47
49
  const tokenManager = deps.tokenManager !== undefined
48
50
  ? deps.tokenManager
49
- : createTokenManagerFromEnv(process.env);
50
- const tokenProvider = new GitHubTokenProvider(tokenManager, process.env.GH_TOKEN || process.env.GITHUB_TOKEN, logger);
51
+ : createTokenManagerFromEnv(process.env, hostPolicy);
52
+ const tokenProvider = new GitHubTokenProvider(tokenManager, process.env.GH_TOKEN || process.env.GITHUB_TOKEN, logger, hostPolicy);
51
53
  const processorFactory = deps.processorFactory ?? createDefaultProcessor;
52
54
  const processor = processorFactory(cwd, retries ?? 3, tokenProvider);
53
55
  let hasErrors = false;
@@ -4,6 +4,7 @@ import { loadRawConfig, normalizeConfig, validateForSync, validateNormalizedConf
4
4
  import { ValidationError, SyncError } from "../shared/errors.js";
5
5
  import { validateBranchName } from "./branch-utils.js";
6
6
  import { createTokenManagerFromEnv } from "../vcs/index.js";
7
+ import { createGitHubHostPolicyFromEnv } from "../shared/github-host-policy.js";
7
8
  import { RepositoryProcessor } from "../sync/index.js";
8
9
  import { ProcessExecutor } from "../shared/command-executor.js";
9
10
  import { Logger } from "../shared/logger.js";
@@ -97,12 +98,14 @@ export async function runSync(options, deps = {}) {
97
98
  logger.log(`Found ${config.repos.length} repositories to process`);
98
99
  logger.log(`Target files: ${formatFileNames(fileNames)}`);
99
100
  logger.log(`Branch: ${branchName}\n`);
100
- const tokenManager = createTokenManagerFromEnv(process.env);
101
+ const hostPolicy = createGitHubHostPolicyFromEnv(process.env);
102
+ const tokenManager = createTokenManagerFromEnv(process.env, hostPolicy);
101
103
  const processor = deps.processorFactory
102
104
  ? deps.processorFactory()
103
105
  : new RepositoryProcessor(undefined, logger, {
104
106
  tokenManager,
105
107
  envToken: process.env.GH_TOKEN,
108
+ hostPolicy,
106
109
  aiEnv: process.env,
107
110
  });
108
111
  const ctx = {
@@ -113,6 +116,7 @@ export async function runSync(options, deps = {}) {
113
116
  lifecycleManager: lifecycleManager ??
114
117
  new RepoLifecycleManager(undefined, executor, options.retries, process.cwd(), logger),
115
118
  tokenManager,
119
+ hostPolicy,
116
120
  reportResults: [],
117
121
  lifecycleReportInputs: [],
118
122
  settingsCollector: new ResultsCollector(),
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { interpolateString, interpolateValue, } from "../shared/interpolation-engine.js";
7
7
  import { ValidationError } from "../shared/errors.js";
8
+ import { isCredentialEnvName } from "../shared/credential-env.js";
8
9
  /**
9
10
  * Regex to match environment variable placeholders.
10
11
  * Captures:
@@ -26,9 +27,16 @@ const ENV_VAR_REGEX = /\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::([?-])([^}]*))?\}/g;
26
27
  * Note: Does NOT match $${xfg:...} patterns - those are handled by xfg templating.
27
28
  */
28
29
  const ESCAPED_VAR_REGEX = /\$\$\{((?!xfg:)[^}]+)\}/g;
30
+ function assertNotCredential(varName) {
31
+ if (isCredentialEnvName(varName)) {
32
+ throw new ValidationError(`Refusing to interpolate \${${varName}}: it is a credential xfg uses for authentication. ` +
33
+ `Use a separate environment variable, or $\${${varName}} for a literal.`);
34
+ }
35
+ }
29
36
  function buildEnvConfig(options) {
30
37
  const envSource = options.env;
31
38
  function resolveEnvVar(match, varName, modifier, defaultOrMsg) {
39
+ assertNotCredential(varName);
32
40
  // Resolution follows bash parameter expansion semantics:
33
41
  // ${VAR} → value or error, ${VAR:-fallback} → value or fallback,
34
42
  // ${VAR:?msg} → value or throw with msg.
@@ -1,4 +1,4 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { resolve, isAbsolute, normalize, extname, relative } from "node:path";
3
3
  import JSON5 from "json5";
4
4
  import { parse as parseYaml } from "yaml";
@@ -21,23 +21,27 @@ export function resolveFileReference(reference, configDir) {
21
21
  if (relativePath.length === 0) {
22
22
  throw new ValidationError(`Invalid file reference "${reference}": path is empty`);
23
23
  }
24
- // Security: block absolute paths
25
24
  if (isAbsolute(relativePath)) {
26
25
  throw new ValidationError(`File reference "${reference}" uses absolute path. Use relative paths only.`);
27
26
  }
28
27
  const resolvedPath = resolve(configDir, relativePath);
29
28
  const normalizedResolved = normalize(resolvedPath);
30
29
  const normalizedConfigDir = normalize(configDir);
31
- // Security: ensure path stays within config directory tree
32
- // Fix for issue #89: Use path.relative() instead of hardcoded "/" separator
33
- // The old approach (!path.startsWith(configDir + "/")) fails on Windows
34
- // where normalize() returns paths with backslash separators.
35
- const pathFromConfig = relative(normalizedConfigDir, normalizedResolved);
36
- if (pathFromConfig.startsWith("..") || isAbsolute(pathFromConfig)) {
37
- throw new ValidationError(`File reference "${reference}" escapes config directory. ` +
38
- `References must be within "${configDir}".`);
39
- }
40
- // Load file
30
+ const escapes = (from, to) => {
31
+ const rel = relative(from, to);
32
+ return rel.startsWith("..") || isAbsolute(rel);
33
+ };
34
+ const escapeError = () => new ValidationError(`File reference "${reference}" escapes config directory. ` +
35
+ `References must be within "${configDir}".`);
36
+ if (escapes(normalizedConfigDir, normalizedResolved)) {
37
+ throw escapeError();
38
+ }
39
+ // A committed symlink can point anywhere, e.g. /proc/self/environ.
40
+ if (existsSync(resolvedPath)) {
41
+ if (escapes(realpathSync(configDir), realpathSync(resolvedPath))) {
42
+ throw escapeError();
43
+ }
44
+ }
41
45
  let content;
42
46
  try {
43
47
  content = readFileSync(resolvedPath, "utf-8");
@@ -46,7 +50,6 @@ export function resolveFileReference(reference, configDir) {
46
50
  const msg = toErrorMessage(error);
47
51
  throw new ValidationError(`Failed to load file reference "${reference}": ${msg}`, { cause: error });
48
52
  }
49
- // Parse based on extension
50
53
  const ext = extname(relativePath).toLowerCase();
51
54
  if (ext === ".json") {
52
55
  return parseWithContext(() => JSON.parse(content), `Invalid JSON in "${reference}"`);
@@ -1,6 +1,8 @@
1
1
  import { validateFileName } from "./validators/file-validator.js";
2
2
  import { isPlainObject } from "../shared/type-guards.js";
3
3
  import { ValidationError } from "../shared/errors.js";
4
+ import { isValidHostname } from "../shared/github-host-policy.js";
5
+ import { isCredentialEnvName } from "../shared/credential-env.js";
4
6
  import { validateBranchName } from "../shared/branch-validation.js";
5
7
  import { validateAiOption } from "./validators/ai-validator.js";
6
8
  import { validateFileConfigFields, validateSettings, } from "./validators/shared.js";
@@ -91,6 +93,9 @@ function validateGithubHosts(config) {
91
93
  if (host.includes("/")) {
92
94
  throw new ValidationError(`githubHosts entries must be hostnames only, not paths. Got: ${host}`);
93
95
  }
96
+ if (!isValidHostname(host)) {
97
+ throw new ValidationError(`githubHosts entries must be hostnames (no userinfo, port, whitespace or trailing dot). Got: ${host}`);
98
+ }
94
99
  }
95
100
  }
96
101
  function validatePrOptions(config) {
@@ -320,6 +325,9 @@ function validateSecretEntry(name, config) {
320
325
  if (!config.env || typeof config.env !== "string") {
321
326
  throw new ValidationError(`Secret '${name}' requires an 'env' field (string) specifying the environment variable source.`);
322
327
  }
328
+ if (isCredentialEnvName(config.env)) {
329
+ throw new ValidationError(`Secret '${name}' cannot use '${config.env}' as its source: it is a credential xfg uses for authentication.`);
330
+ }
323
331
  }
324
332
  function validateSecretsLayer(secrets) {
325
333
  const { deleteOrphaned, inherit } = secrets;
@@ -1,5 +1,6 @@
1
1
  import { isPlainObject } from "../../shared/type-guards.js";
2
2
  import { ValidationError } from "../../shared/errors.js";
3
+ import { assertAiKeyEnvAllowed } from "../../shared/credential-env.js";
3
4
  const VALID_PROVIDERS = ["anthropic", "openai"];
4
5
  const STRING_FIELDS = ["model", "baseUrl", "apiKeyEnv", "prompt"];
5
6
  const KNOWN_KEYS = new Set([
@@ -28,6 +29,7 @@ export function validateAiOption(ai) {
28
29
  throw new ValidationError(`prOptions.ai.${field} must be a non-empty string`);
29
30
  }
30
31
  }
32
+ assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl);
31
33
  if (provider === "openai" && ai.model === undefined) {
32
34
  throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
33
35
  }
@@ -2,6 +2,7 @@ import { extname, isAbsolute } from "node:path";
2
2
  import { isTextContent } from "../merge.js";
3
3
  import { ValidationError } from "../../shared/errors.js";
4
4
  import { isPlainObject } from "../../shared/type-guards.js";
5
+ import { hasGitDirSegment } from "../../shared/path-safety.js";
5
6
  export { isTextContent };
6
7
  export { isPlainObject as isObjectContent };
7
8
  export function validValues(values) {
@@ -27,7 +28,6 @@ export function validateFileName(fileName) {
27
28
  if (!fileName || typeof fileName !== "string") {
28
29
  throw new ValidationError("File name must be a non-empty string");
29
30
  }
30
- // Validate fileName doesn't allow path traversal
31
31
  if (fileName.includes("..") || isAbsolute(fileName)) {
32
32
  throw new ValidationError(`Invalid fileName '${fileName}': must be a relative path without '..' components`);
33
33
  }
@@ -35,5 +35,8 @@ export function validateFileName(fileName) {
35
35
  if (/[\n\r\0]/.test(fileName)) {
36
36
  throw new ValidationError(`Invalid fileName '${fileName}': cannot contain newlines or null bytes`);
37
37
  }
38
+ if (hasGitDirSegment(fileName)) {
39
+ throw new ValidationError(`Invalid fileName '${fileName}': cannot write inside a '.git' directory`);
40
+ }
38
41
  }
39
42
  export { VALID_STRATEGIES };
@@ -3,6 +3,7 @@ import { isPlainObject } from "../../shared/type-guards.js";
3
3
  import { ValidationError } from "../../shared/errors.js";
4
4
  import { validateBranchName } from "../../shared/branch-validation.js";
5
5
  import { validateAiOption } from "./ai-validator.js";
6
+ import { validateFileName } from "./file-validator.js";
6
7
  import { validateFileConfigFields, validateSettings, buildRootSettingsContext, } from "./shared.js";
7
8
  function validateGroupExtends(groupName, extends_, groupNames) {
8
9
  if (typeof extends_ === "string") {
@@ -94,6 +95,7 @@ export function validateGroups(config) {
94
95
  for (const [fileName, fileConfig] of Object.entries(group.files)) {
95
96
  if (fileName === "inherit")
96
97
  continue;
98
+ validateFileName(fileName);
97
99
  if (fileConfig === false)
98
100
  continue;
99
101
  if (fileConfig === undefined)
@@ -159,6 +161,7 @@ export function validateConditionalGroups(config) {
159
161
  for (const [fileName, fileConfig] of Object.entries(entry.files)) {
160
162
  if (fileName === "inherit")
161
163
  continue;
164
+ validateFileName(fileName);
162
165
  if (fileConfig === false)
163
166
  continue;
164
167
  if (fileConfig === undefined)
@@ -87,32 +87,23 @@ export function parseGitUrl(gitUrl, context) {
87
87
  const host = extractHostFromUrl(gitUrl) ?? "github.com";
88
88
  return parseGitHubUrl(gitUrl, host);
89
89
  }
90
+ // gh reads a dotted first segment of OWNER/REPO as a host, so both are strict.
91
+ const GITHUB_OWNER = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
92
+ const GITHUB_REPO = /^[A-Za-z0-9._-]+$/;
90
93
  function parseGitHubUrl(gitUrl, host) {
91
- // Handle SSH format: git@hostname:owner/repo.git
92
94
  // Use (.+?) with end anchor to handle repo names with dots (e.g., my.repo.git)
93
- const sshMatch = gitUrl.match(/^git@[^:]+:([^/]+)\/(.+?)(?:\.git)?$/);
94
- if (sshMatch) {
95
- return {
96
- type: "github",
97
- gitUrl,
98
- owner: sshMatch[1],
99
- repo: sshMatch[2],
100
- host,
101
- };
102
- }
103
- // Handle HTTPS format: https://hostname/owner/repo.git
104
- // Use (.+?) with end anchor to handle repo names with dots
105
- const httpsMatch = gitUrl.match(/^https?:\/\/[^/]+\/([^/]+)\/(.+?)(?:\.git)?$/);
106
- if (httpsMatch) {
107
- return {
108
- type: "github",
109
- gitUrl,
110
- owner: httpsMatch[1],
111
- repo: httpsMatch[2],
112
- host,
113
- };
114
- }
115
- throw new ValidationError(`Unable to parse GitHub URL: ${gitUrl}`);
95
+ const match = gitUrl.match(/^git@[^:]+:([^/]+)\/(.+?)(?:\.git)?$/) ??
96
+ gitUrl.match(/^https?:\/\/[^/]+\/([^/]+)\/(.+?)(?:\.git)?$/);
97
+ if (!match) {
98
+ throw new ValidationError(`Unable to parse GitHub URL: ${gitUrl}`);
99
+ }
100
+ const [, owner, repo] = match;
101
+ if (!GITHUB_OWNER.test(owner) ||
102
+ !GITHUB_REPO.test(repo) ||
103
+ /^\.+$/.test(repo)) {
104
+ throw new ValidationError(`Invalid GitHub owner/repo in ${gitUrl}: expected OWNER/REPO with letters, digits, '-', '_' (and '.' in the repo name)`);
105
+ }
106
+ return { type: "github", gitUrl, owner, repo, host };
116
107
  }
117
108
  function parseAzureDevOpsUrl(gitUrl) {
118
109
  // Handle SSH format: git@ssh.dev.azure.com:v3/organization/project/repo
@@ -0,0 +1,10 @@
1
+ /** Credentials xfg itself reads; config must never route them anywhere else. */
2
+ export declare const CREDENTIAL_ENV_VARS: ReadonlySet<string>;
3
+ export declare function isCredentialEnvName(name: string): boolean;
4
+ export declare function defaultAiKeyEnv(provider: string): string;
5
+ export declare function isDefaultAiBaseUrl(provider: string, baseUrl: string | undefined): boolean;
6
+ /**
7
+ * A credential name may only feed `prOptions.ai` when it is the provider's
8
+ * own key going to the provider's own API.
9
+ */
10
+ export declare function assertAiKeyEnvAllowed(provider: string, apiKeyEnv: string | undefined, baseUrl: string | undefined): void;
@@ -0,0 +1,50 @@
1
+ import { ValidationError } from "./errors.js";
2
+ /** Credentials xfg itself reads; config must never route them anywhere else. */
3
+ export const CREDENTIAL_ENV_VARS = new Set([
4
+ "XFG_GITHUB_APP_PRIVATE_KEY",
5
+ "XFG_GITHUB_CLIENT_ID",
6
+ "GH_TOKEN",
7
+ "GITHUB_TOKEN",
8
+ "GH_ENTERPRISE_TOKEN",
9
+ "GITHUB_ENTERPRISE_TOKEN",
10
+ "AZURE_DEVOPS_EXT_PAT",
11
+ "GITLAB_TOKEN",
12
+ "ANTHROPIC_API_KEY",
13
+ "OPENAI_API_KEY",
14
+ ]);
15
+ export function isCredentialEnvName(name) {
16
+ return CREDENTIAL_ENV_VARS.has(name.toUpperCase());
17
+ }
18
+ const AI_PROVIDER_DEFAULTS = {
19
+ anthropic: {
20
+ keyEnv: "ANTHROPIC_API_KEY",
21
+ origin: "https://api.anthropic.com",
22
+ },
23
+ openai: { keyEnv: "OPENAI_API_KEY", origin: "https://api.openai.com" },
24
+ };
25
+ export function defaultAiKeyEnv(provider) {
26
+ return AI_PROVIDER_DEFAULTS[provider].keyEnv;
27
+ }
28
+ export function isDefaultAiBaseUrl(provider, baseUrl) {
29
+ if (baseUrl === undefined)
30
+ return true;
31
+ try {
32
+ return new URL(baseUrl).origin === AI_PROVIDER_DEFAULTS[provider].origin;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * A credential name may only feed `prOptions.ai` when it is the provider's
40
+ * own key going to the provider's own API.
41
+ */
42
+ export function assertAiKeyEnvAllowed(provider, apiKeyEnv, baseUrl) {
43
+ if (apiKeyEnv === undefined || !isCredentialEnvName(apiKeyEnv))
44
+ return;
45
+ const ownKey = apiKeyEnv.toUpperCase() === defaultAiKeyEnv(provider);
46
+ if (ownKey && isDefaultAiBaseUrl(provider, baseUrl))
47
+ return;
48
+ throw new ValidationError(`prOptions.ai.apiKeyEnv '${apiKeyEnv}' is a credential xfg uses elsewhere; ` +
49
+ `export the key under a dedicated name for this provider and baseUrl.`);
50
+ }
@@ -1,5 +1,6 @@
1
1
  import type { DebugWarnLog } from "./logger.js";
2
2
  import type { GitHubApiTarget } from "./gh-api-utils.js";
3
+ import { type IGitHubHostPolicy } from "./github-host-policy.js";
3
4
  export interface ITokenManager {
4
5
  getTokenForRepo(repoInfo: GitHubApiTarget): Promise<string | null>;
5
6
  }
@@ -17,11 +18,15 @@ export interface ResolveGitHubTokenOptions {
17
18
  context: string;
18
19
  log?: DebugWarnLog;
19
20
  envToken?: string;
21
+ /** Hosts allowed to receive any token. Defaults to github.com only. */
22
+ hostPolicy?: IGitHubHostPolicy;
20
23
  }
21
24
  /**
22
25
  * Resolve a GitHub token for a repo: GitHub App token → envToken fallback.
23
26
  * Returns { token, skipped } where skipped=true means no App installation found
24
27
  * for this owner (token will be undefined). Both sync and settings paths use this.
28
+ * @throws GitHubHostNotAllowedError for a host outside the policy. Running
29
+ * tokenless is not safe there: `gh` would still send ambient credentials.
25
30
  */
26
31
  export declare function resolveGitHubToken(options: ResolveGitHubTokenOptions): Promise<GitHubTokenResult>;
27
32
  export declare function noAppInstallationMessage(owner: string): string;
@@ -29,7 +34,8 @@ export declare class GitHubTokenProvider implements IGitHubTokenProvider {
29
34
  private readonly tokenManager;
30
35
  private readonly envToken?;
31
36
  private readonly log?;
32
- constructor(tokenManager: ITokenManager | null, envToken?: string | undefined, log?: DebugWarnLog | undefined);
37
+ private readonly hostPolicy?;
38
+ constructor(tokenManager: ITokenManager | null, envToken?: string | undefined, log?: DebugWarnLog | undefined, hostPolicy?: IGitHubHostPolicy | undefined);
33
39
  getToken(repoInfo: GitHubApiTarget, context: string): Promise<GitHubTokenResult>;
34
40
  }
35
41
  /**
@@ -1,11 +1,19 @@
1
1
  import { toErrorMessage } from "./type-guards.js";
2
+ import { GitHubHostNotAllowedError, GitHubHostPolicy, } from "./github-host-policy.js";
3
+ const DEFAULT_HOST_POLICY = new GitHubHostPolicy();
2
4
  /**
3
5
  * Resolve a GitHub token for a repo: GitHub App token → envToken fallback.
4
6
  * Returns { token, skipped } where skipped=true means no App installation found
5
7
  * for this owner (token will be undefined). Both sync and settings paths use this.
8
+ * @throws GitHubHostNotAllowedError for a host outside the policy. Running
9
+ * tokenless is not safe there: `gh` would still send ambient credentials.
6
10
  */
7
11
  export async function resolveGitHubToken(options) {
8
12
  const { repoInfo, tokenManager, context, log, envToken } = options;
13
+ const hostPolicy = options.hostPolicy ?? DEFAULT_HOST_POLICY;
14
+ if (!hostPolicy.isAllowed(repoInfo.host)) {
15
+ throw new GitHubHostNotAllowedError(repoInfo.host);
16
+ }
9
17
  try {
10
18
  const appToken = await tokenManager?.getTokenForRepo(repoInfo);
11
19
  if (appToken === null) {
@@ -14,6 +22,8 @@ export async function resolveGitHubToken(options) {
14
22
  return { token: appToken ?? envToken, skipped: false };
15
23
  }
16
24
  catch (error) {
25
+ if (error instanceof GitHubHostNotAllowedError)
26
+ throw error;
17
27
  const errorMsg = `GitHub App token resolution failed for ${context}: ${toErrorMessage(error)}`;
18
28
  if (envToken) {
19
29
  log?.warn(`${errorMsg}; falling back to the environment token`);
@@ -31,10 +41,12 @@ export class GitHubTokenProvider {
31
41
  tokenManager;
32
42
  envToken;
33
43
  log;
34
- constructor(tokenManager, envToken, log) {
44
+ hostPolicy;
45
+ constructor(tokenManager, envToken, log, hostPolicy) {
35
46
  this.tokenManager = tokenManager;
36
47
  this.envToken = envToken;
37
48
  this.log = log;
49
+ this.hostPolicy = hostPolicy;
38
50
  }
39
51
  getToken(repoInfo, context) {
40
52
  return resolveGitHubToken({
@@ -43,6 +55,7 @@ export class GitHubTokenProvider {
43
55
  context,
44
56
  log: this.log,
45
57
  envToken: this.envToken,
58
+ hostPolicy: this.hostPolicy,
46
59
  });
47
60
  }
48
61
  }
@@ -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
- /401\b/,
17
- /403\b/,
18
- /404\b/,
19
- /422\b/,
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
- /429\b/,
65
- /500\b/,
66
- /502\b/,
67
- /503\b/,
68
- /504\b/,
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
- constructor(tokenManager: GitHubAppTokenManager | null, log?: ILogger | undefined, envToken?: string | undefined);
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
- constructor(tokenManager, log, envToken) {
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 {
@@ -1,5 +1,6 @@
1
- import { readFileSync, writeFileSync, existsSync } from "node:fs";
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
- writeFileSync(manifestPath, content, "utf-8");
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
- index.repos[repoName] = { files: files.sort(), deleted: deleted.sort() };
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, writeFileSync, unlinkSync } from "node:fs";
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
- writeFileSync(descFile, body, "utf-8");
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
@@ -16,11 +16,11 @@ export declare class GitOps implements ILocalGitOps {
16
16
  constructor(options: GitOpsOptions);
17
17
  private exec;
18
18
  /**
19
- * Validates that a file path doesn't escape the workspace directory.
20
- * @returns The resolved absolute file path
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.
@@ -1,5 +1,6 @@
1
- import { rmSync, existsSync, statSync, mkdirSync, writeFileSync, readFileSync, chmodSync, } from "node:fs";
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
- * Validates that a file path doesn't escape the workspace directory.
21
- * @returns The resolved absolute file path
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
- writeFileSync(filePath, normalized, "utf-8");
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
- constructor(clientId: string, privateKey: string);
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
- constructor(clientId, privateKey) {
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
- let url = `https://${apiHost}/app/installations?per_page=100`;
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
- if (host === "github.com") {
194
+ const lower = host.toLowerCase();
195
+ if (lower === "github.com") {
176
196
  return "api.github.com";
177
197
  }
178
- return `${host}/api/v3`;
198
+ return `${lower}/api/v3`;
179
199
  }
@@ -1,4 +1,5 @@
1
- import { existsSync, writeFileSync, unlinkSync } from "node:fs";
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
- writeFileSync(bodyFile, body, "utf-8");
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": "7.5.1",
3
+ "version": "8.0.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='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/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",