Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ForgejoCli.ts

960 lines36.0 KB

1import * as Cause from "effect/Cause";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Predicate from "effect/Predicate";
8import * as Schema from "effect/Schema";
9import * as Result from "effect/Result";
10import * as Clock from "effect/Clock";
11import * as FileSystem from "effect/FileSystem";
12import * as Semaphore from "effect/Semaphore";
13// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
14import * as NodePath from "node:path";
15import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest } from "effect/http";
16import { ChildProcessSpawner } from "effect/process";
17import { VcsProcessExitError } from "@t3tools/contracts";
18import { decodeJsonResult } from "@t3tools/shared/schemaJson";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
21import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
22import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
23​
24// A Gitea list page can hold 50 pull request bodies; gt's output is otherwise capped at 1 MB.
25const API_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
26​
27const UNTRUSTED_CERTIFICATE_CODES = new Set([
28 "DEPTH_ZERO_SELF_SIGNED_CERT",
29 "SELF_SIGNED_CERT_IN_CHAIN",
30 "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
31 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
32]);
33​
34// Node's fetch wraps TLS and socket error codes inside generic TypeErrors.
35function nodeErrorCode(cause: unknown): string | undefined {
36 let current = cause;
37 for (let depth = 0; depth < 4 && current !== undefined && current !== null; depth += 1) {
38 if (
39 Predicate.hasProperty(current, "code") &&
40 typeof current.code === "string" &&
41 /^[A-Z0-9_]{1,64}$/.test(current.code)
42 ) {
43 return current.code;
44 }
45 current = Predicate.hasProperty(current, "cause") ? current.cause : undefined;
46 }
47 return undefined;
49​
50// Keep fj transport details bounded to failure kind or Node code so tokens never leak.
51function describeFjRequestFailure(error: unknown): string {
52 if (Cause.isTimeoutError(error)) return "Forgejo API request timed out.";
53 if (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") {
54 const code = nodeErrorCode(error.reason.cause);
55 if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) {
56 return `Forgejo TLS certificate is not trusted (${code}). If this server uses a private CA, add that CA to NODE_EXTRA_CA_CERTS.`;
57 }
58 if (code !== undefined) return `Forgejo API request failed (${code}).`;
59 }
60 return "Forgejo API request failed.";
62​
63const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
64const isVcsProcessExitError = Schema.is(VcsProcessExitError);
65​
66export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
67 command: Schema.Literals(["fj", "gt"]),
68 cwd: Schema.String,
69 detail: Schema.String,
70 userFacingDetail: Schema.optional(Schema.String),
71 reason: Schema.optional(
72 Schema.Literals([
73 "missing-cli",
74 // The executable on PATH is another program of the CLI's name.
75 "wrong-cli",
76 "authentication",
77 "forbidden",
78 "not-found",
79 "rate-limit",
80 "invalid-response",
81 ]),
82 ),
83 httpStatus: Schema.optional(Schema.Int),
84 cause: Schema.optional(Schema.Defect()),
85}) {}
86​
87export const ForgejoLoginSchema = Schema.Struct({
88 name: Schema.String,
89 url: Schema.String,
90 ssh_host: Schema.optional(Schema.String),
91 user: Schema.String,
92 default: Schema.String,
93});
94​
95/** The fields of `gt auth status --json` that say which account each instance uses. */
96export const GT_ACCOUNT_FIELDS = "host,user,active";
97​
98const GtAccountsSchema = Schema.Array(
99 Schema.Struct({
100 host: Schema.String,
101 user: Schema.String,
102 active: Schema.Boolean,
103 verified: Schema.optional(Schema.NullOr(Schema.Boolean)),
104 error: Schema.optional(Schema.NullOr(Schema.String)),
105 }),
106);
107​
108/** Undefined for anything but gt's JSON; signed out, gt prints an empty list. */
109export function parseGtAccounts(raw: string) {
110 const decoded = decodeJsonResult(GtAccountsSchema)(raw);
111 return Result.isSuccess(decoded) ? decoded.success : undefined;
113​
114export function parseForgejoLogins(raw: string): ReadonlyArray<typeof ForgejoLoginSchema.Type> {
115 return (parseGtAccounts(raw) ?? []).map((account) => ({
116 name: account.user,
117 url: account.host,
118 user: account.user,
119 default: String(account.active),
120 }));
122​
123export const ForgejoKeysSchema = Schema.Struct({
124 hosts: Schema.Record(
125 Schema.String,
126 Schema.Struct({
127 type: Schema.Literals(["Application", "OAuth"]),
128 token: Schema.String,
129 }),
130 ),
131 aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
132});
133​
134const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
135​
136function forgejoKeysPaths(input: {
137 readonly platform: string;
138 readonly home: string;
139 readonly dataHome?: string;
140 readonly appData?: string;
141}) {
142 if (input.platform === "darwin")
143 return ["forgejo-cli", "Cyborus"].map((organization) =>
144 NodePath.join(
145 input.home,
146 "Library",
147 "Application Support",
148 `${organization}.forgejo-cli`,
149 "keys.json",
150 ),
151 );
152 if (input.platform === "win32")
153 return ["forgejo-cli", "Cyborus"].map((organization) =>
154 NodePath.win32.join(
155 input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
156 organization,
157 "forgejo-cli",
158 "data",
159 "keys.json",
160 ),
161 );
162 return [
163 NodePath.join(
164 input.dataHome && NodePath.isAbsolute(input.dataHome)
165 ? input.dataHome
166 : NodePath.join(input.home, ".local", "share"),
167 "forgejo-cli",
168 "keys.json",
169 ),
170 ];
172​
173export interface ForgejoRepositoryInput {
174 readonly cwd: string;
175 readonly context?: SourceControlProviderContext;
176 readonly repository?: string;
177 readonly reference?: string;
178 readonly host?: string;
180​
181export interface ForgejoRepository {
182 readonly command?: "fj" | "gt";
183 readonly login: string;
184 readonly repository: string;
185 readonly baseUrl: string;
187​
188export interface ForgejoApiInput extends ForgejoRepositoryInput {
189 readonly path: string;
190 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
191 readonly body?: unknown;
193​
194export class ForgejoCli extends Context.Service<
195 ForgejoCli,
196 {
197 readonly execute: (input: {
198 readonly command?: "fj" | "gt";
199 readonly cwd: string;
200 readonly args: ReadonlyArray<string>;
201 readonly stdin?: string;
202 readonly allowNonZeroExit?: boolean;
203 readonly timeoutMs?: number;
204 readonly maxOutputBytes?: number;
205 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
206 readonly listLogins?: (input: {
207 readonly cwd: string;
208 readonly command: "fj" | "gt";
209 readonly remoteUrl?: string;
210 }) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
211 readonly getAccount?: (input: {
212 readonly cwd: string;
213 readonly baseUrl: string;
214 }) => Effect.Effect<string, ForgejoCliError>;
215 readonly resolveRepository: (
216 input: ForgejoRepositoryInput,
217 ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
218 readonly api: (
219 input: ForgejoApiInput,
220 ) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
221 }
222>()("@t3tools/source-control-forgejo/server/ForgejoCli") {}
223​
224export const NO_DEFAULT_GT_SERVER =
225 "Several gt servers are signed in and gt's default server has no account. Choose one with `gt config set default_host <server-url>`.";
226​
227/**
228 * The gt login a repository named without its server goes to, as it went to tea's default
229 * login: an account on gt's default instance, else on the only instance signed in.
230 */
231export function defaultGtLogin(
232 logins: ReadonlyArray<typeof ForgejoLoginSchema.Type>,
233 defaultHost: string,
234) {
235 const server = (url: string) => url.replace(/\/+$/, "").toLowerCase();
236 const onDefault = logins.filter((login) => server(login.url) === server(defaultHost));
237 const candidates = onDefault.length > 0 ? onDefault : logins;
238 return new Set(candidates.map((login) => server(login.url))).size === 1
239 ? (candidates.find((login) => login.default === "true") ?? candidates[0])
240 : undefined;
242​
243/** Selects the account a resolved repository belongs to; an environment token names no user. */
244export const gtAccountArgs = (repository: Pick<ForgejoRepository, "login" | "baseUrl">) => [
245 "--host",
246 repository.baseUrl,
247 ...(repository.login ? ["--user", repository.login] : []),
248];
249​
250export function parseForgejoRemote(value: string) {
251 if (/^(?:https?|ssh):\/\//i.test(value)) {
252 try {
253 const url = new URL(value);
254 return {
255 host: url.host.toLowerCase(),
256 hostname: url.hostname.toLowerCase(),
257 ssh: url.protocol === "ssh:",
258 path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
259 };
260 } catch {
261 return null;
262 }
263 }
264 // SCP remotes may omit the username; URL treats these as a custom scheme.
265 const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
266 return ssh?.[1] && ssh[2]
267 ? {
268 host: ssh[1].toLowerCase(),
269 hostname: ssh[1].toLowerCase(),
270 ssh: true,
271 path: ssh[2].replace(/\.git$/, ""),
272 }
273 : null;
275​
276export function matchForgejoLogin(
277 logins: ReturnType<typeof parseForgejoLogins>,
278 remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
279 requestedHost?: string,
280 hostOnly = false,
281) {
282 let matches = [
283 ...new Map(
284 logins
285 .filter((login) => {
286 const url = parseForgejoRemote(login.url);
287 if (!url) return false;
288 if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
289 return remote.ssh
290 ? login.ssh_host?.toLowerCase() === remote.host ||
291 login.ssh_host?.toLowerCase() === remote.hostname ||
292 url.hostname === remote.hostname
293 : url.host === remote.host &&
294 ((hostOnly && !remote.path) ||
295 !url.path ||
296 remote.path === url.path ||
297 remote.path.startsWith(`${url.path}/`));
298 })
299 .map((login) => [`${login.url}\n${login.name}`, login]),
300 ).values(),
301 ];
302 if (!remote.ssh && remote.path) {
303 // A root login matches every path on its host; the instance mounted deepest owns the remote.
304 const depth = (login: (typeof matches)[number]) =>
305 parseForgejoRemote(login.url)?.path.length ?? 0;
306 const deepest = Math.max(...matches.map(depth));
307 matches = matches.filter((login) => depth(login) === deepest);
308 }
309 return matches.length === 1
310 ? matches[0]
311 : new Set(matches.map((login) => login.url)).size === 1
312 ? matches.find((login) => login.default === "true")
313 : undefined;
315​
316const ForgejoKeysConfig = Config.all({
317 dataHome: Config.String("XDG_DATA_HOME").pipe(Config.option),
318 appData: Config.String("APPDATA").pipe(Config.option),
319});
320​
321export const make = Effect.gen(function* () {
322 // Optional strings cannot fail to decode.
323 const { dataHome, appData } = yield* Effect.suspend(() => ForgejoKeysConfig).pipe(Effect.orDie);
324 const { process } = yield* SourceControlHost.SourceControlHost;
325 const fileSystem = yield* FileSystem.FileSystem;
326 const httpClient = yield* HttpClient.HttpClient;
327 const authLock = yield* Semaphore.make(1);
328 const authenticated = new Map<string, { token: string; time: number }>();
329 const execute: ForgejoCli["Service"]["execute"] = (input) =>
330 process
331 .run({
332 ...input,
333 operation: "ForgejoCli.execute",
334 command: input.command ?? "gt",
335 timeoutMs: input.timeoutMs ?? 30_000,
336 })
337 .pipe(
338 Effect.mapError(
339 (cause) =>
340 new ForgejoCliError({
341 command: input.command ?? "gt",
342 cwd: input.cwd,
343 ...(input.command === "fj" ? {} : { cause }),
344 ...(cause._tag === "VcsProcessSpawnError"
345 ? { reason: "missing-cli" as const }
346 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
347 ? { reason: "authentication" as const }
348 : {}),
349 detail:
350 cause._tag === "VcsProcessSpawnError"
351 ? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`gt` 2.0 or later) and retry."
352 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
353 ? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `gt auth login`."
354 : "Forgejo CLI command failed.",
355 }),
356 ),
357 );
358​
359 const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
360 for (const path of forgejoKeysPaths({
361 platform: yield* HostProcess.Platform,
362 home: yield* HostProcess.HomeDirectory,
363 ...(Option.isSome(dataHome) ? { dataHome: dataHome.value } : {}),
364 ...(Option.isSome(appData) ? { appData: appData.value } : {}),
365 })) {
366 const exists = yield* fileSystem.exists(path).pipe(
367 Effect.mapError(
368 () =>
369 new ForgejoCliError({
370 command: "fj",
371 cwd,
372 reason: "authentication",
373 detail: "Could not read fj authentication storage.",
374 }),
375 ),
376 );
377 if (!exists) continue;
378 const raw = yield* fileSystem.readFileString(path).pipe(
379 Effect.mapError(
380 () =>
381 new ForgejoCliError({
382 command: "fj",
383 cwd,
384 reason: "authentication",
385 detail: "Could not read fj authentication storage.",
386 }),
387 ),
388 );
389 const decoded = parseForgejoKeys(raw);
390 if (Result.isFailure(decoded))
391 return yield* new ForgejoCliError({
392 command: "fj",
393 cwd,
394 reason: "authentication",
395 detail: "fj authentication storage is invalid. Authenticate again with fj.",
396 });
397 return decoded.success;
398 }
399 const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
400 return empty;
401 });
402​
403 const publicLogins = (
404 keys: typeof ForgejoKeysSchema.Type,
405 remoteUrl?: string,
406 ): ReturnType<typeof parseForgejoLogins> => {
407 const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
408 return Object.keys(keys.hosts).flatMap((host) => {
409 const url = parseForgejoRemote(`https://${host}`);
410 // fj drops URL mounts during whoami and OAuth renewal; gt supports them.
411 if (!url || url.path) return [];
412 // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
413 const scheme =
414 remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
415 ? "http"
416 : "https";
417 const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
418 const aliases = Object.entries(keys.aliases ?? {})
419 .filter(([, target]) => target === host)
420 .map(([alias]) => ({ ...login, ssh_host: alias }));
421 return aliases.length ? aliases : [login];
422 });
423 };
424​
425 const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
426 "ForgejoCli.listLogins",
427 )(function* (input) {
428 if (input.command === "fj") {
429 const keys = yield* readKeys(input.cwd).pipe(Effect.result);
430 if (Result.isFailure(keys)) {
431 // Stale credentials from an uninstalled fj must not disable an available gt login.
432 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
433 Effect.result,
434 );
435 if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
436 return yield* keys.failure;
437 }
438 return publicLogins(keys.success, input.remoteUrl);
439 }
440 const accounts = yield* execute({
441 cwd: input.cwd,
442 args: ["auth", "status", "--json", GT_ACCOUNT_FIELDS],
443 allowNonZeroExit: true,
444 });
445 if (Number(accounts.exitCode) !== 0) {
446 // With --json gt exits 0 even signed out. One that also rejects `version` is another
447 // program of that name, such as Graphite's CLI; a Gitea CLI that answers it is broken.
448 const version = yield* execute({ cwd: input.cwd, args: ["version"] }).pipe(Effect.result);
449 if (Result.isSuccess(version))
450 return yield* new ForgejoCliError({
451 command: "gt",
452 cwd: input.cwd,
453 detail: "`gt auth status` failed. Run it on the T3 Code server to see what gt reports.",
454 });
455 // Only a rejected command says so; a gt that could not be asked fails as it did.
456 if (!isVcsProcessExitError(version.failure.cause)) return yield* version.failure;
457 return yield* new ForgejoCliError({
458 command: "gt",
459 cwd: input.cwd,
460 reason: "wrong-cli",
461 detail:
462 "The `gt` on this server's PATH is not the Gitea CLI. Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`gt` 2.0 or later) and retry.",
463 });
464 }
465 const logins = parseForgejoLogins(accounts.stdout);
466 const remote = input.remoteUrl ? parseForgejoRemote(input.remoteUrl) : null;
467 if (!remote?.ssh) return logins;
468 // Only an instance's `ssh_host` setting maps an SSH alias to it. One named after the
469 // remote matches without it; every other instance is asked.
470 const sshHosts = new Map(
471 yield* Effect.forEach(
472 new Set(
473 logins
474 .map((login) => login.url)
475 .filter((url) => parseForgejoRemote(url)?.hostname !== remote.hostname),
476 ),
477 (url) =>
478 execute({
479 cwd: input.cwd,
480 args: ["config", "get", "ssh_host", "--host", url],
481 allowNonZeroExit: true,
482 }).pipe(
483 Effect.map(
484 (result) => [url, Number(result.exitCode) === 0 ? result.stdout.trim() : ""] as const,
485 ),
486 ),
487 { concurrency: 4 },
488 ),
489 );
490 return logins.map((login) => {
491 const ssh_host = sshHosts.get(login.url);
492 return ssh_host ? { ...login, ssh_host } : login;
493 });
494 });
495​
496 const requestFj = Effect.fn("ForgejoCli.requestFj")(
497 function* (input: {
498 readonly cwd: string;
499 readonly baseUrl: string;
500 readonly token: string;
501 readonly path: string;
502 readonly method?: ForgejoApiInput["method"];
503 readonly body?: string;
504 }) {
505 const base = new URL(`${input.baseUrl}/api/v1/`);
506 const apiUrl = (path: string, from: string) => {
507 const url = URL.parse(path, from);
508 return url &&
509 url.origin === base.origin &&
510 url.pathname.startsWith(base.pathname) &&
511 !url.username &&
512 !url.password
513 ? url
514 : undefined;
515 };
516 const requested = apiUrl(input.path, base.href);
517 if (!requested)
518 return yield* new ForgejoCliError({
519 command: "fj",
520 cwd: input.cwd,
521 detail: "Invalid Forgejo API path.",
522 });
523 let url = requested;
524 const send = (target: URL) => {
525 let request = HttpClientRequest.make(input.method ?? "GET")(target.toString()).pipe(
526 HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
527 );
528 if (input.body !== undefined)
529 request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
530 return httpClient
531 .execute(request)
532 .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
533 };
534 let response = yield* send(url);
535 // Forgejo redirects a renamed repository's API paths before running the handler,
536 // so the same method and body are re-sent. The token never leaves the API base.
537 for (let hops = 0; hops < 5; hops++) {
538 const location = response.headers.location;
539 const next =
540 location && [301, 302, 307, 308].includes(response.status)
541 ? apiUrl(location, url.href)
542 : undefined;
543 if (!next) break;
544 url = next;
545 response = yield* send(url);
546 }
547 const status = response.status;
548 const body =
549 status === 204 || status === 205
550 ? { text: "", truncated: false, invalidUtf8: false }
551 : yield* collectUint8StreamText({
552 stream: response.stream,
553 maxBytes: 8 * 1024 * 1024,
554 });
555 if (body.truncated || body.invalidUtf8)
556 return yield* new ForgejoCliError({
557 command: "fj",
558 cwd: input.cwd,
559 reason: "invalid-response",
560 detail: "Forgejo returned an oversized or invalid response.",
561 });
562 if (status < 200 || status >= 300) {
563 const detail =
564 status === 404
565 ? "Forgejo repository or pull request was not found."
566 : body.text
567 ? `Forgejo API request failed (HTTP ${status}): ${body.text}`
568 : `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`;
569 return yield* new ForgejoCliError({
570 command: "fj",
571 cwd: input.cwd,
572 httpStatus: status,
573 ...(status === 401
574 ? { reason: "authentication" as const }
575 : status === 403
576 ? { reason: "forbidden" as const }
577 : status === 404
578 ? { reason: "not-found" as const }
579 : status === 429
580 ? { reason: "rate-limit" as const }
581 : {}),
582 detail,
583 });
584 }
585 return {
586 exitCode: ChildProcessSpawner.ExitCode(0),
587 stdout: body.text,
588 stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}${response.headers["x-total-count"] ? `x-total-count: ${response.headers["x-total-count"]}\n` : ""}`,
589 stdoutTruncated: false,
590 stderrTruncated: false,
591 };
592 },
593 (effect, input) =>
594 effect.pipe(
595 Effect.timeout(30_000),
596 Effect.mapError((error) =>
597 error._tag === "ForgejoCliError"
598 ? error
599 : new ForgejoCliError({
600 command: "fj",
601 cwd: input.cwd,
602 detail: describeFjRequestFailure(error),
603 }),
604 ),
605 ),
606 );
607​
608 const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
609 cwd: string,
610 login: typeof ForgejoLoginSchema.Type,
611 ) {
612 const keys = yield* readKeys(cwd);
613 const token = keys.hosts[login.name]?.token;
614 const now = yield* Clock.currentTimeMillis;
615 const cached = authenticated.get(login.url);
616 if (token && cached?.token === token && now - cached.time < 30_000) return token;
617 // fj reads the cwd repository even with --host and fails on an unborn branch.
618 yield* execute({
619 command: "fj",
620 cwd: yield* HostProcess.HomeDirectory,
621 args: ["--host", login.url, "whoami"],
622 });
623 // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
624 const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
625 if (!refreshed)
626 return yield* new ForgejoCliError({
627 command: "fj",
628 cwd,
629 reason: "authentication",
630 detail: "fj has no credentials for this server. Authenticate again with fj.",
631 });
632 authenticated.set(login.url, { token: refreshed, time: now });
633 return refreshed;
634 }, authLock.withPermits(1));
635​
636 const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
637 "ForgejoCli.getAccount",
638 )(function* (input) {
639 const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
640 const login = logins.find(
641 (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
642 );
643 if (!login)
644 return yield* new ForgejoCliError({
645 command: "fj",
646 cwd: input.cwd,
647 reason: "authentication",
648 detail: "fj has no credentials for this server.",
649 });
650 const token = yield* authenticateFj(input.cwd, login);
651 const currentUser = yield* requestFj({
652 cwd: input.cwd,
653 baseUrl: login.url.replace(/\/+$/, ""),
654 token,
655 path: "user",
656 });
657 const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
658 if (Result.isFailure(user) || !user.success.login.trim())
659 return yield* new ForgejoCliError({
660 command: "fj",
661 cwd: input.cwd,
662 reason: "invalid-response",
663 detail: "Forgejo returned an invalid account response.",
664 });
665 return user.success.login;
666 });
667​
668 const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
669 input: ForgejoRepositoryInput,
670 hostOnly = false,
671 ) {
672 const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
673 let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
674 (value) => value && parseForgejoRemote(value),
675 );
676 let remote =
677 referenceRemote ??
678 (input.repository ? parseForgejoRemote(input.repository) : null) ??
679 (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
680 if (!remote && (!input.repository || input.host)) {
681 const result = yield* process
682 .run({
683 operation: "ForgejoCli.remote",
684 command: "git",
685 args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
686 cwd: input.cwd,
687 allowNonZeroExit: true,
688 })
689 .pipe(
690 Effect.mapError(
691 (cause) =>
692 new ForgejoCliError({
693 command: "gt",
694 cwd: input.cwd,
695 detail: "Could not resolve the Forgejo repository remote.",
696 cause,
697 }),
698 ),
699 );
700 if (input.host) {
701 const matchingUrls = [
702 ...new Set(
703 result.stdout.split("\n").flatMap((line) => {
704 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
705 const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)(?:\s+\[[^\]]+\])?$/.exec(
706 line.trim(),
707 )?.[1];
708 return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
709 ? [url]
710 : [];
711 }),
712 ),
713 ];
714 const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
715 remoteUrl =
716 matchingUrls.length === 1
717 ? matchingUrls[0]
718 : origins.length === 1
719 ? origins[0]
720 : undefined;
721 } else {
722 remoteUrl = result.stdout.trim();
723 }
724 remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
725 }
726 if (
727 input.host &&
728 !remote?.ssh &&
729 remote?.host !== input.host.toLowerCase() &&
730 remote?.hostname !== input.host.toLowerCase()
731 )
732 remote = {
733 host: input.host.toLowerCase(),
734 hostname: input.host.split(":")[0] ?? input.host,
735 ssh: false,
736 path: remote?.path ?? "",
737 };
738 // A reference or repository URL names the host; the project's own remote decides the scheme.
739 const callerNamedRemote =
740 referenceRemote ?? (input.repository ? parseForgejoRemote(input.repository) : null);
741 const schemeSource = callerNamedRemote ? input.context?.remoteUrl : remoteUrl;
742 const schemeRemoteUrl =
743 schemeSource && parseForgejoRemote(schemeSource)?.ssh
744 ? input.context?.provider.baseUrl
745 : schemeSource;
746 const fjLogins = yield* listLogins({
747 cwd: input.cwd,
748 command: "fj",
749 ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
750 });
751 const requestedHost = input.host ?? input.context?.requestedHost;
752 const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
753 const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
754 remote
755 ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
756 : new Set(logins.map((item) => item.url)).size === 1
757 ? (logins.find((item) => item.default === "true") ?? logins[0])
758 : undefined;
759 let login = selectLogin(fjLogins);
760 let command: "fj" | "gt" = "fj";
761 if (
762 !login &&
763 fjLogins.some(
764 (item) =>
765 !remote ||
766 matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
767 )
768 ) {
769 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
770 Effect.result,
771 );
772 if (Result.isSuccess(available))
773 return yield* new ForgejoCliError({
774 command: "fj",
775 cwd: input.cwd,
776 reason: "authentication",
777 detail: "Multiple fj logins match this repository. Specify its full server URL.",
778 });
779 if (available.failure.reason !== "missing-cli") return yield* available.failure;
780 }
781 if (login) {
782 const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
783 if (Result.isFailure(auth)) {
784 if (auth.failure.reason === "missing-cli") login = undefined;
785 else return yield* auth.failure;
786 }
787 }
788 if (!login) {
789 command = "gt";
790 const gtLogins = yield* listLogins({
791 cwd: input.cwd,
792 command: "gt",
793 ...(remote?.ssh && remoteUrl ? { remoteUrl } : {}),
794 });
795 login = selectLogin(gtLogins);
796 // Publishing a new repository names no server. One server answers for itself above;
797 // with several, gt's default instance decides.
798 if (!login && !remote && gtLogins.length > 0) {
799 const answer = yield* execute({
800 cwd: input.cwd,
801 args: ["config", "get", "default_host"],
802 allowNonZeroExit: true,
803 });
804 login = defaultGtLogin(gtLogins, Number(answer.exitCode) === 0 ? answer.stdout.trim() : "");
805 if (!login)
806 return yield* new ForgejoCliError({
807 command: "gt",
808 cwd: input.cwd,
809 reason: "authentication",
810 detail: NO_DEFAULT_GT_SERVER,
811 });
812 }
813 }
814 if (!login)
815 return yield* new ForgejoCliError({
816 command: "gt",
817 cwd: input.cwd,
818 reason: "authentication",
819 detail:
820 "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `gt auth login` for this server. For a server under a URL subpath, use `gt auth login`. When several servers match, specify the repository's full server URL.",
821 });
822 if (hostOnly)
823 return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
824 const path =
825 referenceRemote?.path ??
826 (input.repository && !parseForgejoRemote(input.repository)
827 ? input.repository
828 : remote?.path) ??
829 "";
830 const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
831 const relativePath =
832 basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
833 ? path.slice(basePath.length + 1)
834 : path;
835 const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
836 if (command === "fj" && !repositoryPath.includes("/")) {
837 login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
838 }
839 const repository = repositoryPath.includes("/")
840 ? repositoryPath
841 : `${login.user}/${repositoryPath}`;
842 if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
843 return yield* new ForgejoCliError({
844 command,
845 cwd: input.cwd,
846 detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
847 });
848 return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
849 });
850 const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
851 const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
852 const repository = yield* resolveTarget(
853 input,
854 input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
855 );
856 const stdin =
857 input.body === undefined
858 ? undefined
859 : yield* encodeApiBody(input.body).pipe(
860 Effect.mapError(
861 (cause) =>
862 new ForgejoCliError({
863 command: "gt",
864 cwd: input.cwd,
865 detail: "Could not encode the Forgejo request body.",
866 cause,
867 }),
868 ),
869 );
870 let path = input.path.replace(/^\/+/, "");
871 if (input.repository && input.repository !== repository.repository) {
872 // Repository identities retain the server mount path; API routes do not.
873 const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
874 if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
875 path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
876 }
877 }
878 if (repository.command === "fj") {
879 const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
880 if (!token)
881 return yield* new ForgejoCliError({
882 command: "fj",
883 cwd: input.cwd,
884 reason: "authentication",
885 detail: "fj has no credentials for this server.",
886 });
887 return yield* requestFj({
888 cwd: input.cwd,
889 baseUrl: repository.baseUrl,
890 token,
891 path,
892 ...(input.method === undefined ? {} : { method: input.method }),
893 ...(stdin === undefined ? {} : { body: stdin }),
894 });
895 }
896 const result = yield* execute({
897 cwd: input.cwd,
898 args: [
899 "api",
900 "--include",
901 ...gtAccountArgs(repository),
902 "--method",
903 input.method ?? "GET",
904 ...(input.body === undefined ? [] : ["--input", "-"]),
905 `${repository.baseUrl}/api/v1/${path}`,
906 ],
907 ...(stdin === undefined ? {} : { stdin }),
908 allowNonZeroExit: true,
909 maxOutputBytes: API_MAX_OUTPUT_BYTES,
910 });
911 // gt exits non-zero on an HTTP failure; the response status it printed says which.
912 const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
913 // Exit code 4 without a response: gt holds no usable credential for this server.
914 const signedOut = !status && Number(result.exitCode) === 4;
915 // gt follows a read's redirect itself, so any status outside 2xx is the final answer, and a
916 // failed exit after a 2xx means the response did not arrive whole.
917 if (!status || status < 200 || status >= 300 || Number(result.exitCode) !== 0) {
918 const body = result.stdout.trim();
919 return yield* new ForgejoCliError({
920 command: "gt",
921 cwd: input.cwd,
922 ...(status ? { httpStatus: status } : {}),
923 ...(status === 401 || signedOut
924 ? { reason: "authentication" as const }
925 : status === 403
926 ? { reason: "forbidden" as const }
927 : status === 404
928 ? { reason: "not-found" as const }
929 : status === 429
930 ? { reason: "rate-limit" as const }
931 : {}),
932 detail:
933 status === 401 || status === 403 || signedOut
934 ? "Forgejo denied access. Check this server's `gt auth status` credentials and permissions."
935 : status === 404
936 ? "Forgejo repository or pull request was not found."
937 : status === 429
938 ? "Forgejo API rate limit exceeded."
939 : !status
940 ? "Forgejo API request failed without an HTTP status."
941 : status < 300
942 ? `Forgejo CLI failed after the server answered (HTTP ${status}).`
943 : body
944 ? `Forgejo API request failed (HTTP ${status}): ${body}`
945 : `Forgejo API request failed (HTTP ${status}).`,
946 });
947 }
948 if (result.stdoutTruncated)
949 return yield* new ForgejoCliError({
950 command: "gt",
951 cwd: input.cwd,
952 reason: "invalid-response",
953 detail: "Forgejo API response exceeded the output size limit.",
954 });
955 return result;
956 });
957 return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
958});
959​
960export const layer = Layer.effect(ForgejoCli, make);