forked from ProverCoderAI/docker-git
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-github.ts
More file actions
301 lines (280 loc) · 11.6 KB
/
auth-github.ts
File metadata and controls
301 lines (280 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import type * as CommandExecutor from "@effect/platform/CommandExecutor"
// NOTE: keep platform type imports grouped for auth flows.
import type { PlatformError } from "@effect/platform/Error"
import type * as FileSystem from "@effect/platform/FileSystem"
import type * as Path from "@effect/platform/Path"
import { Duration, Effect, Schedule } from "effect"
import type { AuthGithubLoginCommand, AuthGithubLogoutCommand, AuthGithubStatusCommand } from "../core/domain.js"
import { defaultTemplateConfig } from "../core/domain.js"
import { trimLeftChar, trimRightChar } from "../core/strings.js"
import { runDockerAuth, runDockerAuthCapture } from "../shell/docker-auth.js"
import type { AuthError } from "../shell/errors.js"
import { CommandFailedError } from "../shell/errors.js"
import { buildDockerAuthSpec, normalizeAccountLabel } from "./auth-helpers.js"
import { migrateLegacyOrchLayout } from "./auth-sync.js"
import { ensureEnvFile, parseEnvEntries, readEnvText, removeEnvKey, upsertEnvKey } from "./env-file.js"
import { ensureGhAuthImage, ghAuthDir, ghAuthRoot, ghImageName } from "./github-auth-image.js"
import { resolvePathFromCwd } from "./path-helpers.js"
import { withFsPathContext } from "./runtime.js"
import { ensureStateDotDockerGitRepo } from "./state-repo-github.js"
import { autoSyncState } from "./state-repo.js"
type GithubTokenEntry = {
readonly key: string
readonly label: string
readonly token: string
}
type GithubFsRuntime = FileSystem.FileSystem | Path.Path
type GithubRuntime = FileSystem.FileSystem | Path.Path | CommandExecutor.CommandExecutor
type EnvContext = {
readonly fs: FileSystem.FileSystem
readonly envPath: string
readonly current: string
}
const ensureGithubOrchLayout = (
cwd: string,
envGlobalPath: string
): Effect.Effect<void, PlatformError, FileSystem.FileSystem | Path.Path> =>
migrateLegacyOrchLayout(cwd, {
envGlobalPath,
envProjectPath: defaultTemplateConfig.envProjectPath,
codexAuthPath: defaultTemplateConfig.codexAuthPath,
ghAuthPath: ghAuthRoot,
claudeAuthPath: ".docker-git/.orch/auth/claude"
})
const normalizeGithubLabel = (value: string | null): string => {
const trimmed = value?.trim() ?? ""
if (trimmed.length === 0) {
return ""
}
const normalized = trimmed.toUpperCase().replaceAll(/[^A-Z0-9]+/g, "_")
const withoutLeading = trimLeftChar(normalized, "_")
const cleaned = trimRightChar(withoutLeading, "_")
return cleaned.length > 0 ? cleaned : ""
}
const tokenKey = "GITHUB_TOKEN"
const tokenPrefix = "GITHUB_TOKEN__"
const buildGithubTokenKey = (label: string | null): string => {
const normalized = normalizeGithubLabel(label)
if (normalized === "DEFAULT" || normalized.length === 0) {
return tokenKey
}
return `${tokenPrefix}${normalized}`
}
const labelFromKey = (key: string): string => key.startsWith(tokenPrefix) ? key.slice(tokenPrefix.length) : "default"
const listGithubTokens = (envText: string): ReadonlyArray<GithubTokenEntry> =>
parseEnvEntries(envText)
.filter((entry) => entry.key === tokenKey || entry.key.startsWith(tokenPrefix))
.map((entry) => ({
key: entry.key,
label: labelFromKey(entry.key),
token: entry.value
}))
.filter((entry) => entry.token.trim().length > 0)
const defaultGithubScopes = "repo,workflow,read:org"
// CHANGE: normalize GitHub scopes for gh auth login
// WHY: ensure required scopes are requested without delete_repo
// QUOTE(ТЗ): "Передай все нужные скопы"
// REF: user-request-2026-02-05-gh-scopes
// SOURCE: n/a
// FORMAT THEOREM: ∀s: normalize(s) -> scopes(s) ⊆ required
// PURITY: CORE
// EFFECT: n/a
// INVARIANT: empty input yields default scopes
// COMPLEXITY: O(n) where n = |scopes|
const normalizeGithubScopes = (value: string | null | undefined): ReadonlyArray<string> => {
const raw = value?.trim() ?? ""
const input = raw.length === 0 ? defaultGithubScopes : raw
const scopes = input
.split(/[,\s]+/g)
.map((scope) => scope.trim())
.filter((scope) => scope.length > 0 && scope !== "delete_repo")
return scopes.length === 0 ? defaultGithubScopes.split(",") : scopes
}
const withEnvContext = <A, E, R>(
envGlobalPath: string,
run: (context: EnvContext) => Effect.Effect<A, E, FileSystem.FileSystem | R>
): Effect.Effect<A, E | PlatformError, FileSystem.FileSystem | Path.Path | R> =>
withFsPathContext(({ cwd, fs, path }) =>
Effect.gen(function*(_) {
yield* _(ensureGithubOrchLayout(cwd, envGlobalPath))
const envPath = resolvePathFromCwd(path, cwd, envGlobalPath)
const current = yield* _(readEnvText(fs, envPath))
return yield* _(run({ fs, envPath, current }))
})
)
const resolveGithubTokenFromGh = (
cwd: string,
accountPath: string
): Effect.Effect<string, CommandFailedError | PlatformError, CommandExecutor.CommandExecutor> =>
runDockerAuthCapture(
buildDockerAuthSpec({
cwd,
image: ghImageName,
hostPath: accountPath,
containerPath: ghAuthDir,
env: `GH_CONFIG_DIR=${ghAuthDir}`,
args: ["auth", "token"],
interactive: false
}),
[0],
(exitCode) => new CommandFailedError({ command: "gh auth token", exitCode })
).pipe(
Effect.map((raw) => raw.trim()),
Effect.filterOrFail(
(value) => value.length > 0,
() => new CommandFailedError({ command: "gh auth token", exitCode: 1 })
)
)
const runGithubLogin = (
cwd: string,
accountPath: string,
scopes: ReadonlyArray<string>
): Effect.Effect<void, CommandFailedError | PlatformError, CommandExecutor.CommandExecutor> =>
runDockerAuth(
buildDockerAuthSpec({
cwd,
image: ghImageName,
hostPath: accountPath,
containerPath: ghAuthDir,
env: ["BROWSER=echo", `GH_CONFIG_DIR=${ghAuthDir}`],
args: [
"auth",
"login",
"--web",
"-h",
"github.com",
"-p",
"https",
...(scopes.length > 0 ? ["--scopes", scopes.join(",")] : [])
],
interactive: false
}),
[0],
(exitCode) => new CommandFailedError({ command: "gh auth login --web", exitCode })
)
const retryGithubLogin = (
effect: Effect.Effect<void, CommandFailedError | PlatformError, CommandExecutor.CommandExecutor>
): Effect.Effect<void, CommandFailedError | PlatformError, CommandExecutor.CommandExecutor> =>
effect.pipe(
Effect.tapError(() => Effect.logWarning("GH auth login failed; retrying...")),
Effect.retry(
Schedule.addDelay(
Schedule.recurs(2),
() => Duration.seconds(2)
)
)
)
const persistGithubToken = (
fs: FileSystem.FileSystem,
envPath: string,
key: string,
token: string
): Effect.Effect<void, PlatformError> =>
Effect.gen(function*(_) {
const current = yield* _(readEnvText(fs, envPath))
const nextText = upsertEnvKey(current, key, token)
yield* _(fs.writeFileString(envPath, nextText))
const label = labelFromKey(key)
yield* _(Effect.log(`GitHub token stored (${label}) in ${envPath}`))
})
const runGithubInteractiveLogin = (
cwd: string,
fs: FileSystem.FileSystem,
path: Path.Path,
envPath: string,
command: AuthGithubLoginCommand
): Effect.Effect<string, AuthError | CommandFailedError | PlatformError, GithubRuntime> =>
Effect.gen(function*(_) {
const rootPath = resolvePathFromCwd(path, cwd, ghAuthRoot)
const accountLabel = normalizeAccountLabel(command.label, "default")
const accountPath = path.join(rootPath, accountLabel)
const scopes = normalizeGithubScopes(command.scopes)
yield* _(fs.makeDirectory(accountPath, { recursive: true }))
yield* _(ensureGhAuthImage(fs, path, cwd, "gh auth"))
yield* _(Effect.log(`Starting GH auth login in container (scopes: ${scopes.join(", ")})...`))
yield* _(retryGithubLogin(runGithubLogin(cwd, accountPath, scopes)))
const resolved = yield* _(resolveGithubTokenFromGh(cwd, accountPath))
yield* _(ensureEnvFile(fs, path, envPath))
const key = buildGithubTokenKey(command.label)
yield* _(persistGithubToken(fs, envPath, key, resolved))
return resolved
})
// CHANGE: login to GitHub by persisting a token in the shared env file
// WHY: make GH_TOKEN available to all docker-git projects
// QUOTE(ТЗ): "система авторизации"
// REF: user-request-2026-01-28-auth
// SOURCE: n/a
// FORMAT THEOREM: forall t: login(t) -> env(GITHUB_TOKEN)=t ∧ cloned(~/.docker-git)
// PURITY: SHELL
// EFFECT: Effect<void, CommandFailedError | PlatformError, CommandExecutor>
// INVARIANT: token is never logged; state repo setup is best-effort
// COMPLEXITY: O(n) where n = |env|
export const authGithubLogin = (
command: AuthGithubLoginCommand
): Effect.Effect<void, AuthError | CommandFailedError | PlatformError, GithubRuntime> =>
withFsPathContext(({ cwd, fs, path }) =>
Effect.gen(function*(_) {
yield* _(ensureGithubOrchLayout(cwd, command.envGlobalPath))
const envPath = resolvePathFromCwd(path, cwd, command.envGlobalPath)
const token = command.token?.trim() ?? ""
const key = buildGithubTokenKey(command.label)
const label = labelFromKey(key)
if (token.length > 0) {
yield* _(ensureEnvFile(fs, path, envPath))
yield* _(persistGithubToken(fs, envPath, key, token))
yield* _(ensureStateDotDockerGitRepo(token))
yield* _(autoSyncState(`chore(state): auth gh ${label}`))
return
}
const resolvedToken = yield* _(runGithubInteractiveLogin(cwd, fs, path, envPath, command))
yield* _(ensureStateDotDockerGitRepo(resolvedToken))
yield* _(autoSyncState(`chore(state): auth gh ${label}`))
})
)
// CHANGE: show GitHub auth status from the shared env file
// WHY: surface current account labels without leaking tokens
// QUOTE(ТЗ): "система авторизации"
// REF: user-request-2026-01-28-auth
// SOURCE: n/a
// FORMAT THEOREM: forall env: status(env) -> labels(env)
// PURITY: SHELL
// EFFECT: Effect<void, PlatformError, FileSystem | Path>
// INVARIANT: tokens are never logged
// COMPLEXITY: O(n) where n = |env|
export const authGithubStatus = (
command: AuthGithubStatusCommand
): Effect.Effect<void, PlatformError, GithubFsRuntime> =>
withEnvContext(command.envGlobalPath, ({ current, envPath }) =>
Effect.gen(function*(_) {
const tokens = listGithubTokens(current)
if (tokens.length === 0) {
yield* _(Effect.log(`GitHub not connected (no tokens in ${envPath}).`))
return
}
const sample = tokens.slice(0, 20).map((entry) => entry.label).join(", ")
const remaining = tokens.length - Math.min(tokens.length, 20)
const suffix = remaining > 0 ? ` ... (+${remaining} more)` : ""
yield* _(Effect.log(`GitHub tokens (${tokens.length}): ${sample}${suffix}`))
}))
// CHANGE: remove GitHub auth token from the shared env file
// WHY: allow revoking tokens without editing files manually
// QUOTE(ТЗ): "система авторизации"
// REF: user-request-2026-01-28-auth
// SOURCE: n/a
// FORMAT THEOREM: forall env: logout(env) -> !hasToken(env)
// PURITY: SHELL
// EFFECT: Effect<void, PlatformError, FileSystem | Path>
// INVARIANT: only the selected token key is removed
// COMPLEXITY: O(n) where n = |env|
export const authGithubLogout = (
command: AuthGithubLogoutCommand
): Effect.Effect<void, PlatformError, GithubRuntime> =>
withEnvContext(command.envGlobalPath, ({ current, envPath, fs }) =>
Effect.gen(function*(_) {
const key = buildGithubTokenKey(command.label)
const nextText = removeEnvKey(current, key)
yield* _(fs.writeFileString(envPath, nextText))
const label = labelFromKey(key)
yield* _(Effect.log(`GitHub token removed (${label}) from ${envPath}`))
yield* _(autoSyncState(`chore(state): auth gh logout ${label}`))
}))