typeclaw 0.48.6 → 0.48.8
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/auth.schema.json +15 -1
- package/package.json +1 -1
- package/secrets.schema.json +15 -1
- package/src/agent/guard-types.ts +25 -0
- package/src/agent/guards.ts +102 -0
- package/src/agent/index.ts +33 -3
- package/src/agent/live-subagents.ts +14 -0
- package/src/agent/multimodal/read-redirect.ts +8 -9
- package/src/agent/plugin-tools.ts +283 -148
- package/src/agent/provider-error.ts +6 -1
- package/src/agent/reload-tool.ts +12 -5
- package/src/agent/retry-same-ref.ts +95 -36
- package/src/agent/session-origin.ts +13 -1
- package/src/agent/system-prompt.ts +14 -3
- package/src/agent/todo/continuation-policy.ts +3 -4
- package/src/agent/tool-file-safety.ts +36 -13
- package/src/agent/tools/channel-reply.ts +39 -2
- package/src/agent/tools/channel-send.ts +45 -2
- package/src/agent/tools/post-github-review.ts +31 -13
- package/src/agent/tools/spawn-subagent.ts +15 -0
- package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
- package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
- package/src/agent/turn-runner.ts +23 -19
- package/src/bundled-plugins/backup/git-auth.ts +7 -4
- package/src/bundled-plugins/backup/subagents.ts +1 -1
- package/src/bundled-plugins/bun-hygiene/README.md +23 -20
- package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
- package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
- package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
- package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
- package/src/bundled-plugins/github-cli-auth/git-command.ts +231 -30
- package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
- package/src/bundled-plugins/github-cli-auth/index.ts +249 -42
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
- package/src/bundled-plugins/guard/index.ts +2 -25
- package/src/bundled-plugins/guard/keys.ts +8 -0
- package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
- package/src/bundled-plugins/guard/policy.ts +1 -7
- package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
- package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
- package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
- package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
- package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
- package/src/bundled-plugins/security/policy.ts +0 -8
- package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
- package/src/channels/adapters/discord-bot.ts +2 -1
- package/src/channels/adapters/discord-classify.ts +16 -4
- package/src/channels/adapters/discord.ts +20 -8
- package/src/channels/adapters/github/dedup.ts +37 -8
- package/src/channels/adapters/github/inbound.ts +241 -46
- package/src/channels/adapters/github/review-state.ts +13 -9
- package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
- package/src/channels/adapters/slack-classify.ts +40 -5
- package/src/channels/adapters/slack.ts +3 -9
- package/src/channels/adapters/webex-bot-classify.ts +4 -33
- package/src/channels/adapters/webex-bot.ts +2 -4
- package/src/channels/adapters/webex-classify.ts +4 -33
- package/src/channels/adapters/webex-format.ts +36 -0
- package/src/channels/adapters/webex.ts +2 -4
- package/src/channels/continuation-willingness.ts +64 -39
- package/src/channels/github-rereview-guard.ts +20 -0
- package/src/channels/github-review-turn-ledger.ts +11 -1
- package/src/channels/github-review-verdict-coordinator.ts +475 -41
- package/src/channels/github-verdict-activity.ts +14 -5
- package/src/channels/persistence.ts +89 -5
- package/src/channels/router.ts +1223 -225
- package/src/channels/types.ts +21 -5
- package/src/cli/compose-stats.ts +6 -7
- package/src/cli/compose-status.ts +6 -7
- package/src/cli/compose-usage.ts +6 -7
- package/src/cli/stats.ts +6 -7
- package/src/cli/status.ts +7 -8
- package/src/cli/ui.ts +4 -4
- package/src/container/start.ts +41 -1
- package/src/cron/consumer.ts +30 -9
- package/src/cron/scheduler.ts +24 -9
- package/src/doctor/channel-checks.ts +64 -0
- package/src/doctor/report.ts +8 -8
- package/src/dreams/render.ts +2 -2
- package/src/init/dockerfile.ts +8 -1
- package/src/inspect/render.ts +2 -2
- package/src/path-safety/real-intended-path.ts +14 -1
- package/src/permissions/permissions.ts +10 -2
- package/src/permissions/resolve.ts +8 -2
- package/src/plugin/core-tool-names.ts +15 -0
- package/src/plugin/hooks.ts +37 -3
- package/src/plugin/registry.ts +7 -3
- package/src/run/index.ts +35 -15
- package/src/sandbox/build.ts +19 -3
- package/src/sandbox/policy.ts +1 -0
- package/src/secrets/export-github-cli-store.ts +158 -0
- package/src/secrets/index.ts +19 -1
- package/src/secrets/provision-github-cli-store.ts +322 -0
- package/src/secrets/schema.ts +13 -7
- package/src/secrets/storage.ts +30 -0
- package/src/shared/index.ts +2 -0
- package/src/shared/style-text.ts +13 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
- package/src/skills/typeclaw-config/SKILL.md +3 -1
- package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
- package/src/skills/typeclaw-permissions/SKILL.md +11 -22
- package/src/usage/report.ts +3 -3
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from 'node:child_process'
|
|
2
|
+
import { constants as fsConstants } from 'node:fs'
|
|
3
|
+
import { lstat, mkdtemp, open, realpath, rm, stat, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
CONTAINER_RUNTIME_HOME,
|
|
9
|
+
formatCommand,
|
|
10
|
+
mapVirtualTmpPath,
|
|
11
|
+
SESSION_TMP_ROOT,
|
|
12
|
+
sessionTmpDir,
|
|
13
|
+
type SandboxMount,
|
|
14
|
+
} from '@/sandbox'
|
|
15
|
+
|
|
16
|
+
import type { GitCommandDecision } from './git-command'
|
|
17
|
+
|
|
18
|
+
const GH_CONFIG_DIR = `${CONTAINER_RUNTIME_HOME}/.config/gh`
|
|
19
|
+
const TRUSTED_GH_EXECUTABLE = '/usr/bin/gh'
|
|
20
|
+
const GH_TOKEN_OUTPUT_LIMIT = 16 * 1024
|
|
21
|
+
const GH_TOKEN_TIMEOUT_MS = 5_000
|
|
22
|
+
const GIT_TIMEOUT_MS = 2_000
|
|
23
|
+
const GIT_STDOUT_LIMIT = 64 * 1024
|
|
24
|
+
const PROCESS_KILL_SETTLE_MS = 250
|
|
25
|
+
const GITHUB_OWNER_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/
|
|
26
|
+
const GITHUB_REPOSITORY_PATTERN = /^(?!\.\.?$)[a-z0-9._-]{1,100}$/
|
|
27
|
+
const GITHUB_URL_PATTERNS = [
|
|
28
|
+
/^https:\/\/github\.com\/([^/\s:@]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
|
|
29
|
+
/^git@github\.com:([^/\s:?#]+)\/([^/\s?#]+?)(?:\.git)?$/i,
|
|
30
|
+
/^ssh:\/\/git@github\.com\/([^/\s:?#]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i,
|
|
31
|
+
] as const
|
|
32
|
+
const AMBIENT_GH_AUTH_KEYS = [
|
|
33
|
+
'GH_TOKEN',
|
|
34
|
+
'GITHUB_TOKEN',
|
|
35
|
+
'GH_ENTERPRISE_TOKEN',
|
|
36
|
+
'GITHUB_ENTERPRISE_TOKEN',
|
|
37
|
+
'GH_HOST',
|
|
38
|
+
] as const
|
|
39
|
+
|
|
40
|
+
export type PreparedGithubStorePush = {
|
|
41
|
+
command: string
|
|
42
|
+
env: Record<string, string>
|
|
43
|
+
backingGitDir: string
|
|
44
|
+
mount: SandboxMount
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type GithubStorePushPlan = {
|
|
48
|
+
askpassPath: string
|
|
49
|
+
worktreeRoot: DirectoryIdentity
|
|
50
|
+
sourceCwd: DirectoryIdentity
|
|
51
|
+
sourceCwdSandboxPath: string
|
|
52
|
+
gitDir: DirectoryIdentity
|
|
53
|
+
commonDir: DirectoryIdentity
|
|
54
|
+
objects: DirectoryIdentity
|
|
55
|
+
objectsSandboxPath: string
|
|
56
|
+
objectFormat: 'sha1' | 'sha256'
|
|
57
|
+
shallow: ShallowMetadata
|
|
58
|
+
repo: string
|
|
59
|
+
remote: string
|
|
60
|
+
requestedRefspecs: string[]
|
|
61
|
+
refspecs: ReconstructedRefspecs
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type GhTokenCommandOptions = {
|
|
65
|
+
cmd: string[]
|
|
66
|
+
env: NodeJS.ProcessEnv
|
|
67
|
+
timeoutMs: number
|
|
68
|
+
maxStdoutBytes: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function canonicalGithubRepoFromGitUrl(raw: string): string | null {
|
|
72
|
+
const url = raw.trim()
|
|
73
|
+
for (const pattern of GITHUB_URL_PATTERNS) {
|
|
74
|
+
const match = pattern.exec(url)
|
|
75
|
+
if (match === null) continue
|
|
76
|
+
const owner = match[1]?.toLocaleLowerCase()
|
|
77
|
+
const repo = match[2]?.toLocaleLowerCase()
|
|
78
|
+
if (
|
|
79
|
+
owner === undefined ||
|
|
80
|
+
repo === undefined ||
|
|
81
|
+
!GITHUB_OWNER_PATTERN.test(owner) ||
|
|
82
|
+
!GITHUB_REPOSITORY_PATTERN.test(repo)
|
|
83
|
+
) {
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
return `${owner}/${repo}`
|
|
87
|
+
}
|
|
88
|
+
return null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type GhTokenCommandRunner = (
|
|
92
|
+
options: GhTokenCommandOptions,
|
|
93
|
+
) => Promise<{ exitCode: number; stdout: string } | null>
|
|
94
|
+
|
|
95
|
+
let ghTokenCommandRunnerForTests: GhTokenCommandRunner | undefined
|
|
96
|
+
|
|
97
|
+
export function setGhTokenCommandRunnerForTests(runner: GhTokenCommandRunner | undefined): void {
|
|
98
|
+
ghTokenCommandRunnerForTests = runner
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function resolveGithubCliStoreToken(
|
|
102
|
+
runner: GhTokenCommandRunner | undefined = undefined,
|
|
103
|
+
parentEnv: NodeJS.ProcessEnv = process.env,
|
|
104
|
+
configDir: string = GH_CONFIG_DIR,
|
|
105
|
+
): Promise<string | null> {
|
|
106
|
+
if (!(await isSafeGithubCliStore(configDir))) return null
|
|
107
|
+
const env: NodeJS.ProcessEnv = { ...parentEnv, GH_CONFIG_DIR: configDir }
|
|
108
|
+
for (const key of AMBIENT_GH_AUTH_KEYS) delete env[key]
|
|
109
|
+
|
|
110
|
+
const result = await (runner ?? ghTokenCommandRunnerForTests ?? runGhTokenCommand)({
|
|
111
|
+
cmd: [TRUSTED_GH_EXECUTABLE, 'auth', 'token', '--hostname', 'github.com'],
|
|
112
|
+
env,
|
|
113
|
+
timeoutMs: GH_TOKEN_TIMEOUT_MS,
|
|
114
|
+
maxStdoutBytes: GH_TOKEN_OUTPUT_LIMIT,
|
|
115
|
+
})
|
|
116
|
+
if (result === null || result.exitCode !== 0) return null
|
|
117
|
+
if (Buffer.byteLength(result.stdout) > GH_TOKEN_OUTPUT_LIMIT || result.stdout.includes('\0')) return null
|
|
118
|
+
|
|
119
|
+
const token = result.stdout.endsWith('\r\n')
|
|
120
|
+
? result.stdout.slice(0, -2)
|
|
121
|
+
: result.stdout.endsWith('\n')
|
|
122
|
+
? result.stdout.slice(0, -1)
|
|
123
|
+
: result.stdout
|
|
124
|
+
if (token === '' || token.trim() !== token || token.includes('\n') || token.includes('\r')) return null
|
|
125
|
+
return token
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function isSafeGithubCliStore(configDir: string): Promise<boolean> {
|
|
129
|
+
const hostsPath = join(configDir, 'hosts.yml')
|
|
130
|
+
for (const path of [dirname(dirname(configDir)), dirname(configDir), configDir, hostsPath]) {
|
|
131
|
+
try {
|
|
132
|
+
const metadata = await lstat(path)
|
|
133
|
+
const isTarget = path === hostsPath
|
|
134
|
+
if (metadata.isSymbolicLink() || (isTarget ? !metadata.isFile() : !metadata.isDirectory())) return false
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export const GH_STORE_AMBIENT_AUTH_KEYS: readonly string[] = AMBIENT_GH_AUTH_KEYS
|
|
144
|
+
|
|
145
|
+
const STORE_GIT_CONFIG: readonly [string, string][] = [
|
|
146
|
+
['core.hooksPath', '/dev/null'],
|
|
147
|
+
['core.askPass', ''],
|
|
148
|
+
['credential.helper', ''],
|
|
149
|
+
['credential.useHttpPath', 'true'],
|
|
150
|
+
['http.followRedirects', 'false'],
|
|
151
|
+
['http.sslVerify', 'true'],
|
|
152
|
+
['http.proxy', ''],
|
|
153
|
+
['protocol.allow', 'never'],
|
|
154
|
+
['protocol.https.allow', 'always'],
|
|
155
|
+
]
|
|
156
|
+
|
|
157
|
+
const CLEAN_GIT_BASE_ENV: NodeJS.ProcessEnv = {
|
|
158
|
+
PATH: process.env.PATH,
|
|
159
|
+
LANG: process.env.LANG,
|
|
160
|
+
LC_ALL: process.env.LC_ALL,
|
|
161
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
162
|
+
GIT_CONFIG_SYSTEM: '/dev/null',
|
|
163
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
164
|
+
GIT_CONFIG_PARAMETERS: '',
|
|
165
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
166
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function planGithubStorePush(
|
|
170
|
+
decision: GitCommandDecision,
|
|
171
|
+
options: { agentDir: string; sessionId: string; askpassPath: string },
|
|
172
|
+
): Promise<GithubStorePushPlan | null> {
|
|
173
|
+
if (decision.kind !== 'inject' || decision.access !== 'write') return null
|
|
174
|
+
const provenance = decision.pushProvenance
|
|
175
|
+
if (
|
|
176
|
+
provenance?.kind !== 'configured-remote' ||
|
|
177
|
+
!provenance.complete ||
|
|
178
|
+
provenance.worktreeTopLevel === null ||
|
|
179
|
+
provenance.pushUrls.length !== 1 ||
|
|
180
|
+
provenance.repoSlugs.length !== 1 ||
|
|
181
|
+
provenance.setUpstream
|
|
182
|
+
) {
|
|
183
|
+
return null
|
|
184
|
+
}
|
|
185
|
+
const repo = canonicalGithubRepoFromGitUrl(provenance.pushUrls[0] as string)
|
|
186
|
+
if (
|
|
187
|
+
repo === null ||
|
|
188
|
+
!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) ||
|
|
189
|
+
decision.repoSlug.toLocaleLowerCase() !== repo ||
|
|
190
|
+
provenance.repoSlugs[0] !== repo
|
|
191
|
+
) {
|
|
192
|
+
return null
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
try {
|
|
196
|
+
const mappedSourceCwd = mapVirtualTmpPath(options.agentDir, options.sessionId, provenance.sourceCwd)
|
|
197
|
+
const physicalSessionTmp = mappedSourceCwd === undefined ? null : await physicalSessionTmpDir(options.sessionId)
|
|
198
|
+
const worktreeRoot = await canonicalDirectory(provenance.worktreeTopLevel)
|
|
199
|
+
const sourceCwd = await canonicalDirectory(mappedSourceCwd ?? provenance.sourceCwd)
|
|
200
|
+
if (!isWithin(worktreeRoot.path, sourceCwd.path)) return null
|
|
201
|
+
if (physicalSessionTmp !== null && !isWithin(physicalSessionTmp, sourceCwd.path)) return null
|
|
202
|
+
|
|
203
|
+
const gitDirOutput = await sourceGitOutput(sourceCwd.path, ['rev-parse', '--absolute-git-dir'])
|
|
204
|
+
const commonDirOutput = await sourceGitOutput(sourceCwd.path, ['rev-parse', '--git-common-dir'])
|
|
205
|
+
const objectFormatOutput = await sourceGitOutput(sourceCwd.path, ['rev-parse', '--show-object-format'])
|
|
206
|
+
if (gitDirOutput === null || commonDirOutput === null || !isObjectFormat(objectFormatOutput)) return null
|
|
207
|
+
const gitDir = await canonicalDirectory(resolveReportedPath(sourceCwd.path, gitDirOutput))
|
|
208
|
+
const commonDir = await canonicalDirectory(resolveReportedPath(sourceCwd.path, commonDirOutput))
|
|
209
|
+
const objects = await canonicalDirectory(join(commonDir.path, 'objects'))
|
|
210
|
+
if (
|
|
211
|
+
physicalSessionTmp !== null &&
|
|
212
|
+
[worktreeRoot, gitDir, commonDir, objects].some((directory) => !isWithin(physicalSessionTmp, directory.path))
|
|
213
|
+
) {
|
|
214
|
+
return null
|
|
215
|
+
}
|
|
216
|
+
const sourceCwdSandboxPath =
|
|
217
|
+
mappedSourceCwd === undefined ? sourceCwd.path : resolve(options.agentDir, provenance.sourceCwd)
|
|
218
|
+
const objectsSandboxPath =
|
|
219
|
+
physicalSessionTmp === null ? objects.path : sandboxVisiblePath(physicalSessionTmp, objects.path)
|
|
220
|
+
if (objectsSandboxPath.includes(':') || objectsSandboxPath.includes('\n') || objectsSandboxPath.includes('\r')) {
|
|
221
|
+
return null
|
|
222
|
+
}
|
|
223
|
+
if (!(await configuredRemoteMatchesTarget(gitDir.path, provenance.remote, repo))) return null
|
|
224
|
+
const shallow = await captureShallowMetadata(sourceCwd.path, gitDir.path, commonDir.path)
|
|
225
|
+
|
|
226
|
+
const refspecs = await reconstructRefspecs({
|
|
227
|
+
gitDir: gitDir.path,
|
|
228
|
+
remote: provenance.remote,
|
|
229
|
+
requested: provenance.refspecs,
|
|
230
|
+
})
|
|
231
|
+
if (refspecs === null || refspecs.values.length === 0) return null
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
askpassPath: options.askpassPath,
|
|
235
|
+
worktreeRoot,
|
|
236
|
+
sourceCwd,
|
|
237
|
+
sourceCwdSandboxPath,
|
|
238
|
+
gitDir,
|
|
239
|
+
commonDir,
|
|
240
|
+
objects,
|
|
241
|
+
objectsSandboxPath,
|
|
242
|
+
objectFormat: objectFormatOutput,
|
|
243
|
+
shallow,
|
|
244
|
+
repo,
|
|
245
|
+
remote: provenance.remote,
|
|
246
|
+
requestedRefspecs: [...provenance.refspecs],
|
|
247
|
+
refspecs,
|
|
248
|
+
}
|
|
249
|
+
} catch {
|
|
250
|
+
return null
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export async function prepareGithubStorePush(plan: GithubStorePushPlan): Promise<PreparedGithubStorePush | null> {
|
|
255
|
+
let backingGitDir: string | null = null
|
|
256
|
+
let completed = false
|
|
257
|
+
try {
|
|
258
|
+
await assertDirectoryIdentity(plan.worktreeRoot)
|
|
259
|
+
await assertDirectoryIdentity(plan.sourceCwd)
|
|
260
|
+
await assertDirectoryIdentity(plan.gitDir)
|
|
261
|
+
await assertDirectoryIdentity(plan.commonDir)
|
|
262
|
+
await assertDirectoryIdentity(plan.objects)
|
|
263
|
+
if ((await sourceGitOutput(plan.sourceCwd.path, ['rev-parse', '--show-object-format'])) !== plan.objectFormat) {
|
|
264
|
+
return null
|
|
265
|
+
}
|
|
266
|
+
if (!(await shallowMetadataMatches(plan.shallow))) return null
|
|
267
|
+
if (!(await configuredRemoteMatchesTarget(plan.gitDir.path, plan.remote, plan.repo))) return null
|
|
268
|
+
|
|
269
|
+
const currentRefspecs = await reconstructRefspecs({
|
|
270
|
+
gitDir: plan.gitDir.path,
|
|
271
|
+
remote: plan.remote,
|
|
272
|
+
requested: plan.requestedRefspecs,
|
|
273
|
+
})
|
|
274
|
+
if (currentRefspecs === null || !sameRefspecs(plan.refspecs, currentRefspecs)) return null
|
|
275
|
+
|
|
276
|
+
backingGitDir = await mkdtemp(join(tmpdir(), 'typeclaw-gh-store-push-'))
|
|
277
|
+
if (!(await runGit(['init', '--bare', '--quiet', `--object-format=${plan.objectFormat}`, backingGitDir])).ok)
|
|
278
|
+
return null
|
|
279
|
+
if (plan.shallow.file !== null) {
|
|
280
|
+
await writeFile(join(backingGitDir, 'shallow'), plan.shallow.file.content, { flag: 'wx', mode: 0o444 })
|
|
281
|
+
}
|
|
282
|
+
const alternateEnv = { GIT_ALTERNATE_OBJECT_DIRECTORIES: plan.objects.path }
|
|
283
|
+
for (const ref of currentRefspecs.refs) {
|
|
284
|
+
const updated = await runGit(['--git-dir', backingGitDir, 'update-ref', ref.name, ref.oid], alternateEnv)
|
|
285
|
+
if (!updated.ok) return null
|
|
286
|
+
}
|
|
287
|
+
if (currentRefspecs.head !== null) {
|
|
288
|
+
const head = await runGit(
|
|
289
|
+
['--git-dir', backingGitDir, 'symbolic-ref', 'HEAD', currentRefspecs.head],
|
|
290
|
+
alternateEnv,
|
|
291
|
+
)
|
|
292
|
+
if (!head.ok) return null
|
|
293
|
+
}
|
|
294
|
+
await assertDirectoryIdentity(plan.objects)
|
|
295
|
+
if ((await sourceGitOutput(plan.sourceCwd.path, ['rev-parse', '--show-object-format'])) !== plan.objectFormat) {
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
if (!(await shallowMetadataMatches(plan.shallow))) return null
|
|
299
|
+
|
|
300
|
+
const virtualGitDir = `/tmp/${basename(backingGitDir)}`
|
|
301
|
+
const destination = `https://github.com/${plan.repo}.git`
|
|
302
|
+
const command = formatCommand([
|
|
303
|
+
'/usr/bin/git',
|
|
304
|
+
'--git-dir',
|
|
305
|
+
virtualGitDir,
|
|
306
|
+
'push',
|
|
307
|
+
destination,
|
|
308
|
+
...currentRefspecs.values,
|
|
309
|
+
])
|
|
310
|
+
const configEnv = Object.fromEntries(
|
|
311
|
+
STORE_GIT_CONFIG.flatMap(([key, value], index) => [
|
|
312
|
+
[`GIT_CONFIG_KEY_${index}`, key],
|
|
313
|
+
[`GIT_CONFIG_VALUE_${index}`, key === 'core.askPass' ? plan.askpassPath : value],
|
|
314
|
+
]),
|
|
315
|
+
)
|
|
316
|
+
completed = true
|
|
317
|
+
return {
|
|
318
|
+
command,
|
|
319
|
+
backingGitDir,
|
|
320
|
+
mount: { type: 'ro-bind', source: backingGitDir, dest: virtualGitDir },
|
|
321
|
+
env: {
|
|
322
|
+
GIT_DIR: virtualGitDir,
|
|
323
|
+
GIT_ALTERNATE_OBJECT_DIRECTORIES: plan.objectsSandboxPath,
|
|
324
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
325
|
+
GIT_CONFIG_SYSTEM: '/dev/null',
|
|
326
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
327
|
+
GIT_CONFIG_PARAMETERS: '',
|
|
328
|
+
GIT_ALLOW_PROTOCOL: 'https',
|
|
329
|
+
GIT_CONFIG_COUNT: String(STORE_GIT_CONFIG.length),
|
|
330
|
+
...configEnv,
|
|
331
|
+
HTTP_PROXY: '',
|
|
332
|
+
HTTPS_PROXY: '',
|
|
333
|
+
ALL_PROXY: '',
|
|
334
|
+
http_proxy: '',
|
|
335
|
+
https_proxy: '',
|
|
336
|
+
all_proxy: '',
|
|
337
|
+
},
|
|
338
|
+
}
|
|
339
|
+
} catch {
|
|
340
|
+
return null
|
|
341
|
+
} finally {
|
|
342
|
+
if (backingGitDir !== null && !completed) await rm(backingGitDir, { recursive: true, force: true })
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export async function cleanupPreparedGithubStorePush(path: string): Promise<void> {
|
|
347
|
+
await rm(path, { recursive: true, force: true })
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export type DirectoryIdentity = { path: string; dev: number; ino: number }
|
|
351
|
+
export type ShallowMetadata = {
|
|
352
|
+
path: string
|
|
353
|
+
parent: DirectoryIdentity
|
|
354
|
+
file: null | { dev: number; ino: number; content: string }
|
|
355
|
+
}
|
|
356
|
+
export type ReconstructedRefspecs = {
|
|
357
|
+
values: string[]
|
|
358
|
+
refs: Array<{ name: string; oid: string }>
|
|
359
|
+
head: string | null
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function sameRefspecs(left: ReconstructedRefspecs, right: ReconstructedRefspecs): boolean {
|
|
363
|
+
if (
|
|
364
|
+
left.head !== right.head ||
|
|
365
|
+
left.values.length !== right.values.length ||
|
|
366
|
+
left.refs.length !== right.refs.length
|
|
367
|
+
) {
|
|
368
|
+
return false
|
|
369
|
+
}
|
|
370
|
+
if (left.values.some((value, index) => value !== right.values[index])) return false
|
|
371
|
+
return left.refs.every((ref, index) => {
|
|
372
|
+
const candidate = right.refs[index]
|
|
373
|
+
return candidate !== undefined && ref.name === candidate.name && ref.oid === candidate.oid
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function canonicalDirectory(path: string): Promise<DirectoryIdentity> {
|
|
378
|
+
const canonical = await realpath(path)
|
|
379
|
+
const linkInfo = await lstat(canonical)
|
|
380
|
+
const info = await stat(canonical)
|
|
381
|
+
if (linkInfo.isSymbolicLink() || !info.isDirectory()) throw new Error('not a stable directory')
|
|
382
|
+
return { path: canonical, dev: info.dev, ino: info.ino }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function assertDirectoryIdentity(expected: DirectoryIdentity): Promise<void> {
|
|
386
|
+
const canonical = await realpath(expected.path)
|
|
387
|
+
const info = await stat(canonical)
|
|
388
|
+
if (canonical !== expected.path || !info.isDirectory() || info.dev !== expected.dev || info.ino !== expected.ino) {
|
|
389
|
+
throw new Error('directory identity changed')
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function captureShallowMetadata(sourceCwd: string, gitDir: string, commonDir: string): Promise<ShallowMetadata> {
|
|
394
|
+
const reported = await sourceGitOutput(sourceCwd, ['rev-parse', '--git-path', 'shallow'])
|
|
395
|
+
if (reported === null) throw new Error('could not resolve shallow metadata')
|
|
396
|
+
const unresolved = resolveReportedPath(sourceCwd, reported)
|
|
397
|
+
const parent = await canonicalDirectory(dirname(unresolved))
|
|
398
|
+
if (!isWithin(gitDir, parent.path) && !isWithin(commonDir, parent.path)) {
|
|
399
|
+
throw new Error('shallow metadata escaped the repository')
|
|
400
|
+
}
|
|
401
|
+
const path = join(parent.path, basename(unresolved))
|
|
402
|
+
return { path, parent, file: await readShallowFile(path) }
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function shallowMetadataMatches(expected: ShallowMetadata): Promise<boolean> {
|
|
406
|
+
try {
|
|
407
|
+
await assertDirectoryIdentity(expected.parent)
|
|
408
|
+
const current = await readShallowFile(expected.path)
|
|
409
|
+
if (expected.file === null || current === null) return expected.file === current
|
|
410
|
+
return (
|
|
411
|
+
expected.file.dev === current.dev &&
|
|
412
|
+
expected.file.ino === current.ino &&
|
|
413
|
+
expected.file.content === current.content
|
|
414
|
+
)
|
|
415
|
+
} catch {
|
|
416
|
+
return false
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function readShallowFile(path: string): Promise<ShallowMetadata['file']> {
|
|
421
|
+
let before: Awaited<ReturnType<typeof lstat>>
|
|
422
|
+
try {
|
|
423
|
+
before = await lstat(path)
|
|
424
|
+
} catch (error) {
|
|
425
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
|
|
426
|
+
throw error
|
|
427
|
+
}
|
|
428
|
+
if (before.isSymbolicLink() || !before.isFile()) throw new Error('unsafe shallow metadata')
|
|
429
|
+
|
|
430
|
+
const handle = await open(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
|
|
431
|
+
try {
|
|
432
|
+
const opened = await handle.stat()
|
|
433
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
|
|
434
|
+
throw new Error('shallow metadata identity changed')
|
|
435
|
+
}
|
|
436
|
+
const content = await handle.readFile('utf8')
|
|
437
|
+
if (!isValidShallowContent(content)) throw new Error('malformed shallow metadata')
|
|
438
|
+
return { dev: opened.dev, ino: opened.ino, content }
|
|
439
|
+
} finally {
|
|
440
|
+
await handle.close()
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function isValidShallowContent(content: string): boolean {
|
|
445
|
+
if (content === '' || content.includes('\0') || content.includes('\r')) return false
|
|
446
|
+
const lines = (content.endsWith('\n') ? content.slice(0, -1) : content).split('\n')
|
|
447
|
+
if (lines.some((line) => !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(line))) return false
|
|
448
|
+
return lines.every((line) => line.length === lines[0]?.length)
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function isWithin(parent: string, child: string): boolean {
|
|
452
|
+
const rel = relative(parent, child)
|
|
453
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
async function physicalSessionTmpDir(sessionId: string): Promise<string> {
|
|
457
|
+
const lexical = sessionTmpDir(sessionId)
|
|
458
|
+
if (!isWithin(SESSION_TMP_ROOT, lexical)) throw new Error('session id escaped the session tmp root')
|
|
459
|
+
return join(await realpath('/tmp'), relative('/tmp', lexical))
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function sandboxVisiblePath(physicalSessionTmp: string, physicalPath: string): string {
|
|
463
|
+
if (physicalPath === physicalSessionTmp) return '/tmp'
|
|
464
|
+
if (!isWithin(physicalSessionTmp, physicalPath)) throw new Error('path escaped the session tmp root')
|
|
465
|
+
return join('/tmp', relative(physicalSessionTmp, physicalPath))
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function isObjectFormat(value: string | null): value is 'sha1' | 'sha256' {
|
|
469
|
+
return value === 'sha1' || value === 'sha256'
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function resolveReportedPath(cwd: string, reported: string): string {
|
|
473
|
+
if (reported === '' || reported.includes('\0') || reported.includes('\n') || reported.includes('\r')) {
|
|
474
|
+
throw new Error('invalid git path')
|
|
475
|
+
}
|
|
476
|
+
return isAbsolute(reported) ? reported : resolve(cwd, reported)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async function reconstructRefspecs(options: {
|
|
480
|
+
gitDir: string
|
|
481
|
+
remote: string
|
|
482
|
+
requested: readonly string[]
|
|
483
|
+
}): Promise<ReconstructedRefspecs | null> {
|
|
484
|
+
let requested = [...options.requested]
|
|
485
|
+
if (requested.length === 0) {
|
|
486
|
+
const configured = await sourceGitResult(options.gitDir, ['config', '--get-all', `remote.${options.remote}.push`])
|
|
487
|
+
if (configured.ok && configured.stdout.trim() !== '') {
|
|
488
|
+
requested = configured.stdout.trim().split(/\r?\n/)
|
|
489
|
+
} else if (configured.code !== 1) {
|
|
490
|
+
return null
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
let head: string | null = null
|
|
495
|
+
if (requested.length === 0) {
|
|
496
|
+
head = await sourceGitDirOutput(options.gitDir, ['symbolic-ref', '-q', 'HEAD'])
|
|
497
|
+
if (head === null || !head.startsWith('refs/heads/')) return null
|
|
498
|
+
const modeResult = await sourceGitResult(options.gitDir, ['config', '--get', 'push.default'])
|
|
499
|
+
const mode = modeResult.ok ? modeResult.stdout.trim() : 'simple'
|
|
500
|
+
if (modeResult.code !== 0 && modeResult.code !== 1) return null
|
|
501
|
+
if (mode === 'nothing' || mode === 'matching') return null
|
|
502
|
+
if (mode === 'upstream' || mode === 'simple' || mode === '') {
|
|
503
|
+
const branch = head.slice('refs/heads/'.length)
|
|
504
|
+
const branchRemote = await sourceGitDirOutput(options.gitDir, ['config', '--get', `branch.${branch}.remote`])
|
|
505
|
+
const merge = await sourceGitDirOutput(options.gitDir, ['config', '--get', `branch.${branch}.merge`])
|
|
506
|
+
if (branchRemote !== options.remote || merge === null || !merge.startsWith('refs/heads/')) return null
|
|
507
|
+
if (mode !== 'upstream' && merge.slice('refs/heads/'.length) !== branch) return null
|
|
508
|
+
requested = [`${head}:${merge}`]
|
|
509
|
+
} else if (mode === 'current') {
|
|
510
|
+
requested = [`${head}:${head}`]
|
|
511
|
+
} else {
|
|
512
|
+
return null
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const refs = new Map<string, string>()
|
|
517
|
+
const values: string[] = []
|
|
518
|
+
for (const raw of requested) {
|
|
519
|
+
const reconstructed = await reconstructOneRefspec(options.gitDir, raw)
|
|
520
|
+
if (reconstructed === null) return null
|
|
521
|
+
values.push(reconstructed.value)
|
|
522
|
+
if (reconstructed.ref !== null) refs.set(reconstructed.ref.name, reconstructed.ref.oid)
|
|
523
|
+
if (reconstructed.head !== null) head = reconstructed.head
|
|
524
|
+
}
|
|
525
|
+
return { values, refs: [...refs].map(([name, oid]) => ({ name, oid })), head }
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function reconstructOneRefspec(
|
|
529
|
+
gitDir: string,
|
|
530
|
+
raw: string,
|
|
531
|
+
): Promise<{ value: string; ref: { name: string; oid: string } | null; head: string | null } | null> {
|
|
532
|
+
if (raw === '' || raw.includes('\n') || raw.includes('\r') || raw.includes('\0') || raw.includes('*')) return null
|
|
533
|
+
const force = raw.startsWith('+')
|
|
534
|
+
const body = force ? raw.slice(1) : raw
|
|
535
|
+
const colon = body.indexOf(':')
|
|
536
|
+
if (colon !== body.lastIndexOf(':')) return null
|
|
537
|
+
const source = colon === -1 ? body : body.slice(0, colon)
|
|
538
|
+
const requestedDestination = colon === -1 ? '' : body.slice(colon + 1)
|
|
539
|
+
if (source === '') {
|
|
540
|
+
const destination = await normalizeDestination(gitDir, requestedDestination)
|
|
541
|
+
return destination === null ? null : { value: `:${destination}`, ref: null, head: null }
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
let sourceRef: string
|
|
545
|
+
let head: string | null = null
|
|
546
|
+
if (source === 'HEAD') {
|
|
547
|
+
const resolvedHead = await sourceGitDirOutput(gitDir, ['symbolic-ref', '-q', 'HEAD'])
|
|
548
|
+
if (resolvedHead === null || !resolvedHead.startsWith('refs/heads/')) return null
|
|
549
|
+
sourceRef = resolvedHead
|
|
550
|
+
head = resolvedHead
|
|
551
|
+
} else if (source.startsWith('refs/heads/') || source.startsWith('refs/tags/')) {
|
|
552
|
+
sourceRef = source
|
|
553
|
+
} else if (/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(source)) {
|
|
554
|
+
const symbolic = await sourceGitDirOutput(gitDir, ['rev-parse', '--symbolic-full-name', '--verify', source])
|
|
555
|
+
if (symbolic === null || (!symbolic.startsWith('refs/heads/') && !symbolic.startsWith('refs/tags/'))) return null
|
|
556
|
+
sourceRef = symbolic
|
|
557
|
+
} else {
|
|
558
|
+
return null
|
|
559
|
+
}
|
|
560
|
+
if (!(await validRef(sourceRef))) return null
|
|
561
|
+
const oid = await sourceGitDirOutput(gitDir, ['rev-parse', '--verify', `${sourceRef}^{object}`])
|
|
562
|
+
if (oid === null || !/^[0-9a-f]{40,64}$/i.test(oid)) return null
|
|
563
|
+
const destination = await normalizeDestination(
|
|
564
|
+
gitDir,
|
|
565
|
+
requestedDestination === '' ? sourceRef : requestedDestination,
|
|
566
|
+
sourceRef.startsWith('refs/tags/') ? 'tags' : 'heads',
|
|
567
|
+
)
|
|
568
|
+
if (destination === null) return null
|
|
569
|
+
return {
|
|
570
|
+
value: `${force ? '+' : ''}${sourceRef}:${destination}`,
|
|
571
|
+
ref: { name: sourceRef, oid },
|
|
572
|
+
head,
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
async function normalizeDestination(gitDir: string, raw: string, namespace?: 'heads' | 'tags'): Promise<string | null> {
|
|
577
|
+
if (!raw.startsWith('refs/') && namespace === undefined) return null
|
|
578
|
+
const destination = raw.startsWith('refs/') ? raw : `refs/${namespace}/${raw}`
|
|
579
|
+
return (await validRef(destination, gitDir)) ? destination : null
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async function validRef(ref: string, gitDir?: string): Promise<boolean> {
|
|
583
|
+
const result = await runGit([...(gitDir === undefined ? [] : ['--git-dir', gitDir]), 'check-ref-format', ref])
|
|
584
|
+
return result.ok
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async function sourceGitOutput(cwd: string, args: string[]): Promise<string | null> {
|
|
588
|
+
const result = await runGit(['-C', cwd, ...args])
|
|
589
|
+
return result.ok ? singleLine(result.stdout) : null
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async function sourceGitDirOutput(gitDir: string, args: string[]): Promise<string | null> {
|
|
593
|
+
const result = await sourceGitResult(gitDir, args)
|
|
594
|
+
return result.ok ? singleLine(result.stdout) : null
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
async function sourceGitResult(gitDir: string, args: string[]): Promise<GitRunResult> {
|
|
598
|
+
return await runGit(['--git-dir', gitDir, ...args])
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async function configuredRemoteMatchesTarget(gitDir: string, remote: string, repo: string): Promise<boolean> {
|
|
602
|
+
const result = await sourceGitResult(gitDir, ['remote', 'get-url', '--push', '--all', remote])
|
|
603
|
+
if (!result.ok) return false
|
|
604
|
+
const urls = result.stdout.trim().split(/\r?\n/).filter(Boolean)
|
|
605
|
+
return urls.length === 1 && canonicalGithubRepoFromGitUrl(urls[0] as string) === repo
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function singleLine(output: string): string | null {
|
|
609
|
+
const trimmed = output.trim()
|
|
610
|
+
return trimmed === '' || trimmed.includes('\n') || trimmed.includes('\r') || trimmed.includes('\0') ? null : trimmed
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export type GitRunResult = { ok: boolean; code: number; stdout: string }
|
|
614
|
+
|
|
615
|
+
export type BoundedGitCommandOptions = {
|
|
616
|
+
executable: string
|
|
617
|
+
args: string[]
|
|
618
|
+
env: NodeJS.ProcessEnv
|
|
619
|
+
timeoutMs: number
|
|
620
|
+
maxStdoutBytes: number
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async function runGit(args: string[], extraEnv: NodeJS.ProcessEnv = {}): Promise<GitRunResult> {
|
|
624
|
+
return await runBoundedGitCommand({
|
|
625
|
+
executable: '/usr/bin/git',
|
|
626
|
+
args,
|
|
627
|
+
env: { ...CLEAN_GIT_BASE_ENV, ...extraEnv },
|
|
628
|
+
timeoutMs: GIT_TIMEOUT_MS,
|
|
629
|
+
maxStdoutBytes: GIT_STDOUT_LIMIT,
|
|
630
|
+
})
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
export async function runBoundedGitCommand(options: BoundedGitCommandOptions): Promise<GitRunResult> {
|
|
634
|
+
return await new Promise((resolveResult) => {
|
|
635
|
+
const child = spawn(options.executable, options.args, {
|
|
636
|
+
detached: process.platform !== 'win32',
|
|
637
|
+
env: options.env,
|
|
638
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
639
|
+
})
|
|
640
|
+
const chunks: Buffer[] = []
|
|
641
|
+
let bytes = 0
|
|
642
|
+
let settled = false
|
|
643
|
+
let terminated = false
|
|
644
|
+
let settleTimer: ReturnType<typeof setTimeout> | undefined
|
|
645
|
+
let timeoutTimer: ReturnType<typeof setTimeout> | undefined
|
|
646
|
+
const finish = (result: GitRunResult): void => {
|
|
647
|
+
if (settled) return
|
|
648
|
+
settled = true
|
|
649
|
+
if (timeoutTimer !== undefined) clearTimeout(timeoutTimer)
|
|
650
|
+
if (settleTimer !== undefined) clearTimeout(settleTimer)
|
|
651
|
+
resolveResult(result)
|
|
652
|
+
}
|
|
653
|
+
const terminate = (): void => {
|
|
654
|
+
if (settleTimer !== undefined || settled) return
|
|
655
|
+
terminated = true
|
|
656
|
+
killChildProcessGroup(child)
|
|
657
|
+
settleTimer = setTimeout(() => finish({ ok: false, code: -1, stdout: '' }), PROCESS_KILL_SETTLE_MS)
|
|
658
|
+
}
|
|
659
|
+
timeoutTimer = setTimeout(terminate, options.timeoutMs)
|
|
660
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
661
|
+
bytes += chunk.length
|
|
662
|
+
if (bytes <= options.maxStdoutBytes) chunks.push(chunk)
|
|
663
|
+
else {
|
|
664
|
+
terminate()
|
|
665
|
+
}
|
|
666
|
+
})
|
|
667
|
+
child.on('error', () => finish({ ok: false, code: -1, stdout: '' }))
|
|
668
|
+
child.on('close', (code) => {
|
|
669
|
+
if (terminated) return finish({ ok: false, code: -1, stdout: '' })
|
|
670
|
+
const exitCode = code ?? -1
|
|
671
|
+
finish({
|
|
672
|
+
ok: exitCode === 0 && bytes <= options.maxStdoutBytes,
|
|
673
|
+
code: exitCode,
|
|
674
|
+
stdout: Buffer.concat(chunks).toString('utf8'),
|
|
675
|
+
})
|
|
676
|
+
})
|
|
677
|
+
})
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const runGhTokenCommand: GhTokenCommandRunner = async (options) =>
|
|
681
|
+
await new Promise((resolve) => {
|
|
682
|
+
const child = spawn(options.cmd[0] as string, options.cmd.slice(1), {
|
|
683
|
+
detached: process.platform !== 'win32',
|
|
684
|
+
env: options.env,
|
|
685
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
686
|
+
})
|
|
687
|
+
const chunks: Buffer[] = []
|
|
688
|
+
let bytes = 0
|
|
689
|
+
let overflow = false
|
|
690
|
+
let settled = false
|
|
691
|
+
let settleTimer: ReturnType<typeof setTimeout> | undefined
|
|
692
|
+
let timeoutTimer: ReturnType<typeof setTimeout> | undefined
|
|
693
|
+
const finish = (value: { exitCode: number; stdout: string } | null): void => {
|
|
694
|
+
if (settled) return
|
|
695
|
+
settled = true
|
|
696
|
+
if (timeoutTimer !== undefined) clearTimeout(timeoutTimer)
|
|
697
|
+
if (settleTimer !== undefined) clearTimeout(settleTimer)
|
|
698
|
+
resolve(value)
|
|
699
|
+
}
|
|
700
|
+
const terminate = (): void => {
|
|
701
|
+
if (settleTimer !== undefined || settled) return
|
|
702
|
+
killChildProcessGroup(child)
|
|
703
|
+
settleTimer = setTimeout(() => finish(null), PROCESS_KILL_SETTLE_MS)
|
|
704
|
+
}
|
|
705
|
+
timeoutTimer = setTimeout(terminate, options.timeoutMs)
|
|
706
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
707
|
+
bytes += chunk.length
|
|
708
|
+
if (bytes > options.maxStdoutBytes) {
|
|
709
|
+
overflow = true
|
|
710
|
+
terminate()
|
|
711
|
+
return
|
|
712
|
+
}
|
|
713
|
+
chunks.push(chunk)
|
|
714
|
+
})
|
|
715
|
+
child.on('error', () => finish(null))
|
|
716
|
+
child.on('close', (code) => {
|
|
717
|
+
if (overflow || code === null) finish(null)
|
|
718
|
+
else finish({ exitCode: code, stdout: Buffer.concat(chunks).toString('utf8') })
|
|
719
|
+
})
|
|
720
|
+
})
|
|
721
|
+
|
|
722
|
+
function killChildProcessGroup(child: ChildProcess): void {
|
|
723
|
+
if (process.platform !== 'win32' && child.pid !== undefined) {
|
|
724
|
+
try {
|
|
725
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
726
|
+
return
|
|
727
|
+
} catch {
|
|
728
|
+
child.kill('SIGKILL')
|
|
729
|
+
return
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
child.kill('SIGKILL')
|
|
733
|
+
}
|