@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.
Files changed (74) 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 +16 -4
  5. package/dist/cli/settings-factories.d.ts +2 -1
  6. package/dist/cli/settings-factories.js +7 -1
  7. package/dist/cli/settings-report-builder.d.ts +6 -1
  8. package/dist/cli/settings-report-builder.js +7 -1
  9. package/dist/cli/settings-runner.js +24 -15
  10. package/dist/cli/sync-command.js +5 -1
  11. package/dist/cli/types.d.ts +4 -2
  12. package/dist/config/env.js +8 -0
  13. package/dist/config/file-reference-resolver.js +16 -13
  14. package/dist/config/index.d.ts +1 -1
  15. package/dist/config/merge.d.ts +9 -5
  16. package/dist/config/merge.js +148 -67
  17. package/dist/config/normalizer.js +87 -18
  18. package/dist/config/types.d.ts +28 -0
  19. package/dist/config/validator.js +25 -3
  20. package/dist/config/validators/ai-validator.js +2 -0
  21. package/dist/config/validators/file-validator.js +4 -1
  22. package/dist/config/validators/group-validator.js +3 -0
  23. package/dist/config/validators/ruleset-validator.js +6 -5
  24. package/dist/config/validators/shared.js +123 -0
  25. package/dist/output/settings-report.d.ts +6 -1
  26. package/dist/output/settings-report.js +31 -9
  27. package/dist/repo/detector.js +15 -24
  28. package/dist/settings/environments/diff.d.ts +22 -0
  29. package/dist/settings/environments/diff.js +78 -0
  30. package/dist/settings/environments/formatter.d.ts +17 -0
  31. package/dist/settings/environments/formatter.js +62 -0
  32. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  33. package/dist/settings/environments/github-environments-strategy.js +54 -0
  34. package/dist/settings/environments/index.d.ts +5 -0
  35. package/dist/settings/environments/index.js +3 -0
  36. package/dist/settings/environments/processor.d.ts +21 -0
  37. package/dist/settings/environments/processor.js +100 -0
  38. package/dist/settings/environments/types.d.ts +38 -0
  39. package/dist/settings/environments/types.js +1 -0
  40. package/dist/settings/index.d.ts +1 -0
  41. package/dist/settings/index.js +1 -0
  42. package/dist/settings/secrets/diff.d.ts +2 -0
  43. package/dist/settings/secrets/formatter.d.ts +4 -0
  44. package/dist/settings/secrets/formatter.js +17 -4
  45. package/dist/settings/secrets/index.d.ts +2 -2
  46. package/dist/settings/secrets/index.js +1 -1
  47. package/dist/settings/secrets/processor.d.ts +16 -2
  48. package/dist/settings/secrets/processor.js +132 -28
  49. package/dist/shared/credential-env.d.ts +10 -0
  50. package/dist/shared/credential-env.js +50 -0
  51. package/dist/shared/gh-token-utils.d.ts +7 -1
  52. package/dist/shared/gh-token-utils.js +14 -1
  53. package/dist/shared/github-host-policy.d.ts +22 -0
  54. package/dist/shared/github-host-policy.js +61 -0
  55. package/dist/shared/path-safety.d.ts +12 -0
  56. package/dist/shared/path-safety.js +51 -0
  57. package/dist/shared/retry-utils.js +9 -13
  58. package/dist/shared/sequential.d.ts +2 -0
  59. package/dist/shared/sequential.js +4 -0
  60. package/dist/sync/auth-options-builder.d.ts +3 -1
  61. package/dist/sync/auth-options-builder.js +4 -1
  62. package/dist/sync/manifest.js +7 -2
  63. package/dist/sync/render-writer.js +7 -1
  64. package/dist/sync/repository-processor.d.ts +2 -0
  65. package/dist/sync/repository-processor.js +1 -1
  66. package/dist/vcs/ado-pr-strategy.js +3 -2
  67. package/dist/vcs/commit-strategy-selector.d.ts +3 -2
  68. package/dist/vcs/commit-strategy-selector.js +5 -4
  69. package/dist/vcs/git-ops.d.ts +3 -3
  70. package/dist/vcs/git-ops.js +29 -8
  71. package/dist/vcs/github-app-token-manager.d.ts +4 -1
  72. package/dist/vcs/github-app-token-manager.js +24 -4
  73. package/dist/vcs/github-pr-strategy.js +3 -2
  74. package/package.json +3 -2
@@ -0,0 +1,100 @@
1
+ import { runSequentially } from "../../shared/sequential.js";
2
+ import { quoted } from "../../shared/string-utils.js";
3
+ import { toErrorMessage } from "../../shared/type-guards.js";
4
+ import { diffEnvironments, needsPatternLookup, toGitHubPolicy, } from "./diff.js";
5
+ import { formatEnvironmentsPlan, formatPatternLabel, } from "./formatter.js";
6
+ import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
7
+ function unmanagedWarnings(repoName, changes) {
8
+ return changes.flatMap((c) => c.unmanagedPatterns.map((p) => `${repoName}: environment ${quoted(c.name)} has ${formatPatternLabel(p)} not in config - left in place`));
9
+ }
10
+ // GitHub's plan-gate replies: 422 for environment protection rules, 403 for other plan-gated features.
11
+ function isPaidPlanError(error) {
12
+ const message = toErrorMessage(error);
13
+ return ((message.includes("HTTP 422") && /billing plan/i.test(message)) ||
14
+ (message.includes("HTTP 403") &&
15
+ message.includes("Upgrade to GitHub Pro or make this repository public")));
16
+ }
17
+ function withWarnings(extra, warnings) {
18
+ return warnings.length > 0 ? { ...extra, warnings } : extra;
19
+ }
20
+ export class EnvironmentsProcessor {
21
+ strategy;
22
+ metadataProvider;
23
+ constructor(strategy, metadataProvider) {
24
+ this.strategy = strategy;
25
+ this.metadataProvider = metadataProvider;
26
+ }
27
+ async process(repoConfig, repoInfo, options) {
28
+ return withGitHubGuards(repoConfig, repoInfo, options, {
29
+ hasDesiredSettings: (rc) => Object.keys(rc.settings?.environments ?? {}).length > 0,
30
+ emptySettingsMessage: "No environments configured",
31
+ applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
32
+ });
33
+ }
34
+ async readPatterns(githubRepo, names, strategyOptions) {
35
+ const patterns = new Map();
36
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
37
+ await runSequentially(names, async (name) => {
38
+ patterns.set(name.toLowerCase(), await this.strategy.listBranchPolicies(githubRepo, name, strategyOptions));
39
+ });
40
+ return patterns;
41
+ }
42
+ async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
43
+ const desired = repoConfig.settings?.environments ?? {};
44
+ const strategyOptions = { token: effectiveToken, host: githubRepo.host };
45
+ const current = await this.strategy.list(githubRepo, strategyOptions);
46
+ const patterns = await this.readPatterns(githubRepo, needsPatternLookup(desired, current), strategyOptions);
47
+ const changes = diffEnvironments(desired, current, patterns);
48
+ const changeCounts = countActions(changes);
49
+ const warnings = unmanagedWarnings(repoName, changes);
50
+ if (options.dryRun) {
51
+ return buildDryRunResult(repoName, changeCounts, withWarnings({ planOutput: formatEnvironmentsPlan(changes, true) }, warnings));
52
+ }
53
+ const progress = { writes: 0 };
54
+ let appliedCount = 0;
55
+ try {
56
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
57
+ await runSequentially(changes.filter((c) => c.action !== "unchanged"), async (change) => {
58
+ await this.applyChange(githubRepo, change, strategyOptions, progress);
59
+ appliedCount++;
60
+ });
61
+ }
62
+ catch (error) {
63
+ if (progress.writes > 0 || !isPaidPlanError(error))
64
+ throw error;
65
+ return this.skipIfNotPublic(githubRepo, strategyOptions, repoName, error);
66
+ }
67
+ return buildApplyResult(repoName, changeCounts, appliedCount, withWarnings({ planOutput: formatEnvironmentsPlan(changes, false) }, warnings));
68
+ }
69
+ async applyChange(githubRepo, change, strategyOptions, progress) {
70
+ if (change.putPolicy) {
71
+ await this.strategy.createOrUpdate(githubRepo, change.name, toGitHubPolicy(change.desiredKind), strategyOptions);
72
+ progress.writes++;
73
+ }
74
+ let missing = change.missingPatterns;
75
+ if (!change.patternsKnown) {
76
+ const existing = await this.strategy.listBranchPolicies(githubRepo, change.name, strategyOptions);
77
+ missing = missing.filter((p) => !existing.some((e) => e.type === p.type && e.name === p.name));
78
+ }
79
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
80
+ await runSequentially(missing, async (pattern) => {
81
+ await this.strategy.createBranchPolicy(githubRepo, change.name, pattern, strategyOptions);
82
+ progress.writes++;
83
+ });
84
+ }
85
+ // GitHub can't report the plan up front: listing a free private repo's environments still succeeds.
86
+ async skipIfNotPublic(githubRepo, strategyOptions, repoName, error) {
87
+ const metadata = await this.metadataProvider.getMetadata(githubRepo, strategyOptions);
88
+ if (metadata.visibility === "public")
89
+ throw error;
90
+ return {
91
+ success: true,
92
+ repoName,
93
+ message: "Skipped: environments need a paid plan on private repos",
94
+ skipped: true,
95
+ warnings: [
96
+ `${repoName}: environments on private repos need a paid GitHub plan (Pro, Team or Enterprise) - skipped (${toErrorMessage(error)})`,
97
+ ],
98
+ };
99
+ }
100
+ }
@@ -0,0 +1,38 @@
1
+ import type { RepoInfo } from "../../repo/index.js";
2
+ import type { GhApiOptions } from "../../shared/gh-api-utils.js";
3
+ import type { DeploymentBranchPattern } from "../../config/index.js";
4
+ import type { GitHubPublicKey, GitHubSecret } from "../secrets/types.js";
5
+ export interface GitHubDeploymentBranchPolicy {
6
+ protected_branches: boolean;
7
+ custom_branch_policies: boolean;
8
+ }
9
+ export interface GitHubEnvironment {
10
+ name: string;
11
+ /** null: any branch can deploy */
12
+ deployment_branch_policy: GitHubDeploymentBranchPolicy | null;
13
+ }
14
+ export interface GitHubEnvironmentsListResponse {
15
+ total_count: number;
16
+ environments?: GitHubEnvironment[];
17
+ }
18
+ export interface GitHubBranchPolicy {
19
+ id: number;
20
+ name: string;
21
+ type?: "branch" | "tag";
22
+ }
23
+ export interface GitHubBranchPoliciesResponse {
24
+ total_count: number;
25
+ branch_policies?: GitHubBranchPolicy[];
26
+ }
27
+ export interface IEnvironmentsStrategy {
28
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
29
+ createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
30
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
31
+ createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
32
+ }
33
+ export interface IEnvironmentSecretsStrategy {
34
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
35
+ listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
36
+ getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
37
+ upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -5,4 +5,5 @@ export { type LabelsPlanEntry, LabelsProcessor, type ILabelsProcessor, GitHubLab
5
5
  export { type CodeScanningPlanEntry, CodeScanningProcessor, type ICodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
6
6
  export { type VariablesPlanEntry, VariablesProcessor, type IVariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
7
7
  export { type CollaboratorsPlanEntry, CollaboratorsProcessor, type ICollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
8
+ export { type EnvironmentsPlanEntry, type EnvironmentsProcessorResult, EnvironmentsProcessor, type IEnvironmentsProcessor, type IEnvironmentSecretsStrategy, GitHubEnvironmentsStrategy, } from "./environments/index.js";
8
9
  export { SecretsProcessor, type SecretsPlanEntry, type ISecretsProcessor, type SecretsProcessorOptions, type SecretsProcessorResult, GitHubSecretsStrategy, SodiumEncryptor, type ISecretEncryptor, } from "./secrets/index.js";
@@ -5,5 +5,6 @@ export { LabelsProcessor, GitHubLabelsStrategy, } from "./labels/index.js";
5
5
  export { CodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
6
6
  export { VariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
7
7
  export { CollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
8
+ export { EnvironmentsProcessor, GitHubEnvironmentsStrategy, } from "./environments/index.js";
8
9
  // Secrets — not wired into `xfg sync`; driven by `xfg secrets sync` only.
9
10
  export { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "./secrets/index.js";
@@ -4,6 +4,8 @@ export type SecretAction = SettingsAction;
4
4
  export interface SecretChange {
5
5
  action: SecretAction;
6
6
  name: string;
7
+ /** Set for environment secrets */
8
+ environment?: string;
7
9
  }
8
10
  /**
9
11
  * Diffs remote secrets against the desired name set.
@@ -3,9 +3,13 @@ import { type ActiveAction } from "../base-processor.js";
3
3
  export interface SecretsPlanEntry {
4
4
  name: string;
5
5
  action: ActiveAction;
6
+ /** Set for environment secrets */
7
+ environment?: string;
6
8
  }
7
9
  export interface SecretsPlanResult {
8
10
  lines: string[];
9
11
  entries: SecretsPlanEntry[];
10
12
  }
13
+ /** `secret "X"` plus its notes, e.g. `secret "X" (environment "release", update, value write-only)`. */
14
+ export declare function formatSecretLabel(entry: SecretsPlanEntry): string;
11
15
  export declare function formatSecretsPlan(changes: SecretChange[], dryRun: boolean): SecretsPlanResult;
@@ -7,21 +7,34 @@ const ACTION_ORDER = {
7
7
  update: 1,
8
8
  delete: 2,
9
9
  };
10
+ /** `secret "X"` plus its notes, e.g. `secret "X" (environment "release", update, value write-only)`. */
11
+ export function formatSecretLabel(entry) {
12
+ const notes = [];
13
+ if (entry.environment !== undefined) {
14
+ notes.push(`environment ${quoted(entry.environment)}`);
15
+ }
16
+ if (entry.action === "update")
17
+ notes.push("update", "value write-only");
18
+ const suffix = notes.length > 0 ? ` (${notes.join(", ")})` : "";
19
+ return `secret ${quoted(entry.name)}${suffix}`;
20
+ }
10
21
  // Names only: this formatter must never receive or print a secret value.
11
22
  function formatEntry(entry) {
12
23
  switch (entry.action) {
13
24
  case "create":
14
- return chalk.green(` + secret ${quoted(entry.name)}`);
25
+ return chalk.green(` + ${formatSecretLabel(entry)}`);
15
26
  case "update":
16
- return chalk.yellow(` ~ secret ${quoted(entry.name)} (update, value write-only)`);
27
+ return chalk.yellow(` ~ ${formatSecretLabel(entry)}`);
17
28
  case "delete":
18
- return chalk.red(` - secret ${quoted(entry.name)}`);
29
+ return chalk.red(` - ${formatSecretLabel(entry)}`);
19
30
  }
20
31
  }
21
32
  export function formatSecretsPlan(changes, dryRun) {
22
33
  const entries = changes
23
34
  .filter(isActiveAction)
24
- .map((c) => ({ name: c.name, action: c.action }))
35
+ .map((c) => c.environment === undefined
36
+ ? { name: c.name, action: c.action }
37
+ : { name: c.name, action: c.action, environment: c.environment })
25
38
  .sort((a, b) => ACTION_ORDER[a.action] - ACTION_ORDER[b.action]);
26
39
  const summary = formatActionCountEntry("secret", "secrets", countActions(entries), dryRun);
27
40
  if (!summary) {
@@ -1,6 +1,6 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
- export type { ISecretsProcessor, SecretsProcessorOptions, SecretsProcessorResult, } from "./processor.js";
3
- export { formatSecretsPlan, type SecretsPlanEntry, type SecretsPlanResult, } from "./formatter.js";
2
+ export type { EnvironmentSecretsDependencies, ISecretsProcessor, SecretsProcessorOptions, SecretsProcessorResult, } from "./processor.js";
3
+ export { formatSecretsPlan, formatSecretLabel, type SecretsPlanEntry, type SecretsPlanResult, } from "./formatter.js";
4
4
  export { diffSecrets, type SecretAction, type SecretChange } from "./diff.js";
5
5
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
6
6
  export { SodiumEncryptor, type ISecretEncryptor } from "./encryption.js";
@@ -1,5 +1,5 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
- export { formatSecretsPlan, } from "./formatter.js";
2
+ export { formatSecretsPlan, formatSecretLabel, } from "./formatter.js";
3
3
  export { diffSecrets } from "./diff.js";
4
4
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
5
5
  export { SodiumEncryptor } from "./encryption.js";
@@ -1,6 +1,7 @@
1
- import type { RepoInfo } from "../../repo/index.js";
1
+ import type { IRepoMetadataProvider, RepoInfo } from "../../repo/index.js";
2
2
  import type { RepoConfig } from "../../config/index.js";
3
3
  import type { ISecretsStrategy } from "./types.js";
4
+ import type { IEnvironmentSecretsStrategy } from "../environments/types.js";
4
5
  import type { ISecretEncryptor } from "./encryption.js";
5
6
  import type { IEnvResolver } from "../../shared/env-resolver.js";
6
7
  import { type IGitHubTokenProvider } from "../../shared/gh-token-utils.js";
@@ -15,13 +16,26 @@ export interface SecretsProcessorResult extends BaseProcessorResult {
15
16
  planOutput?: SecretsPlanResult;
16
17
  /** Set when the skip is "nothing configured here" rather than "not a GitHub repo". */
17
18
  noSecretsConfigured?: boolean;
19
+ warnings?: string[];
20
+ }
21
+ export interface EnvironmentSecretsDependencies {
22
+ strategy: IEnvironmentSecretsStrategy;
23
+ metadataProvider: IRepoMetadataProvider;
18
24
  }
19
25
  export declare class SecretsProcessor implements ISecretsProcessor {
20
26
  private readonly strategy;
21
27
  private readonly encryptor;
22
28
  private readonly envResolver;
23
29
  private readonly tokenProvider?;
24
- constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver, tokenProvider?: IGitHubTokenProvider | undefined);
30
+ private readonly environments?;
31
+ constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver, tokenProvider?: IGitHubTokenProvider | undefined, environments?: EnvironmentSecretsDependencies | undefined);
32
+ private hasDesiredSecrets;
25
33
  process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: SecretsProcessorOptions): Promise<SecretsProcessorResult>;
26
34
  private applySettings;
35
+ private writeChange;
36
+ /** On a public repo a missing environment is an error; elsewhere it may be the plan, so warn and skip. */
37
+ private gateMissingEnvironments;
38
+ private resolve;
39
+ private readEnvironments;
40
+ private diffEnvironmentSecrets;
27
41
  }
@@ -1,3 +1,5 @@
1
+ import { runSequentially } from "../../shared/sequential.js";
2
+ import { quoted } from "../../shared/string-utils.js";
1
3
  import { noAppInstallationMessage, } from "../../shared/gh-token-utils.js";
2
4
  import { diffSecrets } from "./diff.js";
3
5
  import { formatSecretsPlan } from "./formatter.js";
@@ -8,29 +10,47 @@ function secretEntriesOf(repoConfig) {
8
10
  {});
9
11
  return Object.entries(entries);
10
12
  }
11
- function hasDesiredSecrets(repoConfig) {
13
+ function hasRepoSecrets(repoConfig) {
12
14
  const s = repoConfig.settings?.secrets ?? {};
13
15
  const { deleteOrphaned, ...entries } = s;
14
16
  return Object.keys(entries).length > 0 || deleteOrphaned === true;
15
17
  }
18
+ function environmentSecretsOf(repoConfig) {
19
+ return Object.entries(repoConfig.settings?.environments ?? {})
20
+ .map(([name, env]) => [
21
+ name,
22
+ Object.entries(env.secrets ?? {}),
23
+ ])
24
+ .filter(([, entries]) => entries.length > 0);
25
+ }
26
+ function missingEnvironmentWarning(repoName, env) {
27
+ return `${repoName}: environment ${quoted(env)} does not exist - its secrets were skipped (environments on private repos need a paid GitHub plan; on a paid plan, run 'xfg sync' first)`;
28
+ }
16
29
  export class SecretsProcessor {
17
30
  strategy;
18
31
  encryptor;
19
32
  envResolver;
20
33
  tokenProvider;
21
- constructor(strategy, encryptor, envResolver, tokenProvider) {
34
+ environments;
35
+ constructor(strategy, encryptor, envResolver, tokenProvider, environments) {
22
36
  this.strategy = strategy;
23
37
  this.encryptor = encryptor;
24
38
  this.envResolver = envResolver;
25
39
  this.tokenProvider = tokenProvider;
40
+ this.environments = environments;
41
+ }
42
+ hasDesiredSecrets(repoConfig) {
43
+ return (hasRepoSecrets(repoConfig) ||
44
+ (this.environments !== undefined &&
45
+ environmentSecretsOf(repoConfig).length > 0));
26
46
  }
27
47
  async process(repoConfig, repoInfo, options) {
28
48
  const result = await withGitHubGuards(repoConfig, repoInfo, options, {
29
- hasDesiredSettings: hasDesiredSecrets,
49
+ hasDesiredSettings: (rc) => this.hasDesiredSecrets(rc),
30
50
  emptySettingsMessage: "No secrets configured",
31
51
  applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
32
52
  });
33
- if (result.skipped && !hasDesiredSecrets(repoConfig)) {
53
+ if (result.skipped && !this.hasDesiredSecrets(repoConfig)) {
34
54
  return { ...result, noSecretsConfigured: true };
35
55
  }
36
56
  return result;
@@ -55,35 +75,54 @@ export class SecretsProcessor {
55
75
  const deleteOrphaned = configDeleteOrphaned && !(noDelete ?? false);
56
76
  const secretEntries = secretEntriesOf(repoConfig).filter((entry) => typeof entry[1] !== "boolean");
57
77
  const strategyOptions = { token, host: githubRepo.host };
58
- const currentSecrets = await this.strategy.list(githubRepo, strategyOptions);
59
- const changes = diffSecrets(currentSecrets, secretEntries.map(([name]) => name), deleteOrphaned);
60
- const changeCounts = countActions(changes);
78
+ const repoChanges = secretEntries.length > 0 || deleteOrphaned
79
+ ? diffSecrets(await this.strategy.list(githubRepo, strategyOptions), secretEntries.map(([name]) => name), deleteOrphaned)
80
+ : [];
81
+ const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions);
82
+ const envChanges = await this.diffEnvironmentSecrets(githubRepo, envGroups, strategyOptions);
61
83
  if (dryRun) {
62
- return buildDryRunResult(repoName, changeCounts, {
63
- planOutput: formatSecretsPlan(changes, true),
84
+ const planned = [...repoChanges, ...envChanges];
85
+ return buildDryRunResult(repoName, countActions(planned), {
86
+ planOutput: formatSecretsPlan(planned, true),
64
87
  });
65
88
  }
66
- const resolvedValues = secretEntries.length > 0
67
- ? this.envResolver.resolveAll(secretEntries.map(([name, config]) => ({
68
- name,
69
- envVar: config.env,
70
- })))
71
- : new Map();
72
- const publicKey = secretEntries.length > 0
73
- ? await this.strategy.getPublicKey(githubRepo, strategyOptions)
74
- : undefined;
89
+ const gate = await this.gateMissingEnvironments(githubRepo, envGroups, strategyOptions, repoName);
90
+ if (gate.error) {
91
+ return { success: false, repoName, message: `Failed: ${gate.error}` };
92
+ }
93
+ const writableGroups = envGroups.filter((g) => g.exists);
94
+ const writable = new Set(writableGroups.map((g) => g.environment));
95
+ const changes = [
96
+ ...repoChanges,
97
+ ...envChanges.filter((c) => writable.has(c.environment)),
98
+ ];
99
+ const extra = gate.warnings.length > 0 ? { warnings: gate.warnings } : {};
100
+ const repoValues = this.resolve(secretEntries);
101
+ const envValues = writableGroups.map((g) => ({
102
+ environment: g.environment,
103
+ values: this.resolve(g.entries),
104
+ }));
105
+ const scopes = new Map();
106
+ if (secretEntries.length > 0) {
107
+ scopes.set(undefined, {
108
+ values: repoValues,
109
+ publicKey: await this.strategy.getPublicKey(githubRepo, strategyOptions),
110
+ });
111
+ }
112
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
113
+ await runSequentially(envValues, async ({ environment, values }) => {
114
+ scopes.set(environment, {
115
+ values,
116
+ publicKey: await this.environments.strategy.getSecretsPublicKey(githubRepo, environment, strategyOptions),
117
+ });
118
+ });
75
119
  const applied = [];
76
120
  try {
77
- for (const change of changes.filter(isActiveAction)) {
78
- if (change.action === "delete") {
79
- await this.strategy.delete(githubRepo, change.name, strategyOptions);
80
- }
81
- else {
82
- const encrypted = await this.encryptor.encrypt(resolvedValues.get(change.name), publicKey.key);
83
- await this.strategy.upsert(githubRepo, change.name, encrypted, publicKey.key_id, strategyOptions);
84
- }
121
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
122
+ await runSequentially(changes.filter(isActiveAction), async (change) => {
123
+ await this.writeChange(githubRepo, change, scopes, strategyOptions);
85
124
  applied.push(change);
86
- }
125
+ });
87
126
  }
88
127
  catch (error) {
89
128
  // Report what already landed: the writes are not rolled back.
@@ -93,10 +132,75 @@ export class SecretsProcessor {
93
132
  message: `Failed: ${toErrorMessage(error)}`,
94
133
  changes: countActions(applied),
95
134
  planOutput: formatSecretsPlan(applied, false),
135
+ ...extra,
96
136
  };
97
137
  }
98
- return buildApplyResult(repoName, changeCounts, applied.length, {
138
+ return buildApplyResult(repoName, countActions(changes), applied.length, {
99
139
  planOutput: formatSecretsPlan(changes, false),
140
+ ...extra,
141
+ });
142
+ }
143
+ async writeChange(githubRepo, change, scopes, strategyOptions) {
144
+ if (change.action === "delete") {
145
+ await this.strategy.delete(githubRepo, change.name, strategyOptions);
146
+ return;
147
+ }
148
+ const { values, publicKey } = scopes.get(change.environment);
149
+ const encrypted = await this.encryptor.encrypt(values.get(change.name), publicKey.key);
150
+ if (change.environment === undefined) {
151
+ await this.strategy.upsert(githubRepo, change.name, encrypted, publicKey.key_id, strategyOptions);
152
+ }
153
+ else {
154
+ await this.environments.strategy.upsertSecret(githubRepo, change.environment, change.name, encrypted, publicKey.key_id, strategyOptions);
155
+ }
156
+ }
157
+ /** On a public repo a missing environment is an error; elsewhere it may be the plan, so warn and skip. */
158
+ async gateMissingEnvironments(githubRepo, groups, strategyOptions, repoName) {
159
+ const missing = groups.filter((g) => !g.exists);
160
+ if (missing.length === 0)
161
+ return { warnings: [] };
162
+ const { visibility } = await this.environments.metadataProvider.getMetadata(githubRepo, strategyOptions);
163
+ if (visibility === "public") {
164
+ return {
165
+ error: `environment ${quoted(missing[0].environment)} does not exist. Run 'xfg sync' first to create it.`,
166
+ warnings: [],
167
+ };
168
+ }
169
+ return {
170
+ warnings: missing.map((g) => missingEnvironmentWarning(repoName, g.environment)),
171
+ };
172
+ }
173
+ resolve(entries) {
174
+ if (entries.length === 0)
175
+ return new Map();
176
+ return this.envResolver.resolveAll(entries.map(([name, config]) => ({ name, envVar: config.env })));
177
+ }
178
+ async readEnvironments(githubRepo, repoConfig, strategyOptions) {
179
+ const configured = this.environments
180
+ ? environmentSecretsOf(repoConfig)
181
+ : [];
182
+ if (configured.length === 0)
183
+ return [];
184
+ const current = await this.environments.strategy.list(githubRepo, strategyOptions);
185
+ const existing = new Map(current.map((env) => [env.name.toLowerCase(), env.name]));
186
+ return configured.map(([name, entries]) => {
187
+ const actual = existing.get(name.toLowerCase());
188
+ return {
189
+ environment: actual ?? name,
190
+ exists: actual !== undefined,
191
+ entries,
192
+ };
193
+ });
194
+ }
195
+ async diffEnvironmentSecrets(githubRepo, groups, strategyOptions) {
196
+ const changes = [];
197
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
198
+ await runSequentially(groups, async (group) => {
199
+ const current = group.exists
200
+ ? await this.environments.strategy.listSecrets(githubRepo, group.environment, strategyOptions)
201
+ : [];
202
+ changes.push(...diffSecrets(current, group.entries.map(([name]) => name), false).map((change) => ({ ...change, environment: group.environment })));
100
203
  });
204
+ return changes;
101
205
  }
102
206
  }
@@ -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
  }