@peakflo/agent-harness 0.2.31-rc.1 → 0.2.32-rc.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.
@@ -2,6 +2,9 @@ import 'reflect-metadata';
2
2
  export interface GitHubProxyCertificateOptions {
3
3
  /** Override only for deterministic tests. Production preserves process.env. */
4
4
  environment?: NodeJS.ProcessEnv;
5
+ /** Certificate clock only; does not replace timers or TLS verification. */
6
+ now?: () => number;
7
+ logger?: Pick<Console, 'warn'>;
5
8
  }
6
9
  export declare function ambientCaCertificates(environment: NodeJS.ProcessEnv, outputPath: string): Promise<Buffer[]>;
7
10
  /** Node's bundled public roots, PEM, newline-terminated. */
@@ -9,15 +12,17 @@ export declare function publicRootCertificates(): string;
9
12
  export interface GitHubProxyCertificates {
10
13
  caCertificate: Buffer;
11
14
  caCertificatePath: string;
15
+ refresh(): Promise<void>;
12
16
  leaf(hostname: string): Promise<{
13
17
  certificate: Buffer;
14
18
  privateKey: Buffer;
15
19
  }>;
16
20
  }
17
21
  /**
18
- * Create one short-lived CA for this harness process. WebCrypto creates and
19
- * signs every key in process. Private key material exists only in memory. Only
20
- * the public CA certificate is written, as the command-line trust anchor.
22
+ * Maintain one process-local signing identity with renewable certificates.
23
+ * WebCrypto creates and signs every key in process. Private key material exists
24
+ * only in memory. Only the public CA certificate is written as the command-line
25
+ * trust anchor.
21
26
  *
22
27
  * SSL_CERT_FILE and CURL_CA_BUNDLE replace (rather than extend) the caller's
23
28
  * normal trust store. The file therefore also carries Node's public roots. If
@@ -10,7 +10,12 @@ const node_path_1 = require("node:path");
10
10
  const node_tls_1 = require("node:tls");
11
11
  const x509_1 = require("@peculiar/x509");
12
12
  const CA_CERTIFICATE_FILE = '.github-proxy-ca.pem';
13
- const CERTIFICATE_LIFETIME_MS = 2 * 24 * 60 * 60 * 1000;
13
+ const DAY_MS = 24 * 60 * 60 * 1000;
14
+ const CA_LIFETIME_MS = 30 * DAY_MS;
15
+ const CA_RENEW_BEFORE_MS = DAY_MS;
16
+ const LEAF_LIFETIME_MS = 2 * DAY_MS;
17
+ const LEAF_RENEW_BEFORE_MS = 6 * 60 * 60 * 1000;
18
+ const RENEWAL_RETRY_MS = 30_000;
14
19
  const SIGNING_ALGORITHM = {
15
20
  name: 'RSASSA-PKCS1-v1_5',
16
21
  hash: 'SHA-256',
@@ -60,12 +65,11 @@ async function ambientCaCertificates(environment, outputPath) {
60
65
  function publicRootCertificates() {
61
66
  return `${node_tls_1.rootCertificates.join('\n')}\n`;
62
67
  }
63
- function validity() {
64
- const now = Date.now();
68
+ function validity(now, lifetimeMs, issuerExpiry = Infinity) {
65
69
  return {
66
70
  // Permit a small clock difference between the harness and the client.
67
71
  notBefore: new Date(now - 60_000),
68
- notAfter: new Date(now + CERTIFICATE_LIFETIME_MS)
72
+ notAfter: new Date(Math.min(now + lifetimeMs, issuerExpiry))
69
73
  };
70
74
  }
71
75
  function serialNumber() {
@@ -76,9 +80,10 @@ async function privateKeyPem(key) {
76
80
  return Buffer.from(x509_1.PemConverter.encode(pkcs8, x509_1.PemConverter.PrivateKeyTag));
77
81
  }
78
82
  /**
79
- * Create one short-lived CA for this harness process. WebCrypto creates and
80
- * signs every key in process. Private key material exists only in memory. Only
81
- * the public CA certificate is written, as the command-line trust anchor.
83
+ * Maintain one process-local signing identity with renewable certificates.
84
+ * WebCrypto creates and signs every key in process. Private key material exists
85
+ * only in memory. Only the public CA certificate is written as the command-line
86
+ * trust anchor.
82
87
  *
83
88
  * SSL_CERT_FILE and CURL_CA_BUNDLE replace (rather than extend) the caller's
84
89
  * normal trust store. The file therefore also carries Node's public roots. If
@@ -94,58 +99,150 @@ async function createGitHubProxyCertificates(stateRoot, options = {}) {
94
99
  'sign',
95
100
  'verify'
96
101
  ]));
97
- const ca = await x509_1.X509CertificateGenerator.createSelfSigned({
98
- serialNumber: serialNumber(),
99
- name: 'CN=Peakflo GitHub Sandbox Proxy CA',
100
- ...validity(),
101
- signingAlgorithm: SIGNING_ALGORITHM,
102
- keys: caKeys,
103
- extensions: [
104
- new x509_1.BasicConstraintsExtension(true, undefined, true),
105
- new x509_1.KeyUsagesExtension(x509_1.KeyUsageFlags.keyCertSign | x509_1.KeyUsageFlags.cRLSign, true),
106
- await x509_1.SubjectKeyIdentifierExtension.create(caKeys.publicKey)
107
- ]
108
- });
109
- const caCertificate = Buffer.from(ca.toString('pem'));
102
+ const now = options.now ?? Date.now;
110
103
  const caCertificatePath = (0, node_path_1.join)(root, CA_CERTIFICATE_FILE);
111
104
  const ambientRoots = await ambientCaCertificates(options.environment ?? process.env, caCertificatePath);
112
- const publicRoots = publicRootCertificates();
113
- await (0, promises_1.writeFile)(caCertificatePath, Buffer.concat([...ambientRoots, Buffer.from(publicRoots), caCertificate]), { mode: 0o644 });
114
- await (0, promises_1.chmod)(caCertificatePath, 0o644);
105
+ const publicRoots = Buffer.from(publicRootCertificates());
106
+ let ca;
107
+ let caCertificate = Buffer.alloc(0);
108
+ let renewal;
109
+ let retryAfter = 0;
110
+ let lastRenewalFailure;
111
+ let fallbackReady = false;
115
112
  const leaves = new Map();
116
- const makeLeaf = async (hostname) => {
117
- const leafKeys = (await node_crypto_1.webcrypto.subtle.generateKey(SIGNING_ALGORITHM, true, ['sign', 'verify']));
118
- const certificate = await x509_1.X509CertificateGenerator.create({
113
+ const renew = async () => {
114
+ // Keep this process's in-memory signing key and issuer name. Existing
115
+ // clients that cached the still-valid CA can verify refreshed leaves during
116
+ // the renewal window. No private key is persisted or exposed to a backend.
117
+ const next = await x509_1.X509CertificateGenerator.createSelfSigned({
119
118
  serialNumber: serialNumber(),
120
- subject: `CN=${hostname}`,
121
- issuer: ca.subject,
122
- ...validity(),
119
+ name: 'CN=Peakflo GitHub Sandbox Proxy CA',
120
+ ...validity(now(), CA_LIFETIME_MS),
123
121
  signingAlgorithm: SIGNING_ALGORITHM,
124
- publicKey: leafKeys.publicKey,
125
- signingKey: caKeys.privateKey,
122
+ keys: caKeys,
126
123
  extensions: [
127
- new x509_1.BasicConstraintsExtension(false, undefined, true),
128
- new x509_1.KeyUsagesExtension(x509_1.KeyUsageFlags.digitalSignature | x509_1.KeyUsageFlags.keyEncipherment, true),
129
- new x509_1.ExtendedKeyUsageExtension([x509_1.ExtendedKeyUsage.serverAuth]),
130
- new x509_1.SubjectAlternativeNameExtension([{ type: 'dns', value: hostname }]),
131
- await x509_1.SubjectKeyIdentifierExtension.create(leafKeys.publicKey)
124
+ new x509_1.BasicConstraintsExtension(true, undefined, true),
125
+ new x509_1.KeyUsagesExtension(x509_1.KeyUsageFlags.keyCertSign | x509_1.KeyUsageFlags.cRLSign, true),
126
+ await x509_1.SubjectKeyIdentifierExtension.create(caKeys.publicKey)
132
127
  ]
133
128
  });
134
- return {
135
- certificate: Buffer.from(certificate.toString('pem')),
136
- privateKey: await privateKeyPem(leafKeys.privateKey)
137
- };
129
+ const pem = Buffer.from(next.toString('pem'));
130
+ const temporaryPath = `${caCertificatePath}.${(0, node_crypto_1.randomBytes)(8).toString('hex')}.tmp`;
131
+ try {
132
+ await (0, promises_1.writeFile)(temporaryPath, Buffer.concat([...ambientRoots, publicRoots, pem]), { mode: 0o644 });
133
+ // writeFile mode is masked by umask; preserve the old readable bundle mode.
134
+ await (0, promises_1.chmod)(temporaryPath, 0o644);
135
+ // Git must never read a partly rewritten trust bundle.
136
+ await (0, promises_1.rename)(temporaryPath, caCertificatePath);
137
+ }
138
+ finally {
139
+ await (0, promises_1.unlink)(temporaryPath).catch((error) => {
140
+ if (error.code !== 'ENOENT')
141
+ throw error;
142
+ });
143
+ }
144
+ ca = next;
145
+ caCertificate = pem;
146
+ retryAfter = 0;
147
+ lastRenewalFailure = undefined;
148
+ fallbackReady = false;
149
+ // In-flight leaves remain valid: renewal keeps the signing key/issuer,
150
+ // and their validity was bounded by the previous CA. Do not cache them again.
151
+ leaves.clear();
138
152
  };
153
+ const validCaAt = (time) => !!ca && ca.notBefore.getTime() <= time && ca.notAfter.getTime() > time;
154
+ const refresh = async () => {
155
+ const time = now();
156
+ if (validCaAt(time) && ca.notAfter.getTime() - time > CA_RENEW_BEFORE_MS)
157
+ return;
158
+ if (renewal) {
159
+ await renewal;
160
+ return;
161
+ }
162
+ if (time < retryAfter) {
163
+ if (fallbackReady && validCaAt(time))
164
+ return;
165
+ throw lastRenewalFailure;
166
+ }
167
+ // Concurrent leases and CONNECT handshakes share one atomic renewal.
168
+ if (!renewal) {
169
+ renewal = renew()
170
+ .catch(async (error) => {
171
+ lastRenewalFailure = error;
172
+ retryAfter = now() + RENEWAL_RETRY_MS;
173
+ fallbackReady = false;
174
+ // A failed atomic replacement leaves the previous bundle intact. Keep
175
+ // using it only while its actual issuer is valid and still on disk.
176
+ const bundleIntact = validCaAt(now()) &&
177
+ (await (0, promises_1.readFile)(caCertificatePath).then((bundle) => bundle.includes(caCertificate), () => false));
178
+ fallbackReady = bundleIntact;
179
+ if (!fallbackReady)
180
+ throw error;
181
+ (options.logger ?? console).warn('[GitHubProxy] Certificate renewal failed; using the still-valid trust bundle and retrying in 30 seconds.');
182
+ })
183
+ .finally(() => {
184
+ renewal = undefined;
185
+ });
186
+ }
187
+ await renewal;
188
+ };
189
+ await refresh();
139
190
  return {
140
- caCertificate,
191
+ get caCertificate() {
192
+ return caCertificate;
193
+ },
141
194
  caCertificatePath,
142
- leaf(hostname) {
143
- let leaf = leaves.get(hostname);
144
- if (!leaf) {
145
- leaf = makeLeaf(hostname);
146
- leaves.set(hostname, leaf);
195
+ refresh,
196
+ async leaf(hostname) {
197
+ await refresh();
198
+ const time = now();
199
+ let cached = leaves.get(hostname);
200
+ if (cached &&
201
+ cached.validFrom <= time &&
202
+ cached.expiresAt - time > LEAF_RENEW_BEFORE_MS) {
203
+ return cached.value;
204
+ }
205
+ const issuer = ca;
206
+ const dates = validity(time, LEAF_LIFETIME_MS, issuer.notAfter.getTime());
207
+ const value = (async () => {
208
+ const leafKeys = (await node_crypto_1.webcrypto.subtle.generateKey(SIGNING_ALGORITHM, true, ['sign', 'verify']));
209
+ const certificate = await x509_1.X509CertificateGenerator.create({
210
+ serialNumber: serialNumber(),
211
+ subject: `CN=${hostname}`,
212
+ issuer: issuer.subject,
213
+ ...dates,
214
+ signingAlgorithm: SIGNING_ALGORITHM,
215
+ publicKey: leafKeys.publicKey,
216
+ signingKey: caKeys.privateKey,
217
+ extensions: [
218
+ new x509_1.BasicConstraintsExtension(false, undefined, true),
219
+ new x509_1.KeyUsagesExtension(x509_1.KeyUsageFlags.digitalSignature | x509_1.KeyUsageFlags.keyEncipherment, true),
220
+ new x509_1.ExtendedKeyUsageExtension([x509_1.ExtendedKeyUsage.serverAuth]),
221
+ new x509_1.SubjectAlternativeNameExtension([
222
+ { type: 'dns', value: hostname }
223
+ ]),
224
+ await x509_1.SubjectKeyIdentifierExtension.create(leafKeys.publicKey)
225
+ ]
226
+ });
227
+ return {
228
+ certificate: Buffer.from(certificate.toString('pem')),
229
+ privateKey: await privateKeyPem(leafKeys.privateKey)
230
+ };
231
+ })();
232
+ cached = {
233
+ validFrom: dates.notBefore.getTime(),
234
+ expiresAt: dates.notAfter.getTime(),
235
+ value
236
+ };
237
+ leaves.set(hostname, cached);
238
+ try {
239
+ return await value;
240
+ }
241
+ catch (error) {
242
+ if (leaves.get(hostname) === cached)
243
+ leaves.delete(hostname);
244
+ throw error;
147
245
  }
148
- return leaf;
149
246
  }
150
247
  };
151
248
  }
@@ -34,6 +34,7 @@ export declare class GitHubWorkspaceProvider implements WorkspaceProvider {
34
34
  private serverStart;
35
35
  private linkSecret;
36
36
  private caCertificatePath;
37
+ private certificates;
37
38
  private readonly restartNotedSessions;
38
39
  private readonly restoredWorktreeNotes;
39
40
  private readonly preparationNotes;
@@ -69,6 +69,7 @@ class GitHubWorkspaceProvider {
69
69
  serverStart = null;
70
70
  linkSecret = null;
71
71
  caCertificatePath = null;
72
+ certificates = null;
72
73
  restartNotedSessions = new Set();
73
74
  restoredWorktreeNotes = new Map();
74
75
  preparationNotes = new Map();
@@ -423,8 +424,11 @@ class GitHubWorkspaceProvider {
423
424
  return path;
424
425
  }
425
426
  async ensureServer() {
426
- if (this.port !== null)
427
+ // Refresh the trust file before Git or a new backend reads it for a lease.
428
+ if (this.port !== null) {
429
+ await this.certificates?.refresh();
427
430
  return this.port;
431
+ }
428
432
  if (this.serverStart)
429
433
  return this.serverStart;
430
434
  this.serverStart = this.startServer();
@@ -444,7 +448,8 @@ class GitHubWorkspaceProvider {
444
448
  response.writeHead(400, { 'content-type': 'text/plain' });
445
449
  response.end('This endpoint is an HTTPS CONNECT proxy.\n');
446
450
  });
447
- const certificates = await (0, github_proxy_certificates_1.createGitHubProxyCertificates)(this.options.root);
451
+ const certificates = await (0, github_proxy_certificates_1.createGitHubProxyCertificates)(this.options.root, { logger: this.options.logger });
452
+ this.certificates = certificates;
448
453
  this.caCertificatePath = certificates.caCertificatePath;
449
454
  tlsProxy = new github_proxy_1.GitHubTlsProxy(server, {
450
455
  certificates,
@@ -34,6 +34,7 @@ exports.resolveApproval = resolveApproval;
34
34
  const node_crypto_1 = require("node:crypto");
35
35
  const model_gateway_1 = require("../adapters/model-gateway");
36
36
  const contract_1 = require("../contract");
37
+ const repository_cache_1 = require("../repository-cache");
37
38
  const vendor_backends_1 = require("../vendor-backends");
38
39
  const attachments_1 = require("./attachments");
39
40
  const cold_start_steps_1 = require("./cold-start-steps");
@@ -858,13 +859,33 @@ class SessionRunner {
858
859
  }
859
860
  catch (caught) {
860
861
  endWorkspace();
861
- const reason = caught instanceof Error ? caught.message : String(caught);
862
+ const rawReason = caught instanceof Error ? caught.message : String(caught);
863
+ const prefix = caught instanceof repository_cache_1.RepositoryPrepareError
864
+ ? `Repository ${caught.fullName} was not checked out: `
865
+ : '';
866
+ const reason = prefix && rawReason.startsWith(prefix)
867
+ ? rawReason.slice(prefix.length)
868
+ : rawReason;
869
+ if (caught instanceof repository_cache_1.RepositoryPrepareError) {
870
+ repositoryStatuses.push({
871
+ fullName: caught.fullName,
872
+ status: 'failed',
873
+ reason
874
+ });
875
+ }
862
876
  const status = session.workspace.refusalReason ? 'refused' : 'failed';
863
877
  const names = session.workspace.requestedRepositories ??
864
878
  (session.workspace.repositories ?? []).map(({ fullName }) => fullName);
879
+ const attributedFailure = repositoryStatuses.some((repository) => repository.status !== 'checkedOut');
865
880
  for (const fullName of names) {
866
881
  if (!repositoryStatuses.some((current) => current.fullName === fullName)) {
867
- repositoryStatuses.push({ fullName, status, reason });
882
+ repositoryStatuses.push({
883
+ fullName,
884
+ status,
885
+ reason: !session.workspace.refusalReason && attributedFailure
886
+ ? 'Not attempted because another repository could not be prepared.'
887
+ : reason
888
+ });
868
889
  }
869
890
  }
870
891
  const failures = repositoryStatuses.filter((repository) => repository.status !== 'checkedOut');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peakflo/agent-harness",
3
- "version": "0.2.31-rc.1",
3
+ "version": "0.2.32-rc.1",
4
4
  "description": "Headless Peakflo coding-agent harness. One codebase, three hosting modes: a Daytona cloud sandbox, a customer VM, and the 20x desktop.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",