agent-gear 2.21.0 → 2.23.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.
- package/AGENTS.md +30 -2
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +6 -1
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +35 -0
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/commands/github.d.ts +17 -0
- package/dist/commands/github.d.ts.map +1 -0
- package/dist/commands/github.js +24 -0
- package/dist/commands/github.js.map +1 -0
- package/dist/commands/github.test.d.ts +2 -0
- package/dist/commands/github.test.d.ts.map +1 -0
- package/dist/commands/github.test.js +31 -0
- package/dist/commands/github.test.js.map +1 -0
- package/dist/github/credential-manager.d.ts +11 -3
- package/dist/github/credential-manager.d.ts.map +1 -1
- package/dist/github/credential-manager.js +65 -19
- package/dist/github/credential-manager.js.map +1 -1
- package/dist/github/credential-manager.test.js +89 -0
- package/dist/github/credential-manager.test.js.map +1 -1
- package/dist/github/gh-config.d.ts +6 -0
- package/dist/github/gh-config.d.ts.map +1 -1
- package/dist/github/gh-config.js +16 -4
- package/dist/github/gh-config.js.map +1 -1
- package/dist/github/gh-config.test.js +25 -0
- package/dist/github/gh-config.test.js.map +1 -1
- package/dist/github/project-token.d.ts +81 -0
- package/dist/github/project-token.d.ts.map +1 -0
- package/dist/github/project-token.js +232 -0
- package/dist/github/project-token.js.map +1 -0
- package/dist/github/project-token.test.d.ts +2 -0
- package/dist/github/project-token.test.d.ts.map +1 -0
- package/dist/github/project-token.test.js +256 -0
- package/dist/github/project-token.test.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-bases.d.ts +7 -2
- package/dist/knowledge-bases.d.ts.map +1 -1
- package/dist/knowledge-bases.js +10 -4
- package/dist/knowledge-bases.js.map +1 -1
- package/dist/knowledge-bases.test.js +87 -2
- package/dist/knowledge-bases.test.js.map +1 -1
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.js +2 -1
- package/dist/socketio-client.js.map +1 -1
- package/dist/socketio-client.test.js +1 -0
- package/dist/socketio-client.test.js.map +1 -1
- package/dist/workload-executor.d.ts +5 -0
- package/dist/workload-executor.d.ts.map +1 -1
- package/dist/workload-executor.js.map +1 -1
- package/dist/workload-executor.test.js +34 -0
- package/dist/workload-executor.test.js.map +1 -1
- package/package.json +1 -1
- package/src/cloud-host/supervisor.test.ts +43 -0
- package/src/cloud-host/supervisor.ts +5 -1
- package/src/commands/github.test.ts +38 -0
- package/src/commands/github.ts +36 -0
- package/src/github/credential-manager.test.ts +113 -0
- package/src/github/credential-manager.ts +68 -17
- package/src/github/gh-config.test.ts +25 -0
- package/src/github/gh-config.ts +17 -4
- package/src/github/project-token.test.ts +314 -0
- package/src/github/project-token.ts +292 -0
- package/src/index.ts +4 -0
- package/src/knowledge-bases.test.ts +104 -2
- package/src/knowledge-bases.ts +14 -3
- package/src/socketio-client.test.ts +1 -0
- package/src/socketio-client.ts +2 -1
- package/src/workload-executor.test.ts +48 -0
- package/src/workload-executor.ts +5 -0
|
@@ -409,3 +409,116 @@ describe('GithubCredentialManager', () => {
|
|
|
409
409
|
expect(JSON.stringify(result)).not.toContain(TOKEN);
|
|
410
410
|
});
|
|
411
411
|
});
|
|
412
|
+
|
|
413
|
+
describe('GithubCredentialManager project-scoped credentials (T-CM-P)', () => {
|
|
414
|
+
it('T-CM-P1: refreshNow(repo) sends a JSON body and validates the echo', async () => {
|
|
415
|
+
const fetchFn = fakeFetch(async () =>
|
|
416
|
+
jsonResponse({ token: TOKEN, repoFullName: 'Owner/Repo', expiresAt: EXPIRES_AT }),
|
|
417
|
+
);
|
|
418
|
+
const writeGhAuth = vi.fn(async () => {});
|
|
419
|
+
const manager = new GithubCredentialManager({
|
|
420
|
+
env: BASE_ENV,
|
|
421
|
+
fetch: fetchFn,
|
|
422
|
+
writeGhAuth,
|
|
423
|
+
log: createTestLogger().logger,
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
const result = await manager.refreshNow('owner/repo');
|
|
427
|
+
|
|
428
|
+
expect(result.ok).toBe(true);
|
|
429
|
+
expect(writeGhAuth).toHaveBeenCalledWith(TOKEN);
|
|
430
|
+
const [, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
|
|
431
|
+
expect(init.body).toBe(JSON.stringify({ repoFullName: 'owner/repo' }));
|
|
432
|
+
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
it('T-CM-P2: refreshNow() keeps the legacy bodyless request shape', async () => {
|
|
436
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT }));
|
|
437
|
+
const manager = new GithubCredentialManager({
|
|
438
|
+
env: BASE_ENV,
|
|
439
|
+
fetch: fetchFn,
|
|
440
|
+
writeGhAuth: async () => {},
|
|
441
|
+
log: createTestLogger().logger,
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
await manager.refreshNow();
|
|
445
|
+
|
|
446
|
+
const [, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
|
|
447
|
+
expect(init.body).toBeUndefined();
|
|
448
|
+
expect((init.headers as Record<string, string>)['Content-Type']).toBeUndefined();
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it('T-CM-P3: a mismatched echo is rejected and gh config is not written', async () => {
|
|
452
|
+
const fetchFn = fakeFetch(async () =>
|
|
453
|
+
jsonResponse({ token: TOKEN, repoFullName: 'other/repo', expiresAt: EXPIRES_AT }),
|
|
454
|
+
);
|
|
455
|
+
const writeGhAuth = vi.fn(async () => {});
|
|
456
|
+
const manager = new GithubCredentialManager({
|
|
457
|
+
env: BASE_ENV,
|
|
458
|
+
fetch: fetchFn,
|
|
459
|
+
writeGhAuth,
|
|
460
|
+
log: createTestLogger().logger,
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
const result = await manager.refreshNow('owner/repo');
|
|
464
|
+
|
|
465
|
+
expect(result).toEqual({ ok: false, error: 'repo-mismatch' });
|
|
466
|
+
expect(writeGhAuth).not.toHaveBeenCalled();
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it('T-CM-P4: 404 PROJECT_NOT_BOUND maps to project-not-bound without retrying', async () => {
|
|
470
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'PROJECT_NOT_BOUND' }, 404));
|
|
471
|
+
const manager = new GithubCredentialManager({
|
|
472
|
+
env: BASE_ENV,
|
|
473
|
+
fetch: fetchFn,
|
|
474
|
+
writeGhAuth: async () => {},
|
|
475
|
+
log: createTestLogger().logger,
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
const result = await manager.refreshNow('owner/repo');
|
|
479
|
+
|
|
480
|
+
expect(result).toEqual({ ok: false, error: 'project-not-bound' });
|
|
481
|
+
expect(fetchFn).toHaveBeenCalledTimes(1);
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
it('T-CM-P5: concurrent refreshes for different repos do not share a result', async () => {
|
|
485
|
+
const fetchFn = fakeFetch(async (_url, init) => {
|
|
486
|
+
const body = JSON.parse(String(init?.body ?? '{}')) as { repoFullName?: string };
|
|
487
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
488
|
+
return jsonResponse({ token: `token-${body.repoFullName}`, repoFullName: body.repoFullName });
|
|
489
|
+
});
|
|
490
|
+
const writeGhAuth = vi.fn(async (_token: string) => {});
|
|
491
|
+
const manager = new GithubCredentialManager({
|
|
492
|
+
env: BASE_ENV,
|
|
493
|
+
fetch: fetchFn,
|
|
494
|
+
writeGhAuth,
|
|
495
|
+
log: createTestLogger().logger,
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
const [a, b] = await Promise.all([manager.refreshNow('owner/a'), manager.refreshNow('owner/b')]);
|
|
499
|
+
|
|
500
|
+
expect(a.ok).toBe(true);
|
|
501
|
+
expect(b.ok).toBe(true);
|
|
502
|
+
expect(fetchFn).toHaveBeenCalledTimes(2);
|
|
503
|
+
expect(writeGhAuth.mock.calls.map((call) => call[0]).sort()).toEqual([
|
|
504
|
+
'token-owner/a',
|
|
505
|
+
'token-owner/b',
|
|
506
|
+
]);
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
it('T-CM-P6: the same repo key still coalesces into one request', async () => {
|
|
510
|
+
const fetchFn = fakeFetch(async () =>
|
|
511
|
+
jsonResponse({ token: TOKEN, repoFullName: 'owner/repo', expiresAt: EXPIRES_AT }),
|
|
512
|
+
);
|
|
513
|
+
const manager = new GithubCredentialManager({
|
|
514
|
+
env: BASE_ENV,
|
|
515
|
+
fetch: fetchFn,
|
|
516
|
+
writeGhAuth: async () => {},
|
|
517
|
+
log: createTestLogger().logger,
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
await Promise.all([manager.refreshNow('owner/repo'), manager.refreshNow('OWNER/REPO')]);
|
|
521
|
+
|
|
522
|
+
expect(fetchFn).toHaveBeenCalledTimes(1);
|
|
523
|
+
});
|
|
524
|
+
});
|
|
@@ -71,7 +71,8 @@ export class GithubCredentialManager {
|
|
|
71
71
|
private started = false;
|
|
72
72
|
private stopped = false;
|
|
73
73
|
private expiresAt: Date | null = null;
|
|
74
|
-
|
|
74
|
+
/** 按仓库键单飞:`repoFullName.toLowerCase()`;空键为主项目口径(旧语义)。 */
|
|
75
|
+
private readonly activeRefresh = new Map<string, Promise<GithubCredentialRefreshResult>>();
|
|
75
76
|
/** 近过期区「立即重试」是否已被消费(防止服务端持续返回近过期 token 时热循环)。 */
|
|
76
77
|
private nearExpiryImmediateTaken = false;
|
|
77
78
|
|
|
@@ -125,18 +126,22 @@ export class GithubCredentialManager {
|
|
|
125
126
|
/**
|
|
126
127
|
* 立即申请并写入 gh 配置。
|
|
127
128
|
*
|
|
128
|
-
*
|
|
129
|
+
* - 无参(主项目口径):保持旧语义,无 body、写主项目凭据;
|
|
130
|
+
* - 传 `repoFullName`:body `{repoFullName}` 申请项目级 token,并校验响应回显;
|
|
131
|
+
* - 并发调用按仓库键单飞(不同项目不共享同一次请求结果)。
|
|
129
132
|
*/
|
|
130
|
-
refreshNow(): Promise<GithubCredentialRefreshResult> {
|
|
131
|
-
|
|
132
|
-
const
|
|
133
|
-
|
|
133
|
+
refreshNow(repoFullName?: string): Promise<GithubCredentialRefreshResult> {
|
|
134
|
+
const key = typeof repoFullName === 'string' ? repoFullName.trim().toLowerCase() : '';
|
|
135
|
+
const inFlight = this.activeRefresh.get(key);
|
|
136
|
+
if (inFlight) return inFlight;
|
|
137
|
+
const refresh = this.doRefresh(repoFullName).finally(() => {
|
|
138
|
+
if (this.activeRefresh.get(key) === refresh) this.activeRefresh.delete(key);
|
|
134
139
|
});
|
|
135
|
-
this.activeRefresh
|
|
140
|
+
this.activeRefresh.set(key, refresh);
|
|
136
141
|
return refresh;
|
|
137
142
|
}
|
|
138
143
|
|
|
139
|
-
private async doRefresh(): Promise<GithubCredentialRefreshResult> {
|
|
144
|
+
private async doRefresh(repoFullName?: string): Promise<GithubCredentialRefreshResult> {
|
|
140
145
|
if (!this.isEnabled()) {
|
|
141
146
|
return { ok: false, error: 'disabled' };
|
|
142
147
|
}
|
|
@@ -147,7 +152,7 @@ export class GithubCredentialManager {
|
|
|
147
152
|
const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/github-credential`;
|
|
148
153
|
|
|
149
154
|
for (let attempt = 0; ; attempt += 1) {
|
|
150
|
-
const result = await this.request(url, hostKey);
|
|
155
|
+
const result = await this.request(url, hostKey, repoFullName);
|
|
151
156
|
if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
|
|
152
157
|
const delay = BACKOFF_MS[attempt]!;
|
|
153
158
|
this.log.warn(
|
|
@@ -165,12 +170,18 @@ export class GithubCredentialManager {
|
|
|
165
170
|
}
|
|
166
171
|
if (result.kind === 'retryable') {
|
|
167
172
|
// 退避耗尽:每次尝试已在上方记录告警,不重复输出。
|
|
168
|
-
return { ok: false, error: `Github 凭据无效(HTTP ${result.status})` };
|
|
173
|
+
return { ok: false, error: result.finalError ?? `Github 凭据无效(HTTP ${result.status})` };
|
|
169
174
|
}
|
|
170
175
|
const value = result.value;
|
|
171
176
|
// 非 401/403/404 的失败(5xx / 超时 / 非法 JSON / 写 gh 失败)必须留痕,
|
|
172
|
-
//
|
|
173
|
-
if (
|
|
177
|
+
// 否则线上只能看到「凭据没更新」而无任何线索;正常态(disabled/no-binding/project-not-bound)不告警。
|
|
178
|
+
if (
|
|
179
|
+
!value.ok &&
|
|
180
|
+
value.error &&
|
|
181
|
+
value.error !== 'no-binding' &&
|
|
182
|
+
value.error !== 'project-not-bound' &&
|
|
183
|
+
value.error !== 'disabled'
|
|
184
|
+
) {
|
|
174
185
|
this.log.error({ event: 'renew_failed', error: value.error }, '凭据续期失败');
|
|
175
186
|
}
|
|
176
187
|
return value;
|
|
@@ -180,8 +191,9 @@ export class GithubCredentialManager {
|
|
|
180
191
|
private async request(
|
|
181
192
|
url: string,
|
|
182
193
|
hostKey: string,
|
|
194
|
+
repoFullName?: string,
|
|
183
195
|
): Promise<
|
|
184
|
-
| { kind: 'retryable'; status: number }
|
|
196
|
+
| { kind: 'retryable'; status: number; finalError?: string }
|
|
185
197
|
| { kind: 'result'; value: GithubCredentialRefreshResult }
|
|
186
198
|
> {
|
|
187
199
|
const controller = new AbortController();
|
|
@@ -190,16 +202,32 @@ export class GithubCredentialManager {
|
|
|
190
202
|
try {
|
|
191
203
|
const response = await this.fetchFn(url, {
|
|
192
204
|
method: 'POST',
|
|
193
|
-
headers: {
|
|
205
|
+
headers: {
|
|
206
|
+
Authorization: `Bearer ${hostKey}`,
|
|
207
|
+
// 无 body 请求保持报文形状逐字不变(旧服务端兼容)。
|
|
208
|
+
...(repoFullName ? { 'Content-Type': 'application/json' } : {}),
|
|
209
|
+
},
|
|
210
|
+
...(repoFullName ? { body: JSON.stringify({ repoFullName }) } : {}),
|
|
194
211
|
signal: controller.signal,
|
|
195
212
|
});
|
|
196
213
|
|
|
197
214
|
if (response.status === 404) {
|
|
198
|
-
// 未设置 Git
|
|
199
|
-
|
|
215
|
+
// 未设置 Git 项目 / 该项目未初始化:正常跳过,不告警、不重试。
|
|
216
|
+
const error = await this.readErrorCode(response);
|
|
217
|
+
return {
|
|
218
|
+
kind: 'result',
|
|
219
|
+
value: {
|
|
220
|
+
ok: false,
|
|
221
|
+
error: error === 'PROJECT_NOT_BOUND' ? 'project-not-bound' : 'no-binding',
|
|
222
|
+
},
|
|
223
|
+
};
|
|
200
224
|
}
|
|
201
225
|
if (response.status === 401 || response.status === 403) {
|
|
202
|
-
return {
|
|
226
|
+
return {
|
|
227
|
+
kind: 'retryable',
|
|
228
|
+
status: response.status,
|
|
229
|
+
...(response.status === 403 ? { finalError: 'repo-not-authorized' } : {}),
|
|
230
|
+
};
|
|
203
231
|
}
|
|
204
232
|
if (!response.ok) {
|
|
205
233
|
return {
|
|
@@ -218,6 +246,16 @@ export class GithubCredentialManager {
|
|
|
218
246
|
if (typeof token !== 'string' || token.length === 0) {
|
|
219
247
|
return { kind: 'result', value: { ok: false, error: 'Github 凭据响应缺少 token' } };
|
|
220
248
|
}
|
|
249
|
+
if (repoFullName) {
|
|
250
|
+
const echoed = (payload as { repoFullName?: unknown } | null)?.repoFullName;
|
|
251
|
+
if (
|
|
252
|
+
typeof echoed !== 'string' ||
|
|
253
|
+
echoed.trim().toLowerCase() !== repoFullName.trim().toLowerCase()
|
|
254
|
+
) {
|
|
255
|
+
// 新客户端 + 旧服务端(忽略 body)会拿到主项目 token:必须拒绝写入。
|
|
256
|
+
return { kind: 'result', value: { ok: false, error: 'repo-mismatch' } };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
221
259
|
const rawExpiresAt = (payload as { expiresAt?: unknown } | null)?.expiresAt;
|
|
222
260
|
const expiresAt =
|
|
223
261
|
typeof rawExpiresAt === 'string' && !Number.isNaN(Date.parse(rawExpiresAt))
|
|
@@ -251,6 +289,19 @@ export class GithubCredentialManager {
|
|
|
251
289
|
}
|
|
252
290
|
}
|
|
253
291
|
|
|
292
|
+
/**
|
|
293
|
+
* 读取 404/403 响应体里的 `error` 枚举;不可读时返回空串。
|
|
294
|
+
* 只用于区分错误码,响应原文不会进入日志/错误信息。
|
|
295
|
+
*/
|
|
296
|
+
private async readErrorCode(response: Response): Promise<string> {
|
|
297
|
+
try {
|
|
298
|
+
const payload = (await response.json()) as { error?: unknown } | null;
|
|
299
|
+
return typeof payload?.error === 'string' ? payload.error : '';
|
|
300
|
+
} catch {
|
|
301
|
+
return '';
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
254
305
|
/** 下一次续期:50 分钟与「到期前 10 分钟」取较早;已进入/越过余量区时首次立即重试、
|
|
255
306
|
* 其后按 `NEAR_EXPIRY_RETRY_MS` 短间隔退避并告警(绝不回落 50 分钟,否则 token 过期后
|
|
256
307
|
* 还要再等 40 分钟才续期)。定时器 unref,不阻止进程退出。 */
|
|
@@ -101,3 +101,28 @@ describe('writeGhAuth', () => {
|
|
|
101
101
|
expect(calls).toHaveLength(0);
|
|
102
102
|
});
|
|
103
103
|
});
|
|
104
|
+
|
|
105
|
+
describe('writeGhAuth wrapper bypass (T-GHC-SKIP)', () => {
|
|
106
|
+
it('passes ZAG_GH_WRAPPER_SKIP_TOKEN=1 on both gh calls while keeping process.env', async () => {
|
|
107
|
+
const login = new FakeChild();
|
|
108
|
+
const setup = new FakeChild();
|
|
109
|
+
const { spawnFn, calls } = scriptedSpawn([login, setup]);
|
|
110
|
+
const previous = process.env.ZAG_TEST_MARKER;
|
|
111
|
+
process.env.ZAG_TEST_MARKER = 'kept';
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
await writeGhAuth(TOKEN, { spawn: spawnFn });
|
|
115
|
+
} finally {
|
|
116
|
+
if (previous === undefined) delete process.env.ZAG_TEST_MARKER;
|
|
117
|
+
else process.env.ZAG_TEST_MARKER = previous;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (const call of calls) {
|
|
121
|
+
const env = (call.options as { env?: NodeJS.ProcessEnv }).env;
|
|
122
|
+
expect(env?.ZAG_GH_WRAPPER_SKIP_TOKEN).toBe('1');
|
|
123
|
+
expect(env?.ZAG_TEST_MARKER).toBe('kept');
|
|
124
|
+
// token 不进入 env
|
|
125
|
+
expect(JSON.stringify(env)).not.toContain(TOKEN);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
});
|
package/src/github/gh-config.ts
CHANGED
|
@@ -13,12 +13,17 @@ export interface WriteGhAuthOptions {
|
|
|
13
13
|
* 执行一次 `gh` 子命令并收集输出。
|
|
14
14
|
*
|
|
15
15
|
* - `stdin` 只经管道写入(token 绝不进入 argv/env);
|
|
16
|
+
* - `env` 由调用方显式给出:凭据管理器写配置时必须带 `ZAG_GH_WRAPPER_SKIP_TOKEN=1`,
|
|
17
|
+
* 否则容器内的 `/usr/local/bin/gh` wrapper 会再次申请 token 形成自指;
|
|
16
18
|
* - 失败时按 `redactSecrets` 脱敏后再拼接错误,错误信息不含任何 secret;
|
|
17
19
|
* - 每次调用只执行一次,不做重试(避免无限循环)。
|
|
18
20
|
*/
|
|
19
|
-
function runGh(spawnFn: GhSpawn, args: string[], stdin?: string): Promise<void> {
|
|
21
|
+
function runGh(spawnFn: GhSpawn, args: string[], stdin?: string, env?: NodeJS.ProcessEnv): Promise<void> {
|
|
20
22
|
return new Promise<void>((resolve, reject) => {
|
|
21
|
-
const child = spawnFn('gh', args, {
|
|
23
|
+
const child = spawnFn('gh', args, {
|
|
24
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
25
|
+
...(env ? { env } : {}),
|
|
26
|
+
});
|
|
22
27
|
let output = '';
|
|
23
28
|
let settled = false;
|
|
24
29
|
|
|
@@ -58,12 +63,19 @@ function runGh(spawnFn: GhSpawn, args: string[], stdin?: string): Promise<void>
|
|
|
58
63
|
});
|
|
59
64
|
}
|
|
60
65
|
|
|
66
|
+
/**
|
|
67
|
+
* 容器内 gh wrapper 的跳过通道环境变量名(原生 gh 直通,不申请项目级 token)。
|
|
68
|
+
* 凭据管理器自身调用 `gh auth ...` 时必须设置,避免 wrapper 自指递归。
|
|
69
|
+
*/
|
|
70
|
+
export const GH_WRAPPER_SKIP_ENV = 'ZAG_GH_WRAPPER_SKIP_TOKEN';
|
|
71
|
+
|
|
61
72
|
/**
|
|
62
73
|
* 将 Github token 写入容器内 `gh` 配置(云主机唯一凭据写入口)。
|
|
63
74
|
*
|
|
64
75
|
* 1. `gh auth login --with-token`:token 经 stdin 传入;
|
|
65
76
|
* 2. `gh auth setup-git`:配置 git credential helper。
|
|
66
77
|
*
|
|
78
|
+
* 两次调用都显式开启 `ZAG_GH_WRAPPER_SKIP_TOKEN=1`(wrapper 直通原生 gh)。
|
|
67
79
|
* 任一步失败立即抛错(不重试);错误信息不含 token。
|
|
68
80
|
*/
|
|
69
81
|
export async function writeGhAuth(token: string, options: WriteGhAuthOptions = {}): Promise<void> {
|
|
@@ -71,6 +83,7 @@ export async function writeGhAuth(token: string, options: WriteGhAuthOptions = {
|
|
|
71
83
|
throw new Error('Github token 为空');
|
|
72
84
|
}
|
|
73
85
|
const spawnFn = options.spawn ?? (spawn as unknown as GhSpawn);
|
|
74
|
-
|
|
75
|
-
await runGh(spawnFn, ['auth', '
|
|
86
|
+
const env = { ...process.env, [GH_WRAPPER_SKIP_ENV]: '1' };
|
|
87
|
+
await runGh(spawnFn, ['auth', 'login', '--with-token'], token, env);
|
|
88
|
+
await runGh(spawnFn, ['auth', 'setup-git'], undefined, env);
|
|
76
89
|
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import {
|
|
8
|
+
EXIT_FAILED,
|
|
9
|
+
EXIT_NOT_BOUND,
|
|
10
|
+
EXIT_NOT_PROJECT,
|
|
11
|
+
EXIT_OK,
|
|
12
|
+
EXIT_UNAUTHORIZED,
|
|
13
|
+
MAX_TOKEN_LENGTH,
|
|
14
|
+
normalizeGitHubRemote,
|
|
15
|
+
requestProjectToken,
|
|
16
|
+
resolveGitProject,
|
|
17
|
+
runGithubTokenCommand,
|
|
18
|
+
} from './project-token.js';
|
|
19
|
+
|
|
20
|
+
const exec = promisify(execFile);
|
|
21
|
+
|
|
22
|
+
const ENV: NodeJS.ProcessEnv = {
|
|
23
|
+
ZAG_AGENT_API_ENDPOINT: 'http://agent-api:8002/',
|
|
24
|
+
ZAG_CONTROLLER_ID: 'controller-123',
|
|
25
|
+
ZAG_HOST_KEY: 'zag_k_1_host_secret',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
29
|
+
return new Response(JSON.stringify(body), {
|
|
30
|
+
status,
|
|
31
|
+
headers: { 'content-type': 'application/json' },
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fakeFetch(handler: (...args: Parameters<typeof fetch>) => Promise<Response>) {
|
|
36
|
+
return vi.fn(handler) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('normalizeGitHubRemote (T-GPT1)', () => {
|
|
40
|
+
it.each([
|
|
41
|
+
['https://github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
42
|
+
['https://github.com/Owner/Repo', 'Owner/Repo'],
|
|
43
|
+
['http://github.com/Owner/Repo/', 'Owner/Repo'],
|
|
44
|
+
['git@github.com:Owner/Repo.git', 'Owner/Repo'],
|
|
45
|
+
['ssh://git@github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
46
|
+
['git://github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
47
|
+
['https://user:pass@github.com/owner/repo.git', 'owner/repo'],
|
|
48
|
+
[' https://GITHUB.com/owner/repo ', 'owner/repo'],
|
|
49
|
+
['github.com:owner/repo', 'owner/repo'],
|
|
50
|
+
['https://github.com/owner/re.po-1_x', 'owner/re.po-1_x'],
|
|
51
|
+
])('%s → %s', (remote, expected) => {
|
|
52
|
+
expect(normalizeGitHubRemote(remote)).toBe(expected);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it.each([
|
|
56
|
+
'',
|
|
57
|
+
' ',
|
|
58
|
+
'https://gitlab.com/owner/repo.git',
|
|
59
|
+
'https://github.com/owner',
|
|
60
|
+
'https://github.com/owner/repo/extra',
|
|
61
|
+
'https://github.com/own er/repo',
|
|
62
|
+
'not-a-url',
|
|
63
|
+
])('rejects %s', (remote) => {
|
|
64
|
+
expect(normalizeGitHubRemote(remote)).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('resolveGitProject (T-GPT2)', () => {
|
|
69
|
+
let dir = '';
|
|
70
|
+
|
|
71
|
+
async function initRepo(remote?: string) {
|
|
72
|
+
dir = await mkdtemp(join(tmpdir(), 'zag-project-token-'));
|
|
73
|
+
await exec('git', ['init', '--quiet'], { cwd: dir });
|
|
74
|
+
if (remote) await exec('git', ['remote', 'add', 'origin', remote], { cwd: dir });
|
|
75
|
+
return dir;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
it('resolves owner/repo from the git origin', async () => {
|
|
79
|
+
const repo = await initRepo('git@github.com:owner/repo.git');
|
|
80
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({
|
|
81
|
+
kind: 'project',
|
|
82
|
+
repoFullName: 'owner/repo',
|
|
83
|
+
});
|
|
84
|
+
await rm(repo, { recursive: true, force: true });
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('returns not-project outside a git repository', async () => {
|
|
88
|
+
const plain = await mkdtemp(join(tmpdir(), 'zag-plain-'));
|
|
89
|
+
await expect(resolveGitProject(plain)).resolves.toEqual({ kind: 'not-project' });
|
|
90
|
+
await rm(plain, { recursive: true, force: true });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('returns not-project without an origin remote', async () => {
|
|
94
|
+
const repo = await initRepo();
|
|
95
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({ kind: 'not-project' });
|
|
96
|
+
await rm(repo, { recursive: true, force: true });
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('returns not-project for a non-github origin', async () => {
|
|
100
|
+
const repo = await initRepo('https://gitlab.com/owner/repo.git');
|
|
101
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({ kind: 'not-project' });
|
|
102
|
+
await rm(repo, { recursive: true, force: true });
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('returns not-project when git is unavailable', async () => {
|
|
106
|
+
const resolution = await resolveGitProject('/tmp', {
|
|
107
|
+
runGit: async () => null,
|
|
108
|
+
});
|
|
109
|
+
expect(resolution).toEqual({ kind: 'not-project' });
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
describe('requestProjectToken (T-GPT3)', () => {
|
|
114
|
+
it('posts the repo and returns the token', async () => {
|
|
115
|
+
const fetchFn = fakeFetch(async () =>
|
|
116
|
+
jsonResponse({ token: 'ghs_project', repoFullName: 'owner/repo', expiresAt: '2026-01-01T00:00:00Z' }),
|
|
117
|
+
);
|
|
118
|
+
const result = await requestProjectToken({
|
|
119
|
+
repoFullName: 'owner/repo',
|
|
120
|
+
env: ENV,
|
|
121
|
+
fetch: fetchFn,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
expect(result).toEqual({ kind: 'token', token: 'ghs_project' });
|
|
125
|
+
const [url, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
|
|
126
|
+
expect(url).toBe(
|
|
127
|
+
'http://agent-api:8002/internal/cloud-hosts/controller-123/github-credential',
|
|
128
|
+
);
|
|
129
|
+
expect(init).toMatchObject({
|
|
130
|
+
method: 'POST',
|
|
131
|
+
body: JSON.stringify({ repoFullName: 'owner/repo' }),
|
|
132
|
+
});
|
|
133
|
+
expect((init.headers as Record<string, string>).Authorization).toBe(
|
|
134
|
+
'Bearer zag_k_1_host_secret',
|
|
135
|
+
);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('accepts a case-insensitive echo', async () => {
|
|
139
|
+
const fetchFn = fakeFetch(async () =>
|
|
140
|
+
jsonResponse({ token: 't', repoFullName: 'OWNER/REPO' }),
|
|
141
|
+
);
|
|
142
|
+
await expect(
|
|
143
|
+
requestProjectToken({ repoFullName: 'owner/repo', env: ENV, fetch: fetchFn }),
|
|
144
|
+
).resolves.toEqual({ kind: 'token', token: 't' });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('rejects a mismatched echo', async () => {
|
|
148
|
+
const fetchFn = fakeFetch(async () =>
|
|
149
|
+
jsonResponse({ token: 't', repoFullName: 'other/repo' }),
|
|
150
|
+
);
|
|
151
|
+
const result = await requestProjectToken({
|
|
152
|
+
repoFullName: 'owner/repo',
|
|
153
|
+
env: ENV,
|
|
154
|
+
fetch: fetchFn,
|
|
155
|
+
});
|
|
156
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('rejects a missing echo (old server ignoring the body)', async () => {
|
|
160
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ token: 't' }));
|
|
161
|
+
const result = await requestProjectToken({
|
|
162
|
+
repoFullName: 'owner/repo',
|
|
163
|
+
env: ENV,
|
|
164
|
+
fetch: fetchFn,
|
|
165
|
+
});
|
|
166
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it.each([['line1\nline2'], [''], ['has space'], ['x'.repeat(MAX_TOKEN_LENGTH + 1)]])(
|
|
170
|
+
'rejects an invalid token %#',
|
|
171
|
+
async (token) => {
|
|
172
|
+
const fetchFn = fakeFetch(async () =>
|
|
173
|
+
jsonResponse({ token, repoFullName: 'owner/repo' }),
|
|
174
|
+
);
|
|
175
|
+
const result = await requestProjectToken({
|
|
176
|
+
repoFullName: 'owner/repo',
|
|
177
|
+
env: ENV,
|
|
178
|
+
fetch: fetchFn,
|
|
179
|
+
});
|
|
180
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
it('maps 404 PROJECT_NOT_BOUND to exit 4', async () => {
|
|
185
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'PROJECT_NOT_BOUND' }, 404));
|
|
186
|
+
const result = await requestProjectToken({
|
|
187
|
+
repoFullName: 'owner/repo',
|
|
188
|
+
env: ENV,
|
|
189
|
+
fetch: fetchFn,
|
|
190
|
+
});
|
|
191
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_NOT_BOUND });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('maps a plain 404 to exit 4', async () => {
|
|
195
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'NO_BINDING' }, 404));
|
|
196
|
+
const result = await requestProjectToken({
|
|
197
|
+
repoFullName: 'owner/repo',
|
|
198
|
+
env: ENV,
|
|
199
|
+
fetch: fetchFn,
|
|
200
|
+
});
|
|
201
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_NOT_BOUND });
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('maps 403 REPO_NOT_AUTHORIZED to exit 5', async () => {
|
|
205
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'REPO_NOT_AUTHORIZED' }, 403));
|
|
206
|
+
const result = await requestProjectToken({
|
|
207
|
+
repoFullName: 'owner/repo',
|
|
208
|
+
env: ENV,
|
|
209
|
+
fetch: fetchFn,
|
|
210
|
+
});
|
|
211
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_UNAUTHORIZED });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('maps 500 to exit 6 and never leaks the body', async () => {
|
|
215
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'boom-secret' }, 500));
|
|
216
|
+
const result = await requestProjectToken({
|
|
217
|
+
repoFullName: 'owner/repo',
|
|
218
|
+
env: ENV,
|
|
219
|
+
fetch: fetchFn,
|
|
220
|
+
});
|
|
221
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
222
|
+
expect(result.kind === 'error' ? result.message : '').not.toContain('boom-secret');
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it('maps invalid JSON on 200 to exit 6', async () => {
|
|
226
|
+
const fetchFn = fakeFetch(async () => new Response('not-json', { status: 200 }));
|
|
227
|
+
const result = await requestProjectToken({
|
|
228
|
+
repoFullName: 'owner/repo',
|
|
229
|
+
env: ENV,
|
|
230
|
+
fetch: fetchFn,
|
|
231
|
+
});
|
|
232
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('maps timeout to exit 6', async () => {
|
|
236
|
+
const fetchFn = fakeFetch(
|
|
237
|
+
async () =>
|
|
238
|
+
new Promise<Response>((_resolve, reject) => {
|
|
239
|
+
reject(Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }));
|
|
240
|
+
}),
|
|
241
|
+
);
|
|
242
|
+
const result = await requestProjectToken({
|
|
243
|
+
repoFullName: 'owner/repo',
|
|
244
|
+
env: ENV,
|
|
245
|
+
fetch: fetchFn,
|
|
246
|
+
});
|
|
247
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
248
|
+
expect(result.kind === 'error' ? result.message : '').toContain('超时');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('fails on missing env without calling fetch', async () => {
|
|
252
|
+
const fetchFn = fakeFetch(async () => jsonResponse({}));
|
|
253
|
+
const result = await requestProjectToken({
|
|
254
|
+
repoFullName: 'owner/repo',
|
|
255
|
+
env: {},
|
|
256
|
+
fetch: fetchFn,
|
|
257
|
+
});
|
|
258
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
259
|
+
expect(result.kind === 'error' ? result.message : '').toContain('ZAG_HOST_KEY');
|
|
260
|
+
expect(fetchFn).not.toHaveBeenCalled();
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe('runGithubTokenCommand (T-GPTC1)', () => {
|
|
265
|
+
it('writes only the token to stdout and exits 0', async () => {
|
|
266
|
+
const stdout: string[] = [];
|
|
267
|
+
const stderr: string[] = [];
|
|
268
|
+
const code = await runGithubTokenCommand({
|
|
269
|
+
resolveGitProject: async () => ({ kind: 'project', repoFullName: 'owner/repo' }),
|
|
270
|
+
requestProjectToken: async () => ({ kind: 'token', token: 'ghs_x' }),
|
|
271
|
+
stdout: (text) => stdout.push(text),
|
|
272
|
+
stderr: (text) => stderr.push(text),
|
|
273
|
+
});
|
|
274
|
+
expect(code).toBe(EXIT_OK);
|
|
275
|
+
expect(stdout.join('')).toBe('ghs_x\n');
|
|
276
|
+
expect(stderr).toEqual([]);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('exits 3 silently for non-git directories', async () => {
|
|
280
|
+
const stdout: string[] = [];
|
|
281
|
+
const stderr: string[] = [];
|
|
282
|
+
const code = await runGithubTokenCommand({
|
|
283
|
+
resolveGitProject: async () => ({ kind: 'not-project' }),
|
|
284
|
+
requestProjectToken: async () => ({ kind: 'token', token: 'unused' }),
|
|
285
|
+
stdout: (text) => stdout.push(text),
|
|
286
|
+
stderr: (text) => stderr.push(text),
|
|
287
|
+
});
|
|
288
|
+
expect(code).toBe(EXIT_NOT_PROJECT);
|
|
289
|
+
expect(stdout).toEqual([]);
|
|
290
|
+
expect(stderr).toEqual([]);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it.each([
|
|
294
|
+
[4 as const, EXIT_NOT_BOUND],
|
|
295
|
+
[5 as const, EXIT_UNAUTHORIZED],
|
|
296
|
+
[6 as const, EXIT_FAILED],
|
|
297
|
+
])('writes a single stderr line and returns %i', async (errorCode, expected) => {
|
|
298
|
+
const stdout: string[] = [];
|
|
299
|
+
const stderr: string[] = [];
|
|
300
|
+
const code = await runGithubTokenCommand({
|
|
301
|
+
resolveGitProject: async () => ({ kind: 'project', repoFullName: 'owner/repo' }),
|
|
302
|
+
requestProjectToken: async () => ({
|
|
303
|
+
kind: 'error',
|
|
304
|
+
code: errorCode,
|
|
305
|
+
message: '可读原因',
|
|
306
|
+
}),
|
|
307
|
+
stdout: (text) => stdout.push(text),
|
|
308
|
+
stderr: (text) => stderr.push(text),
|
|
309
|
+
});
|
|
310
|
+
expect(code).toBe(expected);
|
|
311
|
+
expect(stdout).toEqual([]);
|
|
312
|
+
expect(stderr).toEqual(['可读原因\n']);
|
|
313
|
+
});
|
|
314
|
+
});
|