@aspruyt/xfg 8.1.0 → 8.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,7 +30,7 @@ export declare class GitHubLifecycleProvider implements IRepoLifecycleProvider {
30
30
  */
31
31
  private isOrganization;
32
32
  private assertGitHub;
33
- private assertTokenCanCreateRepo;
33
+ private execRepoCreatingCommand;
34
34
  private buildGhApiPrefix;
35
35
  exists(params: LifecycleExistsParams): Promise<boolean>;
36
36
  create(params: LifecycleCreateParams): Promise<void>;
@@ -11,14 +11,17 @@ const REPO_NOT_FOUND_PATTERNS = [
11
11
  "Not Found",
12
12
  "404",
13
13
  ];
14
+ function errorText(error) {
15
+ return (toErrorMessage(error) +
16
+ ((error instanceof Error
17
+ ? error.stderr
18
+ : undefined) ?? ""));
19
+ }
14
20
  /**
15
21
  * Check if an error indicates repo not found (vs network/auth error).
16
22
  */
17
23
  function isRepoNotFoundError(error) {
18
- const message = toErrorMessage(error) +
19
- ((error instanceof Error
20
- ? error.stderr
21
- : undefined) ?? "");
24
+ const message = errorText(error);
22
25
  return REPO_NOT_FOUND_PATTERNS.some((pattern) => message.includes(pattern));
23
26
  }
24
27
  /**
@@ -41,13 +44,32 @@ const POST_CREATE_PERMANENT_PATTERNS = [
41
44
  * Interval between fork readiness checks (2 seconds).
42
45
  */
43
46
  const FORK_POLL_INTERVAL_MS = 2_000;
47
+ const CREATE_REPO_APP_PERMISSIONS = "Repository creation: Read and write";
48
+ const FORK_REPO_APP_PERMISSIONS = "Repository creation: Read and write, Administration: Read and write and Contents: Read, and be installed on the target account with access to all repositories and on the upstream account with access to the upstream repository";
49
+ const APP_PERMISSION_DENIED_PATTERNS = [
50
+ /\bHTTP\s*403\b/,
51
+ /not\s*accessible\s*by\s*integration/i,
52
+ ];
53
+ const GITHUB_RATE_LIMIT_PATTERNS = [
54
+ /API rate limit/i,
55
+ /secondary rate limit/i,
56
+ /abuse detection/i,
57
+ /too many requests/i,
58
+ /\b429\b/,
59
+ ];
44
60
  function isInstallationToken(token) {
45
61
  return token?.startsWith("ghs_") ?? false;
46
62
  }
47
- function personalAccountInstallationTokenError(repoInfo) {
48
- return new LifecycleError(`An installation token (GitHub App or Actions GITHUB_TOKEN) cannot create repositories for personal account '${repoInfo.owner}'. ` +
49
- `Create ${repoInfo.owner}/${repoInfo.repo} first, or run lifecycle with a personal access token. ` +
50
- `Installation tokens can only create repositories in organizations.`);
63
+ // GitHub reports a missing App permission on POST /user/repos as "403 Rate Limit Exceeded".
64
+ function isAppPermissionDenied(error) {
65
+ const text = errorText(error);
66
+ return (APP_PERMISSION_DENIED_PATTERNS.some((p) => p.test(text)) &&
67
+ !GITHUB_RATE_LIMIT_PATTERNS.some((p) => p.test(text)));
68
+ }
69
+ function appPermissionDeniedError(action, requiredPermissions, error) {
70
+ return new LifecycleError(`GitHub refused the App installation token while ${action}: ${toErrorMessage(error)}. ` +
71
+ `The GitHub App needs ${requiredPermissions}. ` +
72
+ `After changing App permissions, approve them on the installation.`, { cause: error });
51
73
  }
52
74
  function buildRepoCreateArgs(args, settings) {
53
75
  if (settings?.visibility === "public") {
@@ -121,21 +143,22 @@ export class GitHubLifecycleProvider {
121
143
  assertGitHub(repoInfo) {
122
144
  assertGitHubRepo(repoInfo, "GitHubLifecycleProvider");
123
145
  }
124
- // GitHub refuses installation tokens on POST /user/repos with a misleading
125
- // "403 Rate Limit Exceeded", which withRetry treats as transient.
126
- async assertTokenCanCreateRepo(repoInfo, token) {
127
- if (!isInstallationToken(token))
128
- return;
129
- let isOrg;
146
+ async execRepoCreatingCommand(args, token, permission, retryOptions = {}) {
147
+ const appPermissionDenied = (error) => isInstallationToken(token) && isAppPermissionDenied(error);
148
+ const tokenEnv = buildTokenEnv(token);
130
149
  try {
131
- isOrg = await this.isOrganization(repoInfo.owner, repoInfo, token);
150
+ return await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
151
+ retries: this.retries,
152
+ ...retryOptions,
153
+ abortOn: appPermissionDenied,
154
+ });
132
155
  }
133
156
  catch (error) {
134
- this.log?.debug(`Skipping installation token owner check for '${repoInfo.owner}': ${toErrorMessage(error)}`);
135
- return;
157
+ if (appPermissionDenied(error)) {
158
+ throw appPermissionDeniedError(permission.action, permission.required, error);
159
+ }
160
+ throw error;
136
161
  }
137
- if (!isOrg)
138
- throw personalAccountInstallationTokenError(repoInfo);
139
162
  }
140
163
  buildGhApiPrefix(repoInfo, token) {
141
164
  const tokenEnv = buildTokenEnv(token);
@@ -167,19 +190,15 @@ export class GitHubLifecycleProvider {
167
190
  async create(params) {
168
191
  const { repo: repoInfo, settings, token } = params;
169
192
  this.assertGitHub(repoInfo);
170
- await this.assertTokenCanCreateRepo(repoInfo, token);
171
- const tokenEnv = buildTokenEnv(token);
172
- const args = [
173
- "repo",
174
- "create",
175
- `${repoInfo.owner}/${repoInfo.repo}`,
176
- ];
193
+ const repoSlug = `${repoInfo.owner}/${repoInfo.repo}`;
194
+ const args = ["repo", "create", repoSlug];
177
195
  buildRepoCreateArgs(args, settings);
178
196
  // Add --add-readme to establish the default branch via an initial commit.
179
197
  // This avoids empty repos where HEAD doesn't resolve.
180
198
  args.push("--add-readme");
181
- await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
182
- retries: this.retries,
199
+ await this.execRepoCreatingCommand(args, token, {
200
+ action: `creating ${repoSlug}`,
201
+ required: CREATE_REPO_APP_PERMISSIONS,
183
202
  });
184
203
  if (settings?.defaultBranch) {
185
204
  const { tokenEnv: branchTokenEnv, baseArgs, apiPath, } = this.buildGhApiPrefix(repoInfo, token);
@@ -208,17 +227,14 @@ export class GitHubLifecycleProvider {
208
227
  `The upstream and target owners must be different.`);
209
228
  }
210
229
  const isOrg = await this.isOrganization(target.owner, target, token);
211
- if (!isOrg && isInstallationToken(token)) {
212
- throw personalAccountInstallationTokenError(target);
213
- }
214
- const tokenEnv = buildTokenEnv(token);
215
230
  const forkArgs = ["repo", "fork", `${upstream.owner}/${upstream.repo}`];
216
231
  if (isOrg) {
217
232
  forkArgs.push("--org", target.owner);
218
233
  }
219
234
  forkArgs.push("--fork-name", target.repo, "--clone=false");
220
- await withRetry(() => this.executor.exec("gh", forkArgs, this.cwd, { env: tokenEnv }), {
221
- retries: this.retries,
235
+ await this.execRepoCreatingCommand(forkArgs, token, {
236
+ action: `forking ${upstream.owner}/${upstream.repo} to ${target.owner}/${target.repo}`,
237
+ required: FORK_REPO_APP_PERMISSIONS,
222
238
  });
223
239
  // GitHub forks are async - wait for the fork to be ready for git operations
224
240
  await this.waitForForkReady(target, {
@@ -280,7 +296,6 @@ export class GitHubLifecycleProvider {
280
296
  async receiveMigration(params) {
281
297
  const { repo: repoInfo, sourceDir, settings, token } = params;
282
298
  this.assertGitHub(repoInfo);
283
- await this.assertTokenCanCreateRepo(repoInfo, token);
284
299
  await this.removeOriginRemote(sourceDir);
285
300
  await this.cleanNonStandardRefs(sourceDir);
286
301
  await this.renameMirrorDefaultBranch(sourceDir, settings?.defaultBranch);
@@ -335,8 +350,10 @@ export class GitHubLifecycleProvider {
335
350
  const createArgs = ["repo", "create", repoSlug];
336
351
  buildRepoCreateArgs(createArgs, settings);
337
352
  try {
338
- await withRetry(() => this.executor.exec("gh", createArgs, this.cwd, { env: tokenEnv }), {
339
- retries: this.retries,
353
+ await this.execRepoCreatingCommand(createArgs, token, {
354
+ action: `creating ${repoSlug}`,
355
+ required: CREATE_REPO_APP_PERMISSIONS,
356
+ }, {
340
357
  permanentErrorPatterns: POST_CREATE_PERMANENT_PATTERNS,
341
358
  log: this.log
342
359
  ? { info: (m) => this.log.info(m) }
@@ -14,7 +14,7 @@ export declare const DEFAULT_PERMANENT_ERROR_PATTERNS: RegExp[];
14
14
  * Rate limit errors need longer backoff (60s+) compared to network errors (1-4s).
15
15
  */
16
16
  export declare function isRateLimitError(error: unknown): boolean;
17
- interface RetryOptions {
17
+ export interface RetryOptions {
18
18
  /** Maximum number of retries (default: 3) */
19
19
  retries?: number;
20
20
  /** Callback when a retry attempt fails */
@@ -23,6 +23,8 @@ interface RetryOptions {
23
23
  permanentErrorPatterns?: RegExp[];
24
24
  /** Custom transient error patterns (defaults to DEFAULT_TRANSIENT_ERROR_PATTERNS) */
25
25
  transientErrorPatterns?: RegExp[];
26
+ /** Errors this returns true for fail at once, even if they match a transient pattern */
27
+ abortOn?: (error: Error) => boolean;
26
28
  /** Logger for retry messages (defaults to no logging) */
27
29
  log?: {
28
30
  info(msg: string): void;
@@ -48,4 +50,3 @@ export declare function isTransientError(error: unknown, patterns?: RegExp[]): b
48
50
  * @throws The original error for permanent failures (pRetry unwraps AbortError before propagating), or the last transient error after all retries exhausted
49
51
  */
50
52
  export declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
51
- export {};
@@ -152,8 +152,9 @@ export async function withRetry(fn, options) {
152
152
  }
153
153
  catch (error) {
154
154
  if (error instanceof Error &&
155
- !isTransientError(error, options?.transientErrorPatterns) &&
156
- isPermanentError(error, permanentPatterns)) {
155
+ (options?.abortOn?.(error) ||
156
+ (!isTransientError(error, options?.transientErrorPatterns) &&
157
+ isPermanentError(error, permanentPatterns)))) {
157
158
  throw new AbortError(error);
158
159
  }
159
160
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.1.0",
3
+ "version": "8.1.1",
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",