@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.40

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 (54) hide show
  1. package/README.md +712 -10
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  7. package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
  8. package/dist/index.d.ts +1205 -87
  9. package/dist/index.js +2752 -317
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +92 -18
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +223 -48
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Pinned Cursor OIDC trust predicates for the Factory App broker (#949).
3
+ *
4
+ * The broker verifies a Cursor-managed Cloud Agent JWT and mints a
5
+ * repo-scoped Factory App installation token. Audience, issuer, and JWKS are
6
+ * not consumer settings: a knob that pointed them elsewhere would be the
7
+ * whole mechanism undone, the same reason {@link FACTORY_PROOF_GATE_APP_ID}
8
+ * is pinned.
9
+ */
10
+
11
+ /** Cursor's OIDC issuer. Tokens minted on the agent VM carry this `iss`. */
12
+ export const FACTORY_CURSOR_OIDC_ISSUER = "https://api.cursor.com";
13
+
14
+ /** JWKS the broker uses to verify RS256 signatures. */
15
+ export const FACTORY_CURSOR_OIDC_JWKS_URL = "https://api.cursor.com/keys";
16
+
17
+ /**
18
+ * Audience a Cursor-managed VM must mint with. The CLI and the broker share
19
+ * this string; Cursor does not allowlist audiences.
20
+ */
21
+ export const FACTORY_CURSOR_OIDC_AUDIENCE = "Factory";
22
+
23
+ /**
24
+ * Runtime claim a Cursor-managed Cloud Agent VM always presents. Self-hosted
25
+ * workers are not this broker's callers.
26
+ */
27
+ export const FACTORY_CURSOR_OIDC_MANAGED_RUNTIME = "managed";
28
+
29
+ /** HQ route that exchanges a verified Cursor OIDC JWT for an App token. */
30
+ export const FACTORY_APP_BROKER_PATH = "/api/factory-app/installation-token";
31
+
32
+ /** Production broker origin. The CLI pins this; it is not profile-declared. */
33
+ export const FACTORY_APP_BROKER_ORIGIN = "https://hq.patronage.com";
@@ -1,36 +1,149 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import type {
3
+ SpawnSyncOptionsWithStringEncoding,
4
+ SpawnSyncReturns,
5
+ } from "node:child_process";
2
6
  import { createRequire } from "node:module";
7
+ import path from "node:path";
3
8
 
4
9
  import type { BundleAlchemyEntryOptions } from "./bundle-alchemy-entry.ts";
5
- import { bundleAlchemyEntry } from "./bundle-alchemy-entry.ts";
6
10
 
7
- export interface ExecuteAlchemyEntryOptions {
11
+ /** Node's spawnSync default is 1 MiB; Alchemy plans routinely exceed that. */
12
+ export const EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER = 64 * 1024 * 1024;
13
+
14
+ type AlchemySpawn = (
15
+ command: string,
16
+ args: readonly string[],
17
+ options: SpawnSyncOptionsWithStringEncoding
18
+ ) => SpawnSyncReturns<string>;
19
+
20
+ let spawnImplementation: AlchemySpawn = spawnSync;
21
+
22
+ /** Package-test seam. Not re-exported from `index.ts`. */
23
+ export const setExecuteAlchemyEntrySpawnForTests = (
24
+ next?: AlchemySpawn
25
+ ): void => {
26
+ spawnImplementation = next ?? spawnSync;
27
+ };
28
+
29
+ interface ExecuteAlchemyEntryCommon {
8
30
  /**
9
31
  * CLI arguments before the bundled entry. The absolute entry path is always
10
32
  * appended as the final argument.
11
33
  */
12
34
  readonly args: readonly string[];
13
- readonly bundle: BundleAlchemyEntryOptions;
14
35
  /** Child working directory. Defaults to the bundle root, then process.cwd. */
15
36
  readonly cwd?: string;
16
37
  /** Child environment. Defaults to process.env. */
17
38
  readonly env?: NodeJS.ProcessEnv;
18
39
  /** Consumer module context; normally the caller's import.meta.url. */
19
40
  readonly from: string | URL;
41
+ /**
42
+ * Largest captured stdout or stderr, in bytes. Omitted unless the caller
43
+ * sets it, so Node's spawnSync default (1 MiB) stays in force. Has no
44
+ * effect when stdio is `"inherit"`. Callers that need a larger capture
45
+ * pass `EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER` or another explicit value.
46
+ */
47
+ readonly maxBuffer?: number;
48
+ /**
49
+ * Called once with the child's captured streams, after the child exits and
50
+ * **before its exit status is judged**, so a caller keeping a diagnostic
51
+ * record still receives the output of a child that failed. Unused when
52
+ * stdio is `"inherit"`.
53
+ *
54
+ * The text handed over is the raw capture: `redact` is not applied to it,
55
+ * because `redact` shapes what this function returns and a record is not a
56
+ * return value. A caller that writes this anywhere owns its own redaction.
57
+ *
58
+ * It must not throw. Its work is a side record, and a throw from it would
59
+ * be indistinguishable here from the child's own failure.
60
+ */
61
+ readonly onCaptured?: (captured: {
62
+ readonly stdout: string | null;
63
+ readonly stderr: string | null;
64
+ }) => void;
65
+ /**
66
+ * Applied to captured stdout and stderr before they are returned. Unused
67
+ * when stdio is `"inherit"`. This package does not supply a secret-name
68
+ * policy; the caller owns redaction.
69
+ */
70
+ readonly redact?: (text: string) => string;
20
71
  /** Child stdio. Default "inherit". */
21
72
  readonly stdio?: "inherit" | "pipe";
22
73
  }
23
74
 
75
+ /**
76
+ * Exactly one entry source. The union refuses `bundle` and `bundledEntry`
77
+ * together, and refuses neither, so no runtime check is needed.
78
+ */
79
+ export type ExecuteAlchemyEntryOptions = ExecuteAlchemyEntryCommon &
80
+ (
81
+ | {
82
+ /** Bundle the consumer entry before execution. */
83
+ readonly bundle: BundleAlchemyEntryOptions;
84
+ readonly bundledEntry?: never;
85
+ }
86
+ | {
87
+ readonly bundle?: never;
88
+ /**
89
+ * Already-bundled entry path. Skips the internal bundle step and
90
+ * appends this path as the CLI's final argument.
91
+ */
92
+ readonly bundledEntry: string;
93
+ }
94
+ );
95
+
24
96
  export interface ExecuteAlchemyEntryResult {
25
97
  readonly bundledEntry: string;
26
98
  readonly stderr: string | null;
27
99
  readonly stdout: string | null;
28
100
  }
29
101
 
102
+ /**
103
+ * The child's working directory: the caller's `cwd`, then the bundle root,
104
+ * then this process's. One chain, used by `executeAlchemyEntry` and by the
105
+ * lifecycle, which prepares the bundle itself and so must resolve the same
106
+ * directory the bundle would have.
107
+ */
108
+ export const resolveAlchemyChildCwd = (
109
+ options: Pick<ExecuteAlchemyEntryCommon, "cwd"> & {
110
+ readonly bundle?: Pick<BundleAlchemyEntryOptions, "absWorkingDir">;
111
+ }
112
+ ): string => options.cwd ?? options.bundle?.absWorkingDir ?? process.cwd();
113
+
114
+ const resolveBundledEntry = async (
115
+ options: ExecuteAlchemyEntryOptions
116
+ ): Promise<string> => {
117
+ if (options.bundledEntry === undefined) {
118
+ // Loaded on demand: the bundler pulls in esbuild, and a caller that
119
+ // passes an already-bundled entry, or the `./alchemy` subpath that
120
+ // re-exports this helper, must not pay for it at import time.
121
+ const { bundleAlchemyEntry } = await import("./bundle-alchemy-entry.ts");
122
+ return await bundleAlchemyEntry(options.bundle);
123
+ }
124
+ return path.resolve(options.cwd ?? process.cwd(), options.bundledEntry);
125
+ };
126
+
127
+ const captured = (
128
+ text: string | null,
129
+ redact: ((text: string) => string) | undefined
130
+ ): string | null => {
131
+ if (text === null || redact === undefined) {
132
+ return text;
133
+ }
134
+ return redact(text);
135
+ };
136
+
30
137
  /**
31
138
  * Bundle a consumer-owned Alchemy entry, resolve that consumer's Alchemy CLI,
32
139
  * run it under the current Node binary, and return only on a successful exit.
33
140
  *
141
+ * Options carry exactly one entry source: `bundle` to bundle now, or
142
+ * `bundledEntry` to reuse an already-bundled path. Captured stdout and stderr (`stdio: "pipe"`) can be redacted through
143
+ * `redact` before they are returned; `stdio: "inherit"` still streams the
144
+ * child unredacted. `onCaptured` receives the raw streams of every piped
145
+ * child, including one that then fails.
146
+ *
34
147
  * Deploy/destroy/plan selection, stage admission, credentials, and every
35
148
  * convergence or destructive-change policy remain the caller's responsibility.
36
149
  */
@@ -42,18 +155,25 @@ export const executeAlchemyEntry = async (
42
155
  const cliEntry = createRequire(options.from).resolve(
43
156
  "alchemy/bin/alchemy.js"
44
157
  );
45
- const bundledEntry = await bundleAlchemyEntry(options.bundle);
46
- const result = spawnSync(
158
+ const bundledEntry = await resolveBundledEntry(options);
159
+ const result = spawnImplementation(
47
160
  process.execPath,
48
161
  [cliEntry, ...options.args, bundledEntry],
49
162
  {
50
- cwd: options.cwd ?? options.bundle.absWorkingDir ?? process.cwd(),
163
+ cwd: resolveAlchemyChildCwd(options),
51
164
  encoding: "utf-8",
52
165
  env: options.env ?? process.env,
166
+ ...(options.maxBuffer === undefined
167
+ ? {}
168
+ : { maxBuffer: options.maxBuffer }),
53
169
  stdio: options.stdio ?? "inherit",
54
170
  }
55
171
  );
56
172
 
173
+ // Before the status is judged: a failed child's output is the output a
174
+ // diagnostic record exists for.
175
+ options.onCaptured?.({ stderr: result.stderr, stdout: result.stdout });
176
+
57
177
  if (result.error) {
58
178
  // Node's spawn error carries `spawnargs`; retaining it as `cause` would
59
179
  // let ordinary recursive error logging reveal caller arguments.
@@ -72,7 +192,7 @@ export const executeAlchemyEntry = async (
72
192
 
73
193
  return {
74
194
  bundledEntry,
75
- stderr: result.stderr,
76
- stdout: result.stdout,
195
+ stderr: captured(result.stderr, options.redact),
196
+ stdout: captured(result.stdout, options.redact),
77
197
  };
78
198
  };
@@ -1,10 +1,13 @@
1
1
  import type { NodePnpmActionFamily, PinnedAction } from "./actions.ts";
2
+ import { assertPinnedAction } from "./pinned-action.ts";
2
3
 
3
- const PINNED_ACTION_PATTERN = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/u;
4
- const ACTION_TAG_PATTERN = /^v\d+(?:\.\d+){0,2}$/u;
5
4
  const RESERVED_ACTION_NAMES = new Set(["checkout", "setupNode", "setupPnpm"]);
6
5
 
7
6
  export interface WorkflowStep {
7
+ readonly continueOnError?: boolean;
8
+ readonly env?: Readonly<Record<string, string>>;
9
+ readonly id?: string;
10
+ readonly if?: string;
8
11
  readonly name: string;
9
12
  readonly uses?: string;
10
13
  readonly with?: Readonly<Record<string, string>>;
@@ -12,6 +15,7 @@ export interface WorkflowStep {
12
15
  }
13
16
 
14
17
  export interface CheckoutStepOptions {
18
+ readonly fetchDepth?: number;
15
19
  readonly name?: string;
16
20
  readonly ref?: string;
17
21
  }
@@ -32,6 +36,21 @@ export interface FactoryWorkflowSetupOptions {
32
36
  readonly setupNode?: SetupNodeStepOptions;
33
37
  }
34
38
 
39
+ /**
40
+ * Stable identifiers for the setup steps a generated workflow always emits,
41
+ * in emission order. A consumer selects steps by role instead of locating
42
+ * them by display name or by array position/length, so renaming a step or
43
+ * adding a new supported role never breaks role-based composition (#1076).
44
+ */
45
+ export const SETUP_STEP_ROLES = Object.freeze([
46
+ "checkout",
47
+ "setupPnpm",
48
+ "setupNode",
49
+ "install",
50
+ ] as const);
51
+
52
+ export type SetupStepRole = (typeof SETUP_STEP_ROLES)[number];
53
+
35
54
  export interface FactoryWorkflowOptions<
36
55
  Additional extends Readonly<Record<string, PinnedAction>>,
37
56
  > {
@@ -60,6 +79,13 @@ export interface FactoryWorkflowArtifact<
60
79
  readonly actions: Readonly<FamilyActions & Additional>;
61
80
  /** Checkout → pnpm → Node → install, customized by named role. */
62
81
  readonly setupSteps: readonly WorkflowStep[];
82
+ /**
83
+ * The same steps as `setupSteps`, keyed by stable role instead of position.
84
+ * A consumer that needs a subset or a differently-ordered composition (for
85
+ * example, a custom checkout followed by the shared install steps) selects
86
+ * by role here and never destructures `setupSteps` by array shape.
87
+ */
88
+ readonly setupStepsByRole: Readonly<Record<SetupStepRole, WorkflowStep>>;
63
89
  /**
64
90
  * Structurally accepted by gagen's `writeOrLint`; this package deliberately
65
91
  * has no gagen dependency.
@@ -76,31 +102,6 @@ const assertSingleLine = (name: string, value: string): void => {
76
102
  }
77
103
  };
78
104
 
79
- const actionRepository = (action: PinnedAction): string =>
80
- action.uses.slice(0, action.uses.indexOf("@"));
81
-
82
- const assertPinnedAction = (
83
- name: string,
84
- action: PinnedAction,
85
- expectedRepository?: string
86
- ): void => {
87
- if (!PINNED_ACTION_PATTERN.test(action.uses)) {
88
- throw new Error(
89
- `${name} must use owner/repository@<40-character commit SHA>, got "${action.uses}".`
90
- );
91
- }
92
- if (expectedRepository && actionRepository(action) !== expectedRepository) {
93
- throw new Error(
94
- `${name} must pin ${expectedRepository}, got ${actionRepository(action)}.`
95
- );
96
- }
97
- if (!ACTION_TAG_PATTERN.test(action.tag)) {
98
- throw new Error(
99
- `${name} tag must be vN, vN.N, or vN.N.N, got "${action.tag}".`
100
- );
101
- }
102
- };
103
-
104
105
  const usesStep = (
105
106
  fallbackName: string,
106
107
  action: PinnedAction
@@ -129,10 +130,29 @@ const assertAdditionalActions = (
129
130
  }
130
131
  };
131
132
 
132
- const setupSteps = (
133
+ const checkoutInputs = (
134
+ checkout: CheckoutStepOptions | undefined
135
+ ): Readonly<Record<string, string>> | undefined => {
136
+ if (checkout === undefined) {
137
+ return undefined;
138
+ }
139
+ const inputs: Record<string, string> = {};
140
+ if (checkout.fetchDepth !== undefined) {
141
+ if (!Number.isSafeInteger(checkout.fetchDepth) || checkout.fetchDepth < 0) {
142
+ throw new Error("checkout.fetchDepth must be a non-negative integer.");
143
+ }
144
+ inputs["fetch-depth"] = String(checkout.fetchDepth);
145
+ }
146
+ if (checkout.ref) {
147
+ inputs.ref = checkout.ref;
148
+ }
149
+ return Object.keys(inputs).length > 0 ? inputs : undefined;
150
+ };
151
+
152
+ const setupStepsByRole = (
133
153
  family: NodePnpmActionFamily,
134
154
  setup: FactoryWorkflowSetupOptions = {}
135
- ): readonly WorkflowStep[] => {
155
+ ): Readonly<Record<SetupStepRole, WorkflowStep>> => {
136
156
  const installRun = setup.install?.run ?? "pnpm install --frozen-lockfile";
137
157
  if (/(?:^|\s)--ignore-scripts(?:\s|$)/u.test(installRun)) {
138
158
  throw new Error(
@@ -141,14 +161,18 @@ const setupSteps = (
141
161
  }
142
162
 
143
163
  const { checkout, setupNode } = setup;
144
- return Object.freeze([
145
- {
164
+ const checkoutWith = checkoutInputs(checkout);
165
+ return Object.freeze({
166
+ checkout: {
146
167
  name: checkout?.name ?? "Checkout",
147
168
  uses: family.checkout.uses,
148
- ...(checkout?.ref ? { with: { ref: checkout.ref } } : {}),
169
+ ...(checkoutWith ? { with: checkoutWith } : {}),
170
+ },
171
+ install: {
172
+ name: setup.install?.name ?? "Install workspace",
173
+ run: installRun,
149
174
  },
150
- usesStep("Setup pnpm", family.setupPnpm),
151
- {
175
+ setupNode: {
152
176
  name: "Setup Node",
153
177
  uses: family.setupNode.uses,
154
178
  with: {
@@ -159,13 +183,27 @@ const setupSteps = (
159
183
  "node-version-file": setupNode?.nodeVersionFile ?? ".nvmrc",
160
184
  },
161
185
  },
162
- {
163
- name: setup.install?.name ?? "Install workspace",
164
- run: installRun,
165
- },
166
- ]);
186
+ setupPnpm: usesStep("Setup pnpm", family.setupPnpm),
187
+ });
167
188
  };
168
189
 
190
+ /**
191
+ * Select setup steps by stable role, in the order the roles are given.
192
+ *
193
+ * This is the supported alternative to destructuring `setupSteps` by array
194
+ * position or asserting its length: a caller names exactly the roles it
195
+ * needs (for example, every role but `checkout`, to follow its own
196
+ * head-pinned checkout with the shared pnpm/Node/install sequence), and that
197
+ * selection survives a renamed step or an added role.
198
+ */
199
+ export const setupStepsForRoles = (
200
+ artifact: {
201
+ readonly setupStepsByRole: Readonly<Record<SetupStepRole, WorkflowStep>>;
202
+ },
203
+ roles: readonly SetupStepRole[]
204
+ ): readonly WorkflowStep[] =>
205
+ Object.freeze(roles.map((role) => artifact.setupStepsByRole[role]));
206
+
169
207
  /**
170
208
  * Own one generated workflow source's action pins, setup block, provenance
171
209
  * banner, and gagen pinning policy as a single artifact.
@@ -193,10 +231,15 @@ export const factoryWorkflow = <
193
231
  ...(options.additionalActions ?? ({} as Additional)),
194
232
  }) as Readonly<FamilyActions & Additional>;
195
233
 
234
+ const stepsByRole = setupStepsByRole(options.actionFamily, options.setup);
235
+
196
236
  return Object.freeze({
197
237
  actionFamilyId: options.actionFamily.id,
198
238
  actions,
199
- setupSteps: setupSteps(options.actionFamily, options.setup),
239
+ setupSteps: Object.freeze(
240
+ SETUP_STEP_ROLES.map((role) => stepsByRole[role])
241
+ ),
242
+ setupStepsByRole: stepsByRole,
200
243
  writeOptions: Object.freeze({
201
244
  header: [
202
245
  `# GENERATED BY ${options.generated.source} -- DO NOT EDIT.`,
@@ -1,6 +1,17 @@
1
1
  import { createSign } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
3
 
4
+ import {
5
+ GitHubAppTokenTransportError,
6
+ githubJson,
7
+ setGithubTransportWaitForTests,
8
+ } from "./github-transport.ts";
9
+
10
+ // The error class lives with the transport primitive because `oxlint`'s
11
+ // max-classes-per-file keeps `GitHubApiError` alone in this file. It is
12
+ // re-exported here so the mint surface stays one import for consumers.
13
+ export { GitHubAppTokenTransportError } from "./github-transport.ts";
14
+
4
15
  /**
5
16
  * Minting a GitHub App installation token: the RS256 app JWT, the optional
6
17
  * installation lookup, and the token exchange (#617).
@@ -46,6 +57,20 @@ export class GitHubApiError extends Error {
46
57
  }
47
58
  }
48
59
 
60
+ /**
61
+ * Installation-token permission subset. GitHub only grants permissions the
62
+ * App already has; a caller that wants least privilege names the subset here
63
+ * rather than taking the App's full installation grant (#949).
64
+ */
65
+ export interface GithubAppInstallationPermissions {
66
+ checks?: "read" | "write";
67
+ }
68
+
69
+ /** The Factory App broker's token: repo-scoped Checks write, nothing else. */
70
+ export const FACTORY_APP_BROKER_TOKEN_PERMISSIONS = {
71
+ checks: "write",
72
+ } as const satisfies GithubAppInstallationPermissions;
73
+
49
74
  export interface GithubAppTokenOptions {
50
75
  /** Injectable `fetch` (tests, or a caller with its own instrumented one). */
51
76
  fetch?: typeof fetch;
@@ -55,6 +80,15 @@ export interface GithubAppTokenOptions {
55
80
  readPrivateKey?: (privateKeyPath: string) => Buffer | string;
56
81
  /** Per-request timeout; defaults to five seconds. */
57
82
  timeoutMs?: number;
83
+ /**
84
+ * Total transport attempts per request, the first one included. Defaults to
85
+ * three: a mint that must survive a stale keep-alive socket (#923). A caller
86
+ * whose mint is best-effort and already has a fallback passes 1, because
87
+ * retrying against a deliberately short timeout only delays that fallback
88
+ * (#938). The backoff between attempts is fixed and does not scale with
89
+ * `timeoutMs`; the two dials are unrelated.
90
+ */
91
+ transportAttempts?: number;
58
92
  }
59
93
 
60
94
  const base64url = (value: Buffer | string): string =>
@@ -90,26 +124,40 @@ export const githubAppJwt = (
90
124
  return `${unsigned}.${signer.sign(readKey(credentials.privateKeyPath), "base64url")}`;
91
125
  };
92
126
 
93
- const githubAppJson = async (
127
+ const githubAppJson = (
94
128
  request: typeof fetch,
95
129
  url: string,
96
130
  jwt: string,
97
131
  method: "GET" | "POST",
98
- timeoutMs: number
99
- ): Promise<Record<string, unknown>> => {
100
- const response = await request(url, {
101
- headers: {
102
- Accept: "application/vnd.github+json",
103
- Authorization: `Bearer ${jwt}`,
104
- "X-GitHub-Api-Version": "2022-11-28",
132
+ budget: { attempts?: number; body?: string; timeoutMs: number }
133
+ ): Promise<Record<string, unknown>> =>
134
+ githubJson(
135
+ {
136
+ attempts: budget.attempts,
137
+ ...(budget.body === undefined ? {} : { body: budget.body }),
138
+ closeConnection: true,
139
+ fetch: request,
140
+ method,
141
+ timeoutMs: budget.timeoutMs,
142
+ token: jwt,
143
+ url,
105
144
  },
106
- method,
107
- signal: AbortSignal.timeout(timeoutMs),
108
- });
109
- if (!response.ok) {
110
- throw new GitHubApiError(response.status, response.statusText);
111
- }
112
- return (await response.json()) as Record<string, unknown>;
145
+ {
146
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
147
+ transport: (failure, attempts) =>
148
+ new GitHubAppTokenTransportError(
149
+ failure.reason,
150
+ attempts,
151
+ failure.status
152
+ ),
153
+ }
154
+ ) as Promise<Record<string, unknown>>;
155
+
156
+ /** Package-test seam. Not re-exported from `index.ts`. */
157
+ export const setGithubAppTokenTransportWaitForTests = (
158
+ next?: (ms: number) => Promise<void>
159
+ ): void => {
160
+ setGithubTransportWaitForTests(next);
113
161
  };
114
162
 
115
163
  /**
@@ -124,13 +172,28 @@ export const mintInstallationToken = async (
124
172
  input: {
125
173
  credentials: GithubAppCredentials;
126
174
  owner: string;
175
+ /**
176
+ * Installation permission subset. Omitted, GitHub grants the App's full
177
+ * installation permissions. The Factory App broker passes
178
+ * {@link FACTORY_APP_BROKER_TOKEN_PERMISSIONS}.
179
+ */
180
+ permissions?: GithubAppInstallationPermissions;
181
+ /**
182
+ * Repository names (not `owner/repo`) to bind the token to. Omitted, the
183
+ * token covers every repository the installation can reach. The broker
184
+ * always names the one repository the Cursor OIDC claim authenticated.
185
+ */
186
+ repositories?: readonly string[];
127
187
  repo: string;
128
188
  },
129
189
  options: GithubAppTokenOptions = {}
130
190
  ): Promise<string> => {
131
191
  const { credentials } = input;
132
192
  const request = options.fetch ?? fetch;
133
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
193
+ const budget = {
194
+ attempts: options.transportAttempts,
195
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
196
+ };
134
197
  const jwt = githubAppJwt(credentials, options);
135
198
 
136
199
  let { installationId } = credentials;
@@ -140,7 +203,7 @@ export const mintInstallationToken = async (
140
203
  `https://api.github.com/repos/${input.owner}/${input.repo}/installation`,
141
204
  jwt,
142
205
  "GET",
143
- timeoutMs
206
+ budget
144
207
  );
145
208
  if (typeof installation.id !== "number") {
146
209
  throw new TypeError("GitHub App installation response omitted id");
@@ -148,12 +211,23 @@ export const mintInstallationToken = async (
148
211
  installationId = installation.id;
149
212
  }
150
213
 
214
+ const restriction =
215
+ input.permissions === undefined && input.repositories === undefined
216
+ ? undefined
217
+ : JSON.stringify({
218
+ ...(input.permissions === undefined
219
+ ? {}
220
+ : { permissions: input.permissions }),
221
+ ...(input.repositories === undefined
222
+ ? {}
223
+ : { repositories: [...input.repositories] }),
224
+ });
151
225
  const minted = await githubAppJson(
152
226
  request,
153
227
  `https://api.github.com/app/installations/${installationId}/access_tokens`,
154
228
  jwt,
155
229
  "POST",
156
- timeoutMs
230
+ restriction === undefined ? budget : { ...budget, body: restriction }
157
231
  );
158
232
  if (typeof minted.token !== "string") {
159
233
  throw new TypeError("GitHub App token response omitted token");