@devries-cameron20 / t3code Mirror · read-only / commits / 0c80751701
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

feat: sign in to GitHub through the T3 Code for GitHub app [internal testing only] (#26245)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 21:21 UTC 0c8075170152c1aa24ab1d5a9a652adeafbbf1a5
64 files changed +2818 -108
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+1
@@ -85,6 +85,7 @@ const WSL_FORWARDED_ENV_NAMES = [
85 "OPENAI_API_KEY",
86 "ANTHROPIC_API_KEY",
87 "T3CODE_TELEMETRY_ENABLED",
88 + "T3CODE_GITHUB_APP_CLIENT_ID",
89 // Otherwise the WSL server keeps exporting to endpoints from the bootstrap.
90 "T3CODE_OTEL_SDK_DISABLED",
91 "OTEL_SDK_DISABLED",
apps/desktop/src/shell/DesktopShellEnvironment.ts
+2
@@ -95,6 +95,7 @@ const LOGIN_SHELL_ENV_NAMES = [
95 "SSL_CERT_DIR",
96 "NODE_EXTRA_CA_CERTS",
97 "T3CODE_TELEMETRY_ENABLED",
98 + "T3CODE_GITHUB_APP_CLIENT_ID",
99 "__MISE_DIFF",
100 ] as const;
101 const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
@@ -450,6 +451,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
451 "SSL_CERT_DIR",
452 "NODE_EXTRA_CA_CERTS",
453 "T3CODE_TELEMETRY_ENABLED",
454 + "T3CODE_GITHUB_APP_CLIENT_ID",
455 ] as const) {
456 if (!config.env[name] && shellEnvironment[name]) {
457 config.env[name] = shellEnvironment[name];
apps/mobile/src/features/projects/AddProjectScreen.tsx
+16
@@ -87,6 +87,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
87 import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
88 import { uuidv4 } from "../../lib/uuid";
89 import { useAtomCommand } from "../../state/use-atom-command";
90 +import { suggestAppAccessForRemote } from "./suggestAppAccess";
91 import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
92 import {
93 useRemoteConnectionStatus,
@@ -997,6 +998,10 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s
998 );
999 const environment = resolveAddProjectEnvironment(environmentOptions, selectedEnvironmentId);
1000 const createNew = useAtomCommand(projectEnvironment.createNew, { reportFailure: false });
1001 + const checkPublishedAppAccess = useAtomCommand(sourceControlEnvironment.checkAppAccess, {
1002 + reportFailure: false,
1003 + reportDefect: false,
1004 + });
1005 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
1006 reportFailure: false,
1007 });
@@ -1095,6 +1100,12 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s
1100 `Could not create the ${publishTarget.definition.label} repository`,
1101 errorMessage(Cause.squash(publishResult.cause)),
1102 );
1103 + } else {
1104 + void suggestAppAccessForRemote(
1105 + checkPublishedAppAccess,
1106 + environment.environmentId,
1107 + publishResult.value.remoteUrl,
1108 + );
1109 }
1110 });
1111 }
@@ -1315,6 +1326,10 @@ export function AddProjectDestinationScreen(props: {
1326 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
1327 reportFailure: false,
1328 });
1329 + const checkAppAccess = useAtomCommand(sourceControlEnvironment.checkAppAccess, {
1330 + reportFailure: false,
1331 + reportDefect: false,
1332 + });
1333 const navigation = useNavigation();
1334 const environment = useEnvironmentFromParam(props.environmentId);
1335 const canWriteSourceControl = useEnvironmentScope(
@@ -1376,6 +1391,7 @@ export function AddProjectDestinationScreen(props: {
1391 if (AsyncResult.isFailure(startResult)) {
1392 setError(errorMessage(Cause.squash(startResult.cause)));
1393 } else {
1394 + void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
1395 // Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
1396 const project = await waitForProject(
1397 { environmentId: environment.environmentId, projectId },
apps/mobile/src/features/projects/suggestAppAccess.ts new
+38
@@ -0,0 +1,38 @@
1 +import type {
2 + EnvironmentId,
3 + SourceControlAppAccess,
4 + SourceControlAppAccessInput,
5 +} from "@t3tools/contracts";
6 +import { appSignInTargetForRemote } from "@t3tools/client-runtime/source-control-clients";
7 +import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
8 +import { Alert, Linking } from "react-native";
9 +
10 +/**
11 + * After a clone, suggests installing the forge app on the repository's owner when the server is
12 + * signed in with it but the app does not reach the repository.
13 + */
14 +export async function suggestAppAccessForRemote(
15 + check: (value: {
16 + readonly environmentId: EnvironmentId;
17 + readonly input: SourceControlAppAccessInput;
18 + }) => Promise<AtomCommandResult<SourceControlAppAccess, unknown>>,
19 + environmentId: EnvironmentId,
20 + remoteUrl: string,
21 +): Promise<void> {
22 + const target = appSignInTargetForRemote(remoteUrl);
23 + if (target === null) return;
24 + const result = await check({ environmentId, input: target.input });
25 + if (result._tag !== "Success" || result.value.status !== "not-covered") return;
26 + const owner = target.input.repository.split("/")[0] ?? target.input.repository;
27 + Alert.alert(
28 + `Give ${target.appSignIn.appName} access to ${owner}`,
29 + `It isn't installed there, so GitHub requests for ${target.input.repository} use your own login and its lower rate limit.`,
30 + [
31 + { text: "Not now", style: "cancel" },
32 + {
33 + text: "Install",
34 + onPress: () => void Linking.openURL(target.appSignIn.installUrl).catch(() => undefined),
35 + },
36 + ],
37 + );
38 +}
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+7
@@ -82,6 +82,7 @@ import { pullRequestLabelColor } from "./pullRequestList";
82 import { PullRequestReactions } from "./PullRequestReactions";
83 import { composerPullRequests } from "../../state/pull-requests";
84 import { useEnvironmentQuery } from "../../state/query";
85 +import { SourceControlAppAccessNotice } from "./SourceControlAppAccessNotice";
86 import { usePullToRefresh } from "../../state/use-pull-to-refresh";
87 import {
88 resolveNativeReviewDiffView,
@@ -720,6 +721,12 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
721 <View>
722 {tab === "overview" && identity ? (
723 <View>
724 + <SourceControlAppAccessNotice
725 + environmentId={params.environmentId}
726 + provider={identity.provider}
727 + host={params.host}
728 + repository={params.repository}
729 + />
730 {pr ? (
731 <PullRequestOverview
732 pr={pr}
apps/mobile/src/features/pull-requests/SourceControlAppAccessNotice.tsx new
+59
@@ -0,0 +1,59 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import {
3 + readHostCredentialSettings,
4 + sourceControlClients,
5 +} from "@t3tools/client-runtime/source-control-clients";
6 +import { Linking, Pressable, View } from "react-native";
7 +
8 +import { AppText as Text } from "../../components/ui/AppText";
9 +import { useEnvironmentPresentation } from "../../state/presentation";
10 +import { useEnvironmentQuery } from "../../state/query";
11 +import { sourceControlEnvironment } from "../../state/sourceControl";
12 +
13 +/**
14 + * Says when the server's forge app sign-in cannot reach `repository`, so requests there fall back
15 + * to the user's own login. Renders nothing for servers that do not use the app.
16 + */
17 +export function SourceControlAppAccessNotice(props: {
18 + readonly environmentId: string;
19 + readonly provider: string | undefined;
20 + readonly host: string | undefined;
21 + /** `owner/name`. */
22 + readonly repository: string;
23 +}) {
24 + const environmentId = EnvironmentId.make(props.environmentId);
25 + const { presentation } = useEnvironmentPresentation(environmentId);
26 + const definition = props.provider ? sourceControlClients.find(props.provider) : undefined;
27 + const appSignIn = definition?.credentials?.appSignIn;
28 + const host = (props.host ?? definition?.publicHost ?? "").toLowerCase();
29 + const settings = presentation?.serverConfig?.settings;
30 + const signedIn =
31 + definition !== undefined &&
32 + settings !== undefined &&
33 + (readHostCredentialSettings(settings, definition.kind).signIns[host] ?? "").length > 0;
34 + const access = useEnvironmentQuery(
35 + definition !== undefined && appSignIn?.hosts.includes(host) && signedIn
36 + ? sourceControlEnvironment.appAccess({
37 + environmentId,
38 + input: { provider: definition.kind, host, repository: props.repository },
39 + })
40 + : null,
41 + );
42 + if (appSignIn === undefined || access.data?.status !== "not-covered") return null;
43 + const owner = props.repository.split("/")[0] ?? props.repository;
44 +
45 + return (
46 + <View className="mb-4 gap-1 rounded-2xl bg-grouped-card px-4 py-3">
47 + <Text className="text-sm text-foreground-muted">
48 + {appSignIn.appName} isn't installed on {owner}, so requests here use your own GitHub login
49 + and its lower rate limit.
50 + </Text>
51 + <Pressable
52 + accessibilityRole="link"
53 + onPress={() => void Linking.openURL(appSignIn.installUrl).catch(() => undefined)}
54 + >
55 + <Text className="text-sm font-t3-bold text-foreground">Install on {owner}</Text>
56 + </Pressable>
57 + </View>
58 + );
59 +}
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+3
@@ -45,6 +45,9 @@ vi.mock("../../state/preferences", () => ({
45 updateMobilePreferencesAtom: {},
46 }));
47 vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
48 +vi.mock("./components/SourceControlSignInSection", () => ({
49 + SourceControlSignInSection: () => null,
50 +}));
51 vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
52 vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
53 vi.mock("../../state/session", () => ({
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+7
@@ -28,6 +28,7 @@ import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
28 import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
29 import { SettingsSection } from "./components/SettingsSection";
30 import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
31 +import { SourceControlSignInSection } from "./components/SourceControlSignInSection";
32 import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
33 import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
34 import { useSettingsWriter } from "./useSettingsWriter";
@@ -382,6 +383,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
383
384 {props.page === "source-control" ? (
385 <>
386 + {projectSelected ? null : (
387 + <SourceControlSignInSection
388 + environments={selectedTargets}
389 + canWrite={(environmentId) => writableEnvironments.has(environmentId)}
390 + />
391 + )}
392 <SettingsSection title="Pull requests">
393 <SettingsSwitchRow
394 icon={PullRequestGlyph.merged}
apps/mobile/src/features/settings/components/SourceControlSignInSection.tsx new
+207
@@ -0,0 +1,207 @@
1 +import type { EnvironmentId, SourceControlSignInPrompt } from "@t3tools/contracts";
2 +import {
3 + readHostCredentialSettings,
4 + sourceControlClients,
5 + type SourceControlAppSignIn,
6 + type SourceControlDefinition,
7 +} from "@t3tools/client-runtime/source-control-clients";
8 +import * as Cause from "effect/Cause";
9 +import * as Clipboard from "expo-clipboard";
10 +import { useRef, useState } from "react";
11 +import { Alert, Linking } from "react-native";
12 +
13 +import { useEnvironmentQuery } from "../../../state/query";
14 +import { serverEnvironment } from "../../../state/server";
15 +import { sourceControlEnvironment } from "../../../state/sourceControl";
16 +import { useAtomCommand } from "../../../state/use-atom-command";
17 +import type { SettingsTarget } from "../settings-environment-filter";
18 +import { SettingsRow } from "./SettingsRow";
19 +import { SettingsSection } from "./SettingsSection";
20 +
21 +const failureMessage = (cause: Cause.Cause<unknown>) => {
22 + const error = Cause.squash(cause);
23 + return error instanceof Error ? error.message : String(error);
24 +};
25 +
26 +const openUrl = (url: string) => void Linking.openURL(url).catch(() => undefined);
27 +
28 +const appSignInHosts = sourceControlClients.definitions.flatMap((definition) =>
29 + definition.credentials?.appSignIn === undefined
30 + ? []
31 + : [{ definition, appSignIn: definition.credentials.appSignIn }],
32 +);
33 +
34 +/**
35 + * Signing an environment in through a forge's own app, such as T3 Code for GitHub, on servers
36 + * configured for it.
37 + */
38 +export function SourceControlSignInSection(props: {
39 + readonly environments: readonly SettingsTarget[];
40 + readonly canWrite: (environmentId: EnvironmentId) => boolean;
41 +}) {
42 + return (
43 + <>
44 + {appSignInHosts.flatMap(({ definition, appSignIn }) =>
45 + props.environments.map((environment) => (
46 + <OfferedAppSignIn
47 + key={`${definition.kind}:${environment.environmentId}`}
48 + environment={environment}
49 + title={
50 + props.environments.length > 1
51 + ? `${definition.label} · ${environment.label}`
52 + : definition.label
53 + }
54 + definition={definition}
55 + appSignIn={appSignIn}
56 + disabled={!props.canWrite(environment.environmentId)}
57 + />
58 + )),
59 + )}
60 + </>
61 + );
62 +}
63 +
64 +function OfferedAppSignIn(props: {
65 + readonly environment: SettingsTarget;
66 + readonly title: string;
67 + readonly definition: SourceControlDefinition;
68 + readonly appSignIn: SourceControlAppSignIn;
69 + readonly disabled: boolean;
70 +}) {
71 + const discovery = useEnvironmentQuery(
72 + sourceControlEnvironment.discovery({
73 + environmentId: props.environment.environmentId,
74 + input: {},
75 + }),
76 + );
77 + const offered = discovery.data?.sourceControlProviders.some(
78 + (item) => item.kind === props.definition.kind && item.appSignIn === true,
79 + );
80 + if (offered !== true) return null;
81 + return (
82 + <SettingsSection title={props.title}>
83 + <AppSignInRow
84 + environment={props.environment}
85 + label={props.appSignIn.appName}
86 + definition={props.definition}
87 + appSignIn={props.appSignIn}
88 + disabled={props.disabled}
89 + />
90 + </SettingsSection>
91 + );
92 +}
93 +
94 +function AppSignInRow(props: {
95 + readonly environment: SettingsTarget;
96 + readonly label: string;
97 + readonly definition: SourceControlDefinition;
98 + readonly appSignIn: SourceControlAppSignIn;
99 + readonly disabled: boolean;
100 +}) {
101 + const { environment, definition, appSignIn } = props;
102 + const environmentId = environment.environmentId;
103 + const host = appSignIn.hosts[0] ?? "";
104 + const { signIns } = readHostCredentialSettings(
105 + environment.serverConfig.settings,
106 + definition.kind,
107 + );
108 + const signedIn = (signIns[host] ?? "").length > 0;
109 + const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
110 + const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
111 + const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
112 + // The attempt a pending `wait` belongs to; a cancel or a newer attempt makes its outcome stale.
113 + const attempt = useRef<SourceControlSignInPrompt | null>(null);
114 + const input = { provider: definition.kind, host };
115 + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
116 + label: `sign out of ${appSignIn.appName}`,
117 + });
118 + const [pending, setPending] = useState<SourceControlSignInPrompt | "starting" | null>(null);
119 +
120 + const showCode = (prompt: SourceControlSignInPrompt) => {
121 + void Clipboard.setStringAsync(prompt.userCode).catch(() => undefined);
122 + Alert.alert(
123 + prompt.userCode,
124 + `Enter this code on GitHub, then approve ${appSignIn.appName}. It is copied. The server finishes signing in even if you leave the app.`,
125 + [
126 + {
127 + text: "Cancel",
128 + style: "cancel",
129 + onPress: () => {
130 + attempt.current = null;
131 + setPending(null);
132 + void cancel({ environmentId, input });
133 + },
134 + },
135 + { text: "Open GitHub", onPress: () => openUrl(prompt.verificationUri) },
136 + ],
137 + );
138 + };
139 +
140 + const signIn = async () => {
141 + setPending("starting");
142 + const started = await start({ environmentId, input });
143 + if (started._tag !== "Success") {
144 + setPending(null);
145 + Alert.alert("Could not start the sign-in", failureMessage(started.cause));
146 + return;
147 + }
148 + const prompt = started.value;
149 + attempt.current = prompt;
150 + setPending(prompt);
151 + showCode(prompt);
152 + const finished = await wait({ environmentId, input });
153 + if (attempt.current !== prompt) return;
154 + attempt.current = null;
155 + setPending(null);
156 + if (finished._tag !== "Success") {
157 + Alert.alert("Sign-in did not finish", failureMessage(finished.cause));
158 + }
159 + };
160 +
161 + const signOut = () =>
162 + void updateSettings({
163 + environmentId,
164 + // Send the whole map; other hosts' redaction markers preserve their sessions.
165 + input: {
166 + patch: {
167 + sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
168 + },
169 + },
170 + });
171 +
172 + const onPress = () => {
173 + if (signedIn) {
174 + Alert.alert(
175 + appSignIn.appName,
176 + "Signed in. GitHub requests use the app's higher rate limit, in repositories where the app is installed.",
177 + [
178 + { text: "Install on an organization", onPress: () => openUrl(appSignIn.installUrl) },
179 + { text: "Sign out", style: "destructive", onPress: signOut },
180 + { text: "Cancel", style: "cancel" },
181 + ],
182 + );
183 + } else if (pending !== null && pending !== "starting") {
184 + showCode(pending);
185 + } else if (pending === null) {
186 + void signIn();
187 + }
188 + };
189 +
190 + return (
191 + <SettingsRow
192 + icon="person.crop.circle"
193 + label={props.label}
194 + value={
195 + signedIn
196 + ? "Signed in"
197 + : pending === "starting"
198 + ? "Starting…"
199 + : pending !== null
200 + ? `Enter ${pending.userCode}`
201 + : "Sign in"
202 + }
203 + disabled={props.disabled}
204 + onPress={onPress}
205 + />
206 + );
207 +}
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -138,6 +138,7 @@ export const RPC_REQUIRED_SCOPES = {
138 [WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
139 [WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
140 [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
141 + [WS_METHODS.sourceControlAppAccess]: AuthOrchestrationReadScope,
142 [WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
143 [WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
144 [WS_METHODS.projectsListIgnoredFiles]: AuthFilesystemReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+4
@@ -134,6 +134,10 @@ const RPC_AGGREGATES = {
134 [WS_METHODS.sourceControlLookupRepository]: "source-control",
135 [WS_METHODS.sourceControlCloneRepository]: "source-control",
136 [WS_METHODS.sourceControlPublishRepository]: "source-control",
137 + [WS_METHODS.sourceControlSignInStart]: "source-control",
138 + [WS_METHODS.sourceControlSignInWait]: "source-control",
139 + [WS_METHODS.sourceControlSignInCancel]: "source-control",
140 + [WS_METHODS.sourceControlAppAccess]: "source-control",
141 [WS_METHODS.projectCloneStart]: "source-control",
142 [WS_METHODS.projectCloneCancel]: "source-control",
143 [WS_METHODS.projectCloneRetry]: "source-control",
apps/server/src/pullRequest/PullRequestService.ts
+6 -2
@@ -1565,7 +1565,7 @@ export const make = Effect.gen(function* () {
1565 }
1566 const result = yield* api
1567 .withVerifiedCredential(
1568 - { cwd: project.project.workspaceRoot, host: project.host },
1568 + { cwd: project.project.workspaceRoot, host: project.host, repository: project.repository },
1569 (identity) =>
1570 identity.accountId === input.expectedAccountId
1571 ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)
@@ -2066,7 +2066,11 @@ export const make = Effect.gen(function* () {
2066 return input.action === "delete-branch" && project.api.withVerifiedCredential !== undefined
2067 ? project.api
2068 .withVerifiedCredential(
2069 - { cwd: project.project.workspaceRoot, host: project.host },
2069 + {
2070 + cwd: project.project.workspaceRoot,
2071 + host: project.host,
2072 + repository: project.repository,
2073 + },
2074 () => operation.pipe(Effect.result),
2075 )
2076 .pipe(
apps/server/src/server.ts
+4
@@ -61,6 +61,7 @@ import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRe
61 import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
62 import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
63 import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
64 +import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
65 import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControl/sourceControlDefinitions.ts";
66 import * as TextGeneration from "./textGeneration/TextGeneration.ts";
67 import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts";
@@ -419,6 +420,9 @@ const layerVcs = Layer.empty.pipe(
420 Layer.provideMerge(layerGitWorkflow),
421 Layer.provideMerge(layerReview),
422 Layer.provideMerge(layerSourceControlRepositoryService),
423 + Layer.provideMerge(
424 + SourceControlSignIn.layer.pipe(Layer.provide(layerSourceControlProviderRegistry)),
425 + ),
426 Layer.provideMerge(layerProjectCloneTracker),
427 Layer.provideMerge(
428 VcsStatusBroadcaster.layer.pipe(
apps/server/src/sourceControl/ServerSourceControlHost.ts
+1 -1
@@ -15,7 +15,7 @@ export const layer = Layer.effect(
15 const git = yield* GitVcsDriver.GitVcsDriver;
16 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
17 return SourceControlHost.SourceControlHost.of({
18 - settings: { get: serverSettings.getSettings },
18 + settings: { get: serverSettings.getSettings, update: serverSettings.updateSettings },
19 process: { run: process.run },
20 git: {
21 execute: git.execute,
apps/server/src/sourceControl/SourceControlSignIn.ts new
+69
@@ -0,0 +1,69 @@
1 +import {
2 + type SourceControlAppAccess,
3 + type SourceControlAppAccessInput,
4 + SourceControlSignInError,
5 + type SourceControlSignInInput,
6 + type SourceControlSignInPrompt,
7 + type SourceControlSignInResult,
8 +} from "@t3tools/contracts";
9 +import * as Context from "effect/Context";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +
13 +import * as SourceControlBuiltInDrivers from "./builtInDrivers.ts";
14 +
15 +/** Signs the server in to a forge through the forge's own app, for hosts whose driver offers it. */
16 +export class SourceControlSignIn extends Context.Service<
17 + SourceControlSignIn,
18 + {
19 + readonly start: (
20 + input: SourceControlSignInInput,
21 + ) => Effect.Effect<SourceControlSignInPrompt, SourceControlSignInError>;
22 + readonly wait: (
23 + input: SourceControlSignInInput,
24 + ) => Effect.Effect<SourceControlSignInResult, SourceControlSignInError>;
25 + readonly cancel: (
26 + input: SourceControlSignInInput,
27 + ) => Effect.Effect<void, SourceControlSignInError>;
28 + readonly access: (input: SourceControlAppAccessInput) => Effect.Effect<SourceControlAppAccess>;
29 + }
30 +>()("t3/sourceControl/SourceControlSignIn") {}
31 +
32 +const make = Effect.gen(function* () {
33 + const drivers = yield* SourceControlBuiltInDrivers.SourceControlDrivers;
34 +
35 + const signInFor = (input: SourceControlSignInInput) => {
36 + const signIn = drivers.find(({ driver }) => driver.kind === input.provider)?.instance.signIn;
37 + return signIn === undefined
38 + ? Effect.fail(
39 + new SourceControlSignInError({
40 + provider: input.provider,
41 + host: input.host,
42 + reason: "unsupported",
43 + detail: `This server cannot sign in to ${input.provider}. Use a token or the host's CLI.`,
44 + }),
45 + )
46 + : Effect.succeed(signIn);
47 + };
48 +
49 + return SourceControlSignIn.of({
50 + start: Effect.fn("SourceControlSignIn.start")(function* (input) {
51 + return yield* (yield* signInFor(input)).start(input.host);
52 + }),
53 + wait: Effect.fn("SourceControlSignIn.wait")(function* (input) {
54 + return yield* (yield* signInFor(input)).wait(input.host);
55 + }),
56 + cancel: Effect.fn("SourceControlSignIn.cancel")(function* (input) {
57 + return yield* (yield* signInFor(input)).cancel(input.host);
58 + }),
59 + access: Effect.fn("SourceControlSignIn.access")(function* (input) {
60 + const signIn = drivers.find(({ driver }) => driver.kind === input.provider)?.instance.signIn;
61 + return {
62 + status:
63 + signIn === undefined ? "signed-out" : yield* signIn.access(input.host, input.repository),
64 + } satisfies SourceControlAppAccess;
65 + }),
66 + });
67 +});
68 +
69 +export const layer = Layer.effect(SourceControlSignIn, make);
apps/server/src/telemetry/FeatureUsage.ts
+1
@@ -70,6 +70,7 @@ const METHOD_FEATURES: Readonly<Record<string, (payload: Payload) => FeatureUsag
70 [WS_METHODS.agentSessionsImport]: () => ({ feature: "agent_session.import" }),
71 [WS_METHODS.projectCloneStart]: () => ({ feature: "project.clone" }),
72 [WS_METHODS.sourceControlPublishRepository]: () => ({ feature: "repository.publish" }),
73 + [WS_METHODS.sourceControlSignInStart]: () => ({ feature: "source_control.sign_in" }),
74 [WS_METHODS.serverUpsertKeybinding]: () => ({ feature: "keybinding.customize" }),
75 [WS_METHODS.guestShareCreate]: () => ({ feature: "guest_share.create" }),
76 };
apps/server/src/ws.test.ts
+2
@@ -86,6 +86,7 @@ import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
86 import * as SessionStore from "./auth/SessionStore.ts";
87 import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
88 import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
89 +import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
90 import * as StorageCleanup from "./storageCleanup.ts";
91 import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
92 import * as TerminalManager from "./terminal/Manager.ts";
@@ -454,6 +455,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
455 Layer.mock(SessionStore.SessionStore)({ cookieName: "config-test", legacyCookieName: undefined }),
456 Layer.mock(SourceControlDiscovery.SourceControlDiscovery)({}),
457 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
458 + Layer.mock(SourceControlSignIn.SourceControlSignIn)({}),
459 Layer.mock(StorageCleanup.StorageCleanup)({}),
460 Layer.mock(DatabaseStorage.DatabaseStorage)({}),
461 Layer.mock(TerminalManager.TerminalManager)({}),
apps/server/src/ws.ts
+6
@@ -244,6 +244,7 @@ import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReact
244 import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
245 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
246 import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
247 +import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
248 import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
249 import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
250 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
@@ -1352,6 +1353,7 @@ export const layerWsRpc = (
1353 const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck;
1354 const sourceControlRepositories =
1355 yield* SourceControlRepositoryService.SourceControlRepositoryService;
1356 + const sourceControlSignIn = yield* SourceControlSignIn.SourceControlSignIn;
1357 const withPullRequestViewer = pullRequests.withRoutingCredential;
1358 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
1359 const sessions = yield* SessionStore.SessionStore;
@@ -2653,6 +2655,10 @@ export const layerWsRpc = (
2655 sourceControlRepositories.lookupRepository(input),
2656 [WS_METHODS.sourceControlCloneRepository]: (input) =>
2657 sourceControlRepositories.cloneRepository(input),
2658 + [WS_METHODS.sourceControlSignInStart]: (input) => sourceControlSignIn.start(input),
2659 + [WS_METHODS.sourceControlSignInWait]: (input) => sourceControlSignIn.wait(input),
2660 + [WS_METHODS.sourceControlSignInCancel]: (input) => sourceControlSignIn.cancel(input),
2661 + [WS_METHODS.sourceControlAppAccess]: (input) => sourceControlSignIn.access(input),
2662 [WS_METHODS.projectCloneStart]: (input) =>
2663 projectCloneTracker.start(input, {
2664 createProject: (project) =>
apps/web/src/components/CommandPalette.tsx
+5
@@ -231,6 +231,7 @@ import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindin
231 import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "./ui/command";
232 import { Button } from "./ui/button";
233 import { stackedThreadToast, toastManager } from "./ui/toast";
234 +import { suggestAppAccessForRemote } from "./sourceControlAppAccessToast";
235 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
236 import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
237 import type { ChatComposerHandle } from "./chat/ChatComposer";
@@ -1982,6 +1983,10 @@ function OpenCommandPaletteDialog(props: {
1983 return;
1984 }
1985 setOpen(false);
1986 + void suggestAppAccessForRemote(
1987 + addProjectCloneFlow.environmentId,
1988 + addProjectCloneFlow.remoteUrl,
1989 + );
1990 const projectRef = scopeProjectRef(addProjectCloneFlow.environmentId, projectId);
1991 await waitForProject(projectRef, 3_000).catch(() => null);
1992 const navigationResult = await settlePromise(() => handleNewThread(projectRef));
apps/web/src/components/SourceControlAppAccessNotice.tsx new
+68
@@ -0,0 +1,68 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import {
3 + readHostCredentialSettings,
4 + sourceControlClients,
5 +} from "@t3tools/client-runtime/source-control-clients";
6 +import { ExternalLinkIcon } from "lucide-react";
7 +
8 +import { useEnvironmentSettings } from "../hooks/useSettings";
9 +import { cn } from "../lib/utils";
10 +import { useEnvironmentQuery } from "../state/query";
11 +import { sourceControlEnvironment } from "../state/sourceControl";
12 +import { T3AppIcon } from "./T3AppIcon";
13 +import { InlineButton } from "./ui/button";
14 +
15 +/**
16 + * Says when the server's forge app sign-in cannot reach `repository`, so requests there fall back
17 + * to the user's own login. Renders nothing for servers that do not use the app.
18 + */
19 +export function SourceControlAppAccessNotice(props: {
20 + readonly environmentId: EnvironmentId;
21 + readonly provider: string | undefined;
22 + readonly host: string | undefined;
23 + /** `owner/name`. */
24 + readonly repository: string;
25 + readonly className?: string;
26 +}) {
27 + const definition = props.provider ? sourceControlClients.find(props.provider) : undefined;
28 + const appSignIn = definition?.credentials?.appSignIn;
29 + const host = (props.host ?? definition?.publicHost ?? "").toLowerCase();
30 + const signedIn = useEnvironmentSettings(props.environmentId, (settings) =>
31 + definition === undefined
32 + ? false
33 + : (readHostCredentialSettings(settings, definition.kind).signIns[host] ?? "").length > 0,
34 + );
35 + const access = useEnvironmentQuery(
36 + definition !== undefined && appSignIn?.hosts.includes(host) && signedIn
37 + ? sourceControlEnvironment.appAccess({
38 + environmentId: props.environmentId,
39 + input: { provider: definition.kind, host, repository: props.repository },
40 + })
41 + : null,
42 + );
43 + if (appSignIn === undefined || access.data?.status !== "not-covered") return null;
44 + const owner = props.repository.split("/")[0] ?? props.repository;
45 +
46 + return (
47 + <div
48 + role="note"
49 + className={cn(
50 + "flex items-center gap-2.5 bg-muted/40 px-4 py-2 text-xs text-muted-foreground",
51 + props.className,
52 + )}
53 + >
54 + <T3AppIcon className="size-4 shrink-0" />
55 + <p className="min-w-0 flex-1">
56 + {appSignIn.appName} isn't installed on <span className="text-foreground">{owner}</span>, so
57 + requests here use your own GitHub login and its lower rate limit.
58 + </p>
59 + <InlineButton
60 + className="shrink-0"
61 + render={<a href={appSignIn.installUrl} target="_blank" rel="noreferrer noopener" />}
62 + >
63 + Install on {owner}
64 + <ExternalLinkIcon aria-hidden className="size-3" />
65 + </InlineButton>
66 + </div>
67 + );
68 +}
apps/web/src/components/T3AppIcon.tsx new
+6
@@ -0,0 +1,6 @@
1 +// The production icon, as GitHub shows the T3 Code app, whatever this build's channel.
2 +import appIconUrl from "../../../../assets/prod/t3-black-web-apple-touch-180.png";
3 +
4 +export function T3AppIcon(props: { readonly className?: string }) {
5 + return <img src={appIconUrl} alt="" className={props.className} />;
6 +}
apps/web/src/components/promptLinks/NewThreadLinkView.tsx
+5
@@ -42,6 +42,7 @@ import { Button } from "../ui/button";
42 import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
43 import { SidebarInset } from "../ui/sidebar";
44 import { stackedThreadToast, toastManager } from "../ui/toast";
45 +import { suggestAppAccessForRemote } from "../sourceControlAppAccessToast";
46 import { WorkspacePageHeader } from "../WorkspacePageHeader";
47 import { placeLinkedPrompt, warnAboutHiddenCharacters } from "./linkedPrompt";
48
@@ -233,6 +234,10 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
234 setState({ status: "missing-repository", repository });
235 return;
236 }
237 + void suggestAppAccessForRemote(
238 + environmentId,
239 + `https://github.com/${repository.owner}/${repository.name}.git`,
240 + );
241 const project = await waitForProject(scopeProjectRef(environmentId, projectId), 5_000).catch(
242 () => null,
243 );
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+8
@@ -100,6 +100,7 @@ import { PullRequestBaseBranch } from "./PullRequestBaseBranch";
100 import { PullRequestDetailCrumbs } from "./PullRequestDetailCrumbs";
101 import { PullRequestTitleEditor } from "./PullRequestTitleEditor";
102 import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
103 +import { SourceControlAppAccessNotice } from "../SourceControlAppAccessNotice";
104 import { DiffPanelLoadingState } from "../DiffPanelShell";
105 import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
106 import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab";
@@ -1681,6 +1682,13 @@ export function PullRequestDetailPanel({
1682 ) : null}
1683 </div>
1684
1685 + <SourceControlAppAccessNotice
1686 + environmentId={environmentId}
1687 + provider={detail?.provider ?? repositoryIdentity?.provider}
1688 + host={reference.host}
1689 + repository={reference.repository}
1690 + className="border-b border-border/60"
1691 + />
1692 <div
1693 className="relative flex min-h-0 flex-1 flex-col overflow-hidden"
1694 onScrollCapture={(event) => {
apps/web/src/components/settings/SourceControlAppSignInSettings.tsx new
+277
@@ -0,0 +1,277 @@
1 +import type { EnvironmentId, SourceControlSignInPrompt } from "@t3tools/contracts";
2 +import {
3 + readHostCredentialSettings,
4 + type SourceControlAppSignIn,
5 + type SourceControlDefinition,
6 +} from "@t3tools/client-runtime/source-control-clients";
7 +import { useAtomValue } from "@effect/atom-react";
8 +import * as Cause from "effect/Cause";
9 +import { Check, Copy } from "lucide";
10 +import { CheckIcon, ExternalLinkIcon } from "lucide-react";
11 +import { useState, type ReactNode } from "react";
12 +
13 +import { MorphIcon } from "~/components/MorphIcon";
14 +import { T3AppIcon } from "~/components/T3AppIcon";
15 +import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
16 +import { useEnvironmentSettings } from "../../hooks/useSettings";
17 +import { cn } from "../../lib/utils";
18 +import { serverEnvironment } from "../../state/server";
19 +import { sourceControlEnvironment } from "../../state/sourceControl";
20 +import { useAtomCommand } from "../../state/use-atom-command";
21 +import { Button, InlineButton } from "../ui/button";
22 +import { Spinner } from "../ui/spinner";
23 +import { RedactedSensitiveText } from "./RedactedSensitiveText";
24 +
25 +type SignInState =
26 + | { readonly status: "idle" }
27 + | { readonly status: "starting" }
28 + | { readonly status: "waiting"; readonly prompt: SourceControlSignInPrompt }
29 + | { readonly status: "failed"; readonly message: string };
30 +
31 +const failureMessage = (cause: Cause.Cause<unknown>) => {
32 + const error = Cause.squash(cause);
33 + return error instanceof Error ? error.message : String(error);
34 +};
35 +
36 +const expiryTime = (expiresAt: number) =>
37 + new Date(expiresAt).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
38 +
39 +function ExternalLink(props: { readonly href: string; readonly children: ReactNode }) {
40 + return (
41 + <InlineButton render={<a href={props.href} target="_blank" rel="noreferrer noopener" />}>
42 + {props.children}
43 + <ExternalLinkIcon aria-hidden className="size-3" />
44 + </InlineButton>
45 + );
46 +}
47 +
48 +function AppMark(props: { readonly signedIn: boolean }) {
49 + return (
50 + <div className="relative size-10 shrink-0">
51 + <T3AppIcon className="size-full" />
52 + {props.signedIn ? (
53 + <span className="absolute -right-1 -bottom-1 grid size-4 place-items-center rounded-full bg-success text-white ring-2 ring-card">
54 + <CheckIcon aria-hidden className="size-2.5" strokeWidth={3} />
55 + </span>
56 + ) : null}
57 + </div>
58 + );
59 +}
60 +
61 +/** The device code, one cell per character, as GitHub prints it. */
62 +function DeviceCode(props: { readonly code: string }) {
63 + return (
64 + <div className="flex items-center gap-1 font-mono text-lg font-medium">
65 + <span className="sr-only">{props.code}</span>
66 + {Array.from(props.code, (char, index) =>
67 + char === "-" ? (
68 + <span key={index} aria-hidden className="px-0.5 text-muted-foreground">
69 + –
70 + </span>
71 + ) : (
72 + <span
73 + key={index}
74 + aria-hidden
75 + className="grid h-10 w-8 place-items-center rounded-md border border-border bg-background shadow-xs"
76 + >
77 + {char}
78 + </span>
79 + ),
80 + )}
81 + </div>
82 + );
83 +}
84 +
85 +export function SourceControlAppSignInSettings({
86 + environmentId,
87 + definition,
88 + appSignIn,
89 + account,
90 + onChanged,
91 +}: {
92 + readonly environmentId: EnvironmentId;
93 + readonly definition: SourceControlDefinition;
94 + readonly appSignIn: SourceControlAppSignIn;
95 + /** The login discovery reports, which is the signed-in account when no token overrides it. */
96 + readonly account: string | null;
97 + readonly onChanged: () => void;
98 +}) {
99 + const host = appSignIn.hosts[0] ?? "";
100 + const { signIns, tokens } = useEnvironmentSettings(environmentId, (settings) =>
101 + readHostCredentialSettings(settings, definition.kind),
102 + );
103 + const signedIn = (signIns[host] ?? "").length > 0;
104 + const tokenOverrides = (tokens[host] ?? "").length > 0;
105 + const canSignIn = useAtomValue(
106 + sourceControlEnvironment.startSignIn.permissionAtom(environmentId),
107 + );
108 + const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
109 + const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
110 + const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
111 + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
112 + label: `sign out of ${appSignIn.appName}`,
113 + });
114 + const { copyToClipboard, isCopied } = useCopyToClipboard({
115 + timeout: 1500,
116 + target: "sign-in code",
117 + });
118 + const [state, setState] = useState<SignInState>({ status: "idle" });
119 +
120 + const signIn = async () => {
121 + setState({ status: "starting" });
122 + const input = { provider: definition.kind, host };
123 + const started = await start({ environmentId, input });
124 + if (started._tag !== "Success") {
125 + setState({ status: "failed", message: failureMessage(started.cause) });
126 + return;
127 + }
128 + const prompt = started.value;
129 + setState({ status: "waiting", prompt });
130 + const finished = await wait({ environmentId, input });
131 + // A newer attempt, a cancel, or a sign-out owns the state by now.
132 + setState((current) => {
133 + if (current.status !== "waiting" || current.prompt !== prompt) return current;
134 + return finished._tag === "Success"
135 + ? { status: "idle" }
136 + : { status: "failed", message: failureMessage(finished.cause) };
137 + });
138 + if (finished._tag === "Success") onChanged();
139 + };
140 +
141 + const signOut = async () => {
142 + setState({ status: "idle" });
143 + const result = await updateSettings({
144 + environmentId,
145 + // Send the whole map; other hosts' redaction markers preserve their sessions.
146 + input: {
147 + patch: {
148 + sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
149 + },
150 + },
151 + });
152 + if (result._tag === "Success") onChanged();
153 + };
154 +
155 + const waiting = !signedIn && state.status === "waiting" ? state.prompt : null;
156 +
157 + let subtitle: ReactNode;
158 + let action: ReactNode;
159 + if (signedIn) {
160 + subtitle =
161 + account !== null && !tokenOverrides ? (
162 + <span className="flex min-w-0 items-center gap-1">
163 + Signed in as
164 + <RedactedSensitiveText
165 + value={account}
166 + ariaLabel="Signed-in GitHub account"
167 + revealTooltip="Show account"
168 + hideTooltip="Hide account"
169 + />
170 + </span>
171 + ) : tokenOverrides ? (
172 + "Signed in, but the token saved below is used until you remove it."
173 + ) : (
174 + "Signed in"
175 + );
176 + action = (
177 + <Button size="xs" variant="outline" disabled={!canSignIn} onClick={() => void signOut()}>
178 + Sign out
179 + </Button>
180 + );
181 + } else if (waiting !== null) {
182 + subtitle = "Approve the app on GitHub to finish signing in.";
183 + action = (
184 + <Button
185 + size="xs"
186 + variant="ghost"
187 + onClick={() => {
188 + setState({ status: "idle" });
189 + void cancel({ environmentId, input: { provider: definition.kind, host } });
190 + }}
191 + >
192 + Cancel
193 + </Button>
194 + );
195 + } else {
196 + subtitle = "A far higher GitHub API rate limit than a personal token or gh login.";
197 + action = (
198 + <Button
199 + size="xs"
200 + disabled={!canSignIn || state.status === "starting"}
201 + onClick={() => void signIn()}
202 + >
203 + {state.status === "starting" ? <Spinner /> : null}
204 + {state.status === "failed" ? "Try again" : "Sign in with GitHub"}
205 + </Button>
206 + );
207 + }
208 +
209 + return (
210 + <div
211 + className={cn(
212 + "overflow-hidden rounded-xl border bg-card",
213 + state.status === "failed" && !signedIn ? "border-destructive/40" : "border-border",
214 + )}
215 + >
216 + <div className="flex items-center gap-3 p-3">
217 + <AppMark signedIn={signedIn} />
218 + <div className="min-w-0 flex-1 space-y-0.5">
219 + <p className="text-sm font-medium text-foreground">{appSignIn.appName}</p>
220 + <div className="text-xs text-muted-foreground">{subtitle}</div>
221 + </div>
222 + <div className="shrink-0">{action}</div>
223 + </div>
224 +
225 + {waiting !== null ? (
226 + <div className="grid gap-4 border-t border-border bg-muted/40 px-3 py-4 sm:grid-cols-[auto_1fr] sm:items-center sm:gap-6">
227 + <div className="flex items-center gap-2">
228 + <DeviceCode code={waiting.userCode} />
229 + <Button
230 + size="icon-xs"
231 + variant="ghost"
232 + aria-label="Copy code"
233 + onClick={() => copyToClipboard(waiting.userCode, undefined)}
234 + >
235 + <MorphIcon className="size-3.5" icon={isCopied ? Check : Copy} />
236 + </Button>
237 + </div>
238 + <div className="grid gap-2 sm:justify-items-end">
239 + <Button
240 + size="sm"
241 + render={
242 + <a href={waiting.verificationUri} target="_blank" rel="noreferrer noopener" />
243 + }
244 + onClick={() => copyToClipboard(waiting.userCode, undefined)}
245 + >
246 + Copy code & open GitHub
247 + <ExternalLinkIcon aria-hidden className="size-3.5" />
248 + </Button>
249 + <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
250 + <span aria-hidden className="size-1.5 rounded-full bg-warning" />
251 + Waiting for approval · code expires at {expiryTime(waiting.expiresAt)}
252 + </p>
253 + </div>
254 + </div>
255 + ) : null}
256 +
257 + {signedIn ? (
258 + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
259 + <span className="min-w-0 flex-1">
260 + Reaches repositories in accounts and organizations that installed the app.
261 + </span>
262 + <ExternalLink href={appSignIn.installUrl}>Install on an organization</ExternalLink>
263 + <ExternalLink href={appSignIn.revokeUrl}>Manage on GitHub</ExternalLink>
264 + </div>
265 + ) : null}
266 +
267 + {state.status === "failed" && !signedIn ? (
268 + <p
269 + role="alert"
270 + className="border-t border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive"
271 + >
272 + {state.message}
273 + </p>
274 + ) : null}
275 + </div>
276 + );
277 +}
apps/web/src/components/settings/SourceControlSettings.tsx
+18
@@ -32,6 +32,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
32 import { GitIcon, JujutsuIcon, type Icon } from "../Icons";
33 import { SourceControlHostSettings } from "./SourceControlHostSettings";
34 import { SourceControlAccountSettings } from "./SourceControlAccountSettings";
35 +import { SourceControlAppSignInSettings } from "./SourceControlAppSignInSettings";
36 import { SourceControlTokenSettings } from "./SourceControlTokenSettings";
37 import { RedactedSensitiveText } from "./RedactedSensitiveText";
38 import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
@@ -391,6 +392,23 @@ export function SourceControlSettingsPanel() {
392 return (
393 <SettingsSearchTarget id={sourceControlHostSettingsSearchId(item.kind)}>
394 <div className="grid gap-6">
395 + {credentials.appSignIn && item.appSignIn === true ? (
396 + <SourceControlAppSignInSettings
397 + key={`sign-in-${environmentId}`}
398 + environmentId={environmentId}
399 + definition={definition}
400 + appSignIn={credentials.appSignIn}
401 + account={Option.getOrNull(item.auth.account)}
402 + onChanged={handleScan}
403 + />
404 + ) : null}
405 + {credentials.appSignIn && item.appSignIn === true ? (
406 + <div className="flex items-center gap-3 text-2xs text-muted-foreground">
407 + <span aria-hidden className="h-px flex-1 bg-border" />
408 + Or use your own credentials
409 + <span aria-hidden className="h-px flex-1 bg-border" />
410 + </div>
411 + ) : null}
412 <SourceControlTokenSettings
413 key={`token-${environmentId}`}
414 environmentId={environmentId}
apps/web/src/components/sourceControlAppAccessToast.ts new
+38
@@ -0,0 +1,38 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import { appSignInTargetForRemote } from "@t3tools/client-runtime/source-control-clients";
3 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
4 +import { appAtomRegistry } from "../rpc/atomRegistry";
5 +import { sourceControlEnvironment } from "../state/sourceControl";
6 +import { toastManager } from "./ui/toast";
7 +
8 +/**
9 + * After a clone, suggests installing the forge app on the repository's owner when the server is
10 + * signed in with it but the app does not reach the repository.
11 + */
12 +export async function suggestAppAccessForRemote(
13 + environmentId: EnvironmentId,
14 + remoteUrl: string,
15 +): Promise<void> {
16 + const target = appSignInTargetForRemote(remoteUrl);
17 + if (target === null) return;
18 + const result = await runAtomCommand(
19 + appAtomRegistry,
20 + sourceControlEnvironment.checkAppAccess,
21 + { environmentId, input: target.input },
22 + { label: "check app access", reportFailure: false, reportDefect: false },
23 + );
24 + if (result._tag !== "Success" || result.value.status !== "not-covered") return;
25 + const owner = target.input.repository.split("/")[0] ?? target.input.repository;
26 + const id = toastManager.add({
27 + type: "info",
28 + title: `Give ${target.appSignIn.appName} access to ${owner}`,
29 + description: `It isn't installed there, so GitHub requests for ${target.input.repository} use your own login and its lower rate limit.`,
30 + actionProps: {
31 + children: "Install",
32 + onClick: () => {
33 + toastManager.close(id);
34 + window.open(target.appSignIn.installUrl, "_blank", "noopener,noreferrer");
35 + },
36 + },
37 + });
38 +}
apps/web/src/hooks/useNewProject.ts
+2
@@ -15,6 +15,7 @@ import { projectEnvironment } from "~/state/projects";
15 import { sourceControlEnvironment } from "~/state/sourceControl";
16 import { useAtomCommand } from "~/state/use-atom-command";
17 import { useNewThreadHandler } from "./useHandleNewThread";
18 +import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
19
20 function errorMessage(error: unknown): string {
21 return error instanceof Error && error.message.trim().length > 0
@@ -63,6 +64,7 @@ export function useNewProject() {
64 description: result.value.repository.nameWithOwner,
65 }),
66 );
67 + void suggestAppAccessForRemote(input.environmentId, result.value.remoteUrl);
68 };
69
70 return async (input: {
apps/web/src/lib/addProjectToMachine.ts
+2
@@ -13,6 +13,7 @@ import type {
13 import { create } from "zustand";
14
15 import { appAtomRegistry } from "../rpc/atomRegistry";
16 +import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
17 import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../state/projectClones";
18 import { projectEnvironment } from "../state/projects";
19 import { sourceControlEnvironment } from "../state/sourceControl";
@@ -143,6 +144,7 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
144 setFileCopy(copyKey, null);
145 throw new Error(failureMessage(started));
146 }
147 + void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl);
148 if (reads.length === 0) return;
149
150 void (async () => {
apps/web/src/rpc/requestLatencyState.ts
+3 -1
@@ -27,10 +27,12 @@ interface PendingRpcAckRequest {
27
28 const pendingRpcAckRequests = new Map<string, PendingRpcAckRequest>();
29 // Background reports nobody waits on. A busy host delays them first, and warning
30 -// about a request the user never made does not say what is wrong.
30 +// about a request the user never made does not say what is wrong. A sign-in wait
31 +// lasts as long as the user takes on the forge.
32 const untrackedRpcAckMethods = new Set<string>([
33 WS_METHODS.serverGetUsageSummary,
34 WS_METHODS.serverReportClientActivity,
35 + WS_METHODS.sourceControlSignInWait,
36 ]);
37 const longRunningRpcAckMethods = new Set<string>([
38 WS_METHODS.serverUpdateProvider,
apps/web/src/state/sourceControlActions.test.ts
+3
@@ -19,6 +19,9 @@ vi.mock("@effect/atom-react", () => ({
19 useAtomValue: () => ({ operation: null, error: null, isRunning: false }),
20 }));
21 vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
22 +vi.mock("../components/sourceControlAppAccessToast", () => ({
23 + suggestAppAccessForRemote: () => Promise.resolve(),
24 +}));
25 vi.mock("./session", () => ({
26 useEnvironmentScope: (environmentId: string, scope: string) =>
27 state.scopes.get(environmentId)?.has(scope) === true,
apps/web/src/state/sourceControlActions.ts
+6 -1
@@ -31,6 +31,7 @@ import { readEnvironmentScope, useEnvironmentScope } from "./session";
31 import { sourceControlEnvironment } from "./sourceControl";
32 import { useAtomCommand } from "./use-atom-command";
33 import { vcsActionManager, vcsEnvironment } from "./vcs";
34 +import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
35
36 export type SourceControlActionKind =
37 | "init"
@@ -286,13 +287,17 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi
287 ),
288 );
289 }
289 - return publishRepository({
290 + const result = await publishRepository({
291 environmentId: target.environmentId,
292 input: {
293 cwd: target.cwd,
294 ...input,
295 },
296 });
297 + if (result._tag === "Success") {
298 + void suggestAppAccessForRemote(target.environmentId, result.value.remoteUrl);
299 + }
300 + return result;
301 };
302 return useAction({
303 kind: "publishRepository",
packages/client-runtime/src/sourceControlClients.test.ts
+21 -1
@@ -1,7 +1,7 @@
1 import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3
4 -import { sourceControlClients } from "./sourceControlClients.ts";
4 +import { appSignInTargetForRemote, sourceControlClients } from "./sourceControlClients.ts";
5 import { normalizeThreadPullRequestKey } from "./threadPullRequests.ts";
6
7 const parse = (url: string) => {
@@ -366,3 +366,23 @@ describe("sourceControlClients.findByPublicDomain", () => {
366 expect(sourceControlClients.findByPublicHost("gist.github.com")).toBeUndefined();
367 });
368 });
369 +
370 +describe("appSignInTargetForRemote", () => {
371 + it("names the repository a GitHub remote points at, in the remote's casing", () => {
372 + for (const remote of [
373 + "https://github.com/octocat/Hello-World.git",
374 + "git@github.com:octocat/Hello-World.git",
375 + ]) {
376 + expect(appSignInTargetForRemote(remote)?.input).toEqual({
377 + provider: "github",
378 + host: "github.com",
379 + repository: "octocat/Hello-World",
380 + });
381 + }
382 + });
383 +
384 + it("skips hosts the app is not registered on", () => {
385 + expect(appSignInTargetForRemote("https://ghe.acme.test/acme/web.git")).toBeNull();
386 + expect(appSignInTargetForRemote("https://gitlab.com/acme/web.git")).toBeNull();
387 + });
388 +});
packages/client-runtime/src/sourceControlClients.ts
+32 -1
@@ -2,8 +2,11 @@ import { builtInSourceControlDefinitions } from "@t3tools/source-control-definit
2 import {
3 HostCredentialSettings,
4 readSourceControlHostSettings,
5 + type SourceControlAppSignIn,
6 + type SourceControlDefinition,
7 } from "@t3tools/source-control-core/shared/definition";
6 -import type { ServerSettings } from "@t3tools/contracts";
8 +import type { ServerSettings, SourceControlAppAccessInput } from "@t3tools/contracts";
9 +import { parseGitRemoteRepository } from "@t3tools/shared/git";
10
11 export {
12 isMonochromeSourceControlIcon,
@@ -14,6 +17,7 @@ export {
17 type HostCredentialSettings,
18 type ParsedChangeRequestUrl,
19 type ReferenceAutolink,
20 + type SourceControlAppSignIn,
21 type SourceControlDefinition,
22 type SourceControlHostCredentials,
23 type SourceControlIcon,
@@ -33,3 +37,30 @@ export function readHostCredentialSettings(
37 export function capitalizeTerm(term: string): string {
38 return term.charAt(0).toUpperCase() + term.slice(1);
39 }
40 +
41 +/** The repository a remote names, when its host has an app sign-in that could reach it. */
42 +export function appSignInTargetForRemote(remoteUrl: string): {
43 + readonly definition: SourceControlDefinition;
44 + readonly appSignIn: SourceControlAppSignIn;
45 + readonly input: SourceControlAppAccessInput;
46 +} | null {
47 + const parsed = parseGitRemoteRepository(remoteUrl);
48 + const provider = sourceControlClients.recognizeRemote(remoteUrl);
49 + const definition = provider ? sourceControlClients.find(provider.kind) : undefined;
50 + const appSignIn = definition?.credentials?.appSignIn;
51 + if (parsed === null || definition === undefined || appSignIn === undefined) return null;
52 + if (!appSignIn.hosts.includes(parsed.host)) return null;
53 + // The parser lowercases; keep the remote's own casing for display when it names the same path.
54 + const asWritten = remoteUrl
55 + .trim()
56 + .replace(/\.git\/?$/i, "")
57 + .split(/[/:]/)
58 + .slice(-2)
59 + .join("/");
60 + const repository = asWritten.toLowerCase() === parsed.path ? asWritten : parsed.path;
61 + return {
62 + definition,
63 + appSignIn,
64 + input: { provider: definition.kind, host: parsed.host, repository },
65 + };
66 +}
packages/client-runtime/src/state/sourceControl.ts
+22
@@ -21,6 +21,15 @@ export function createSourceControlEnvironmentAtoms<R, E>(
21 label: "environment-data:server:source-control-discovery",
22 tag: WS_METHODS.serverDiscoverSourceControl,
23 }),
24 + appAccess: createEnvironmentRpcQueryAtomFamily(runtime, {
25 + label: "environment-data:source-control:app-access",
26 + tag: WS_METHODS.sourceControlAppAccess,
27 + }),
28 + // One check, as after cloning, where no view keeps the query mounted.
29 + checkAppAccess: createEnvironmentRpcCommand(runtime, {
30 + label: "environment-data:source-control:check-app-access",
31 + tag: WS_METHODS.sourceControlAppAccess,
32 + }),
33 repository: createEnvironmentRpcQueryAtomFamily(runtime, {
34 label: "environment-data:source-control:repository",
35 tag: WS_METHODS.sourceControlLookupRepository,
@@ -56,6 +65,19 @@ export function createSourceControlEnvironmentAtoms<R, E>(
65 key: ({ environmentId }) => environmentId,
66 },
67 }),
68 + // Unscheduled: a pending sign-in waits on the user for minutes and must not hold up clones.
69 + startSignIn: createEnvironmentRpcCommand(runtime, {
70 + label: "environment-data:source-control:sign-in-start",
71 + tag: WS_METHODS.sourceControlSignInStart,
72 + }),
73 + waitForSignIn: createEnvironmentRpcCommand(runtime, {
74 + label: "environment-data:source-control:sign-in-wait",
75 + tag: WS_METHODS.sourceControlSignInWait,
76 + }),
77 + cancelSignIn: createEnvironmentRpcCommand(runtime, {
78 + label: "environment-data:source-control:sign-in-cancel",
79 + tag: WS_METHODS.sourceControlSignInCancel,
80 + }),
81 projectClones: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
82 label: "environment-data:source-control:project-clones",
83 tag: WS_METHODS.subscribeProjectClones,
packages/contracts/src/clientRpcPermissions.ts
+4
@@ -35,6 +35,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
35 [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope,
36 [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope,
37 [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope,
38 + // Signing in replaces the server's GitHub credential, as saving a token in Settings does.
39 + [WS_METHODS.sourceControlSignInStart]: AuthSettingsWriteScope,
40 + [WS_METHODS.sourceControlSignInWait]: AuthSettingsWriteScope,
41 + [WS_METHODS.sourceControlSignInCancel]: AuthSettingsWriteScope,
42 [WS_METHODS.projectCloneStart]: AuthSourceControlWriteScope,
43 [WS_METHODS.projectCloneCancel]: AuthSourceControlWriteScope,
44 [WS_METHODS.projectCloneRetry]: AuthSourceControlWriteScope,
packages/contracts/src/rpc.ts
+41
@@ -382,6 +382,12 @@ import {
382 SourceControlRepositoryError,
383 SourceControlRepositoryInfo,
384 SourceControlRepositoryLookupInput,
385 + SourceControlAppAccess,
386 + SourceControlAppAccessInput,
387 + SourceControlSignInError,
388 + SourceControlSignInInput,
389 + SourceControlSignInPrompt,
390 + SourceControlSignInResult,
391 } from "./sourceControl.ts";
392 import { VcsError } from "./vcs.ts";
393 import { Project, ProjectMutation, ProjectMutationError } from "./project.ts";
@@ -567,6 +573,10 @@ export const WS_METHODS = {
573 sourceControlLookupRepository: "sourceControl.lookupRepository",
574 sourceControlCloneRepository: "sourceControl.cloneRepository",
575 sourceControlPublishRepository: "sourceControl.publishRepository",
576 + sourceControlSignInStart: "sourceControl.signInStart",
577 + sourceControlSignInWait: "sourceControl.signInWait",
578 + sourceControlSignInCancel: "sourceControl.signInCancel",
579 + sourceControlAppAccess: "sourceControl.appAccess",
580 projectCloneStart: "projectClone.start",
581 projectCloneCancel: "projectClone.cancel",
582 projectCloneRetry: "projectClone.retry",
@@ -1182,6 +1192,33 @@ const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlClone
1192 error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),
1193 });
1194
1195 +// Starts a device-flow sign-in the server finishes on its own, so a client can leave meanwhile.
1196 +const WsSourceControlSignInStartRpc = Rpc.make(WS_METHODS.sourceControlSignInStart, {
1197 + payload: SourceControlSignInInput,
1198 + success: SourceControlSignInPrompt,
1199 + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]),
1200 +});
1201 +
1202 +// Resolves when the sign-in `signInStart` began ends, however long the user takes.
1203 +const WsSourceControlSignInWaitRpc = Rpc.make(WS_METHODS.sourceControlSignInWait, {
1204 + payload: SourceControlSignInInput,
1205 + success: SourceControlSignInResult,
1206 + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]),
1207 +});
1208 +
1209 +// Ends the sign-in `signInStart` began, so approving the code afterwards signs nothing in.
1210 +const WsSourceControlSignInCancelRpc = Rpc.make(WS_METHODS.sourceControlSignInCancel, {
1211 + payload: SourceControlSignInInput,
1212 + success: Schema.Void,
1213 + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]),
1214 +});
1215 +
1216 +const WsSourceControlAppAccessRpc = Rpc.make(WS_METHODS.sourceControlAppAccess, {
1217 + payload: SourceControlAppAccessInput,
1218 + success: SourceControlAppAccess,
1219 + error: EnvironmentAuthorizationError,
1220 +});
1221 +
1222 // Returns when the project exists and cloning starts; progress uses the subscription.
1223 const WsProjectCloneStartRpc = Rpc.make(WS_METHODS.projectCloneStart, {
1224 payload: ProjectCloneStartInput,
@@ -1981,6 +2018,10 @@ export const WsRpcGroup = RpcGroup.make(
2018 WsSourceControlLookupRepositoryRpc,
2019 WsSourceControlCloneRepositoryRpc,
2020 WsSourceControlPublishRepositoryRpc,
2021 + WsSourceControlSignInStartRpc,
2022 + WsSourceControlSignInWaitRpc,
2023 + WsSourceControlSignInCancelRpc,
2024 + WsSourceControlAppAccessRpc,
2025 WsProjectCloneStartRpc,
2026 WsProjectCloneCancelRpc,
2027 WsProjectCloneRetryRpc,
packages/contracts/src/sourceControl.ts
+59
@@ -155,6 +155,8 @@ export const SourceControlProviderDiscoveryItem = Schema.Struct({
155 kind: SourceControlProviderKind,
156 ...SourceControlDiscoverySharedFields,
157 auth: SourceControlProviderAuth,
158 + /** The server is configured to sign in through the host's app; clients offer it only then. */
159 + appSignIn: Schema.optionalKey(Schema.Boolean),
160 });
161 export type SourceControlProviderDiscoveryItem = typeof SourceControlProviderDiscoveryItem.Type;
162
@@ -182,6 +184,63 @@ export class SourceControlProviderError extends Schema.TaggedError<SourceControl
184 }
185 }
186
187 +export const SourceControlSignInInput = Schema.Struct({
188 + provider: SourceControlProviderKind,
189 + host: TrimmedNonEmptyString,
190 +});
191 +export type SourceControlSignInInput = typeof SourceControlSignInInput.Type;
192 +
193 +/** A device-flow code the user enters at `verificationUri` in any browser. */
194 +export const SourceControlSignInPrompt = Schema.Struct({
195 + userCode: TrimmedNonEmptyString,
196 + verificationUri: TrimmedNonEmptyString,
197 + expiresAt: Schema.Number,
198 +});
199 +export type SourceControlSignInPrompt = typeof SourceControlSignInPrompt.Type;
200 +
201 +export const SourceControlSignInResult = Schema.Struct({
202 + account: TrimmedNonEmptyString,
203 +});
204 +export type SourceControlSignInResult = typeof SourceControlSignInResult.Type;
205 +
206 +export const SourceControlSignInFailure = Schema.Literals([
207 + "unsupported",
208 + "not-started",
209 + "cancelled",
210 + "denied",
211 + "expired",
212 + "failed",
213 +]);
214 +export type SourceControlSignInFailure = typeof SourceControlSignInFailure.Type;
215 +
216 +export const SourceControlAppAccessInput = Schema.Struct({
217 + provider: SourceControlProviderKind,
218 + host: TrimmedNonEmptyString,
219 + repository: TrimmedNonEmptyString,
220 +});
221 +export type SourceControlAppAccessInput = typeof SourceControlAppAccessInput.Type;
222 +
223 +/** Whether the server's forge app sign-in reaches a repository; `signed-out` when not in use. */
224 +export const SourceControlAppAccess = Schema.Struct({
225 + status: Schema.Literals(["covered", "not-covered", "signed-out"]),
226 +});
227 +export type SourceControlAppAccess = typeof SourceControlAppAccess.Type;
228 +
229 +export class SourceControlSignInError extends Schema.TaggedError<SourceControlSignInError>()(
230 + "SourceControlSignInError",
231 + {
232 + provider: SourceControlProviderKind,
233 + host: Schema.String,
234 + reason: SourceControlSignInFailure,
235 + detail: Schema.String,
236 + cause: Schema.optional(Schema.Defect()),
237 + },
238 +) {
239 + override get message(): string {
240 + return this.detail;
241 + }
242 +}
243 +
244 export class SourceControlRepositoryError extends Schema.TaggedError<SourceControlRepositoryError>()(
245 "SourceControlRepositoryError",
246 {
packages/source-control-core/src/server/PullRequestProvider.ts
+2 -1
@@ -268,7 +268,8 @@ export interface ProviderRepositoryRef {
268
269 export interface PullRequestProviderApi {
270 readonly withVerifiedCredential?: <A, E, R>(
271 - input: { readonly cwd: string; readonly host: string },
271 + /** `repository` lets a host pick the credential that can reach it. */
272 + input: { readonly cwd: string; readonly host: string; readonly repository?: string },
273 use: (identity: {
274 readonly accountId: string;
275 readonly viewer: string;
packages/source-control-core/src/server/SourceControlHost.ts
+5
@@ -2,6 +2,7 @@ import type {
2 GitCommandError,
3 ServerSettings,
4 ServerSettingsError,
5 + ServerSettingsPatch,
6 VcsError,
7 VcsListRemotesResult,
8 VcsProcessExitFailureKind,
@@ -67,6 +68,10 @@ export class SourceControlHost extends Context.Service<
68 readonly settings: {
69 /** Read fresh on each call to pick up credential changes. */
70 readonly get: Effect.Effect<ServerSettings, ServerSettingsError>;
71 + /** For credentials the host obtains itself, such as a sign-in it refreshes. */
72 + readonly update: (
73 + patch: ServerSettingsPatch,
74 + ) => Effect.Effect<ServerSettings, ServerSettingsError>;
75 };
76 readonly process: {
77 readonly run: (
packages/source-control-core/src/server/driver.ts
+27 -1
@@ -1,4 +1,10 @@
1 -import type { SourceControlProviderKind } from "@t3tools/contracts";
1 +import type {
2 + SourceControlAppAccess,
3 + SourceControlProviderKind,
4 + SourceControlSignInError,
5 + SourceControlSignInPrompt,
6 + SourceControlSignInResult,
7 +} from "@t3tools/contracts";
8 import type * as Crypto from "effect/Crypto";
9 import * as Effect from "effect/Effect";
10 import type * as FileSystem from "effect/FileSystem";
@@ -21,6 +27,25 @@ export interface SourceControlMediaRequest {
27 readonly headers: Readonly<Record<string, string>>;
28 }
29
30 +/** The server side of a definition's `credentials.appSignIn`. */
31 +export interface SourceControlSignIn {
32 + /** Replaces any sign-in already pending for `host`; the driver finishes it on its own. */
33 + readonly start: (
34 + host: string,
35 + ) => Effect.Effect<SourceControlSignInPrompt, SourceControlSignInError>;
36 + /** The outcome of the latest sign-in `start` began for `host`, waiting for it if pending. */
37 + readonly wait: (
38 + host: string,
39 + ) => Effect.Effect<SourceControlSignInResult, SourceControlSignInError>;
40 + /** Ends the sign-in pending for `host`; its `wait` fails as cancelled. */
41 + readonly cancel: (host: string) => Effect.Effect<void>;
42 + /** Whether the sign-in reaches `owner/name`, so clients can suggest installing the app there. */
43 + readonly access: (
44 + host: string,
45 + repository: string,
46 + ) => Effect.Effect<SourceControlAppAccess["status"]>;
47 +}
48 +
49 export interface SourceControlDriverInstance {
50 readonly sourceControl: SourceControlProvider.SourceControlProvider["Service"];
51 readonly discovery: SourceControlProviderDiscoverySpec;
@@ -37,6 +62,7 @@ export interface SourceControlDriverInstance {
62 HttpClientError.HttpClientError,
63 Scope.Scope
64 >;
65 + readonly signIn?: SourceControlSignIn;
66 }
67
68 /** What the server gives every driver. A driver builds anything else it needs itself. */
packages/source-control-core/src/shared/definition.ts
+23
@@ -166,6 +166,23 @@ export interface SourceControlHostCredentials {
166 /** What a token must be granted, completing "Give it …". */
167 readonly tokenAccess: string;
168 readonly newTokenUrl: (host: string) => string;
169 + /** Signing in through the forge's own app instead of a token or CLI login. */
170 + readonly appSignIn?: SourceControlAppSignIn;
171 +}
172 +
173 +/**
174 + * A forge app the server signs in to with a device code, on the hosts it is registered on. The
175 + * session it keeps is the `signIns` setting, which takes precedence over everything but a saved
176 + * token.
177 + */
178 +export interface SourceControlAppSignIn {
179 + /** The app's name on the forge, as the consent screen shows it. */
180 + readonly appName: string;
181 + readonly hosts: ReadonlyArray<string>;
182 + /** Where an account or organization installs the app so it can reach its repositories. */
183 + readonly installUrl: string;
184 + /** Where the user revokes the app's access entirely. */
185 + readonly revokeUrl: string;
186 }
187
188 export const SourceControlHostName = TrimmedNonEmptyString.pipe(
@@ -189,6 +206,12 @@ export const hostCredentialSettingsFields = {
206 secretSetting,
207 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
208 ),
209 + /** The serialized session of an `appSignIn`, owned by the server's driver. */
210 + signIns: Schema.Record(SourceControlHostName, TrimmedString).pipe(
211 + Schema.withDecodingDefault(Effect.succeed({})),
212 + secretSetting,
213 + Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
214 + ),
215 };
216
217 export const HostCredentialSettings = Schema.Struct(hostCredentialSettingsFields);
packages/source-control-github/scripts/measure-pr-preview.ts
+2
@@ -13,6 +13,7 @@ import * as Stream from "effect/Stream";
13 import { FetchHttpClient, HttpClient } from "effect/http";
14 import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16 +import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts";
17 import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts";
18 import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts";
19 import * as GitHubRest from "../src/server/GitHubRest.ts";
@@ -99,6 +100,7 @@ const sourceControlHost = Layer.unwrap(
100 ).pipe(Layer.provideMerge(NodeServices.layer));
101
102 const services = GitHubPullRequestApi.layer.pipe(
103 + Layer.provideMerge(GitHubAppAccess.layer),
104 Layer.provideMerge(GitHubRest.layerWithDependencies),
105 Layer.provideMerge(SourceControlRateLimit.layer),
106 Layer.provideMerge(measuredHttp),
packages/source-control-github/src/server/GitHubAppAccess.ts new
+216
@@ -0,0 +1,216 @@
1 +import * as Cache from "effect/Cache";
2 +import * as Context from "effect/Context";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Layer from "effect/Layer";
7 +import * as Option from "effect/Option";
8 +import * as Schema from "effect/Schema";
9 +
10 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
11 +import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
12 +import * as GitHubRest from "./GitHubRest.ts";
13 +
14 +const Installations = Schema.fromJsonString(
15 + Schema.Struct({
16 + installations: Schema.Array(
17 + Schema.Struct({
18 + id: Schema.Number,
19 + repository_selection: Schema.String,
20 + account: Schema.NullOr(Schema.Struct({ login: Schema.String })),
21 + }),
22 + ),
23 + }),
24 +);
25 +
26 +const InstallationRepositories = Schema.fromJsonString(
27 + Schema.Struct({ repositories: Schema.Array(Schema.Struct({ full_name: Schema.String })) }),
28 +);
29 +
30 +const Viewer = Schema.fromJsonString(Schema.Struct({ login: Schema.String }));
31 +
32 +const PAGE_SIZE = 100;
33 +const MAX_PAGES = 10;
34 +// Installing the app on another account should show up soon after the user comes back.
35 +const COVERAGE_TTL = Duration.minutes(2);
36 +// A failed read answers `covered`; keep that briefly so an outage is not re-asked per request.
37 +const COVERAGE_FAILURE_TTL = Duration.seconds(30);
38 +
39 +/** Whether the app sign-in reaches a repository; `signed-out` when the server is not signed in. */
40 +export type GitHubAppReach = "covered" | "not-covered" | "signed-out";
41 +
42 +/** Accounts that installed the app for all repositories, and repositories listed one by one. */
43 +interface AppCoverage {
44 + readonly accounts: ReadonlySet<string>;
45 + readonly repositories: ReadonlySet<string>;
46 +}
47 +
48 +export class GitHubAppAccess extends Context.Service<
49 + GitHubAppAccess,
50 + {
51 + /**
52 + * Whether an installation covers `owner/name`. A check that fails answers `covered`, so a
53 + * GitHub hiccup does not nag the user.
54 + */
55 + readonly reach: (host: string, repository: string) => Effect.Effect<GitHubAppReach>;
56 + /** The login the app sign-in acts as. */
57 + readonly viewer: (host: string) => Effect.Effect<string, GitHubRequestPolicy.GitHubApiError>;
58 + /**
59 + * The credential for work pinned to one repository: the app's only where an installation is
60 + * confirmed to cover it, the user's own otherwise when there is one.
61 + */
62 + readonly credentialFor: (
63 + host: string,
64 + repository: string,
65 + ) => Effect.Effect<
66 + GitHubRequestPolicy.GitHubHeldCredential,
67 + GitHubRequestPolicy.GitHubApiError
68 + >;
69 + }
70 +>()("@t3tools/source-control-github/server/GitHubAppAccess") {}
71 +
72 +/** Callers may name a repository as a URL, `host/owner/name` or `owner/name.git`. */
73 +function ownerAndName(repository: string): string {
74 + return repository
75 + .trim()
76 + .toLowerCase()
77 + .replace(/\.git\/?$/, "")
78 + .split(/[/:]/)
79 + .filter((segment) => segment.length > 0)
80 + .slice(-2)
81 + .join("/");
82 +}
83 +
84 +/** @public */
85 +export const make = Effect.gen(function* () {
86 + const api = yield* GitHubRest.GitHubRest;
87 + const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
88 +
89 + /** Reads `path` as the app sign-in, whatever credential outranks it elsewhere. */
90 + const readAsApp = Effect.fn("GitHubAppAccess.readAsApp")(function* <A>(
91 + host: string,
92 + operation: string,
93 + path: string,
94 + schema: Schema.Codec<A, string>,
95 + ) {
96 + const app = yield* api.appCredential(host);
97 + if (Option.isNone(app)) return Option.none<A>();
98 + const response = yield* api.rest({ host, operation, path, allowReserve: true }).pipe(
99 + Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
100 + host,
101 + token: app.value.token,
102 + credentialFingerprint: app.value.fingerprint,
103 + }),
104 + );
105 + return Option.some(yield* Schema.decodeEffect(schema)(response.body));
106 + });
107 +
108 + const coverageOf = Effect.fn("GitHubAppAccess.coverageOf")(function* (host: string) {
109 + const installations: Array<{
110 + readonly id: number;
111 + readonly repository_selection: string;
112 + readonly account: { readonly login: string } | null;
113 + }> = [];
114 + for (let page = 1; page <= MAX_PAGES; page++) {
115 + const listed = yield* readAsApp(
116 + host,
117 + "appInstallations",
118 + `user/installations?per_page=${PAGE_SIZE}&page=${page}`,
119 + Installations,
120 + );
121 + if (Option.isNone(listed)) return null;
122 + installations.push(...listed.value.installations);
123 + if (listed.value.installations.length < PAGE_SIZE) break;
124 + }
125 + const accounts = new Set<string>();
126 + const repositories = new Set<string>();
127 + for (const installation of installations) {
128 + const login = installation.account?.login.toLowerCase();
129 + if (login === undefined) continue;
130 + if (installation.repository_selection === "all") {
131 + accounts.add(login);
132 + continue;
133 + }
134 + for (let page = 1; ; page++) {
135 + // Past the cap the list is cut short; count the whole account as reached rather than nag.
136 + if (page > MAX_PAGES) {
137 + accounts.add(login);
138 + break;
139 + }
140 + const listed = yield* readAsApp(
141 + host,
142 + "appInstallationRepositories",
143 + `user/installations/${installation.id}/repositories?per_page=${PAGE_SIZE}&page=${page}`,
144 + InstallationRepositories,
145 + );
146 + if (Option.isNone(listed)) return null;
147 + for (const repository of listed.value.repositories) {
148 + repositories.add(repository.full_name.toLowerCase());
149 + }
150 + if (listed.value.repositories.length < PAGE_SIZE) break;
151 + }
152 + }
153 + return { accounts, repositories } satisfies AppCoverage;
154 + });
155 +
156 + const coverage = yield* Cache.makeWith(coverageOf, {
157 + capacity: 8,
158 + timeToLive: (exit) => (Exit.isSuccess(exit) ? COVERAGE_TTL : COVERAGE_FAILURE_TTL),
159 + });
160 +
161 + /** `unknown` when GitHub could not list the installations just now. */
162 + const coverageFor = Effect.fn("GitHubAppAccess.coverageFor")(function* (
163 + rawHost: string,
164 + rawRepository: string,
165 + ) {
166 + const host = rawHost.trim().toLowerCase();
167 + if (!appSignIn.enabled) return "signed-out" as const;
168 + const known = yield* Cache.get(coverage, host).pipe(Effect.option);
169 + if (Option.isNone(known)) return "unknown" as const;
170 + if (known.value === null) return "signed-out" as const;
171 + const repository = ownerAndName(rawRepository);
172 + const owner = repository.split("/")[0] ?? "";
173 + return known.value.accounts.has(owner) || known.value.repositories.has(repository)
174 + ? ("covered" as const)
175 + : ("not-covered" as const);
176 + });
177 +
178 + const reach: GitHubAppAccess["Service"]["reach"] = (host, repository) =>
179 + coverageFor(host, repository).pipe(
180 + Effect.map((answer) => (answer === "unknown" ? "covered" : answer)),
181 + );
182 +
183 + const viewer: GitHubAppAccess["Service"]["viewer"] = Effect.fn("GitHubAppAccess.viewer")(
184 + function* (rawHost) {
185 + const host = rawHost.trim().toLowerCase();
186 + // A new sign-in can reach different installations than the cached answer.
187 + yield* Cache.invalidate(coverage, host);
188 + const login = yield* readAsApp(host, "appViewer", "user", Viewer).pipe(
189 + Effect.catchTags({
190 + SchemaError: () => Effect.succeed(Option.none<{ readonly login: string }>()),
191 + }),
192 + );
193 + if (Option.isNone(login)) {
194 + return yield* new GitHubRequestPolicy.GitHubApiAuthenticationError({
195 + host,
196 + operation: "appViewer",
197 + });
198 + }
199 + return login.value.login;
200 + },
201 + );
202 +
203 + const credentialFor: GitHubAppAccess["Service"]["credentialFor"] = Effect.fn(
204 + "GitHubAppAccess.credentialFor",
205 + )(function* (host, repository) {
206 + // Pinned work cannot be handed on, so only confirmed app access keeps the app credential.
207 + if ((yield* coverageFor(host, repository)) === "covered") return yield* api.credential(host);
208 + return yield* api
209 + .credential(host, { personal: true })
210 + .pipe(Effect.catch(() => api.credential(host)));
211 + });
212 +
213 + return GitHubAppAccess.of({ reach, viewer, credentialFor });
214 +});
215 +
216 +export const layer = Layer.effect(GitHubAppAccess, make);
packages/source-control-github/src/server/GitHubAppSignIn.test.ts new
+593
@@ -0,0 +1,593 @@
1 +import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 +import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
3 +import * as Deferred from "effect/Deferred";
4 +import * as Effect from "effect/Effect";
5 +import * as Fiber from "effect/Fiber";
6 +import * as Layer from "effect/Layer";
7 +import * as Option from "effect/Option";
8 +import * as Redacted from "effect/Redacted";
9 +import { HttpClient, HttpClientResponse } from "effect/http";
10 +import { ChildProcessSpawner } from "effect/process";
11 +import * as TestClock from "effect/testing/TestClock";
12 +
13 +import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts";
14 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
15 +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
16 +import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
17 +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
18 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
19 +
20 +import * as GitHubClient from "../shared/definition.ts";
21 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
22 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
23 +import * as GitHubRest from "./GitHubRest.ts";
24 +
25 +type Reply = { readonly status?: number; readonly body: unknown };
26 +interface Sent {
27 + readonly host: string;
28 + readonly path: string;
29 + readonly form: URLSearchParams;
30 + /** The bearer token, if any. */
31 + readonly token: string | undefined;
32 +}
33 +
34 +const HOUR = 3_600_000;
35 +
36 +const session = (overrides: Record<string, unknown> = {}) =>
37 + JSON.stringify({
38 + accessToken: "ghu_current",
39 + accessTokenExpiresAt: 8 * HOUR,
40 + refreshToken: "ghr_current",
41 + refreshTokenExpiresAt: 4_000 * HOUR,
42 + ...overrides,
43 + });
44 +
45 +/** The whole GitHub request stack over a fake GitHub that `handle` answers. */
46 +function harness(options: {
47 + readonly handle: (sent: Sent) => Reply;
48 + readonly signIns?: Record<string, string>;
49 + readonly tokens?: Record<string, string>;
50 + /** Without one, the server has no `gh` login to fall back to. */
51 + readonly ghSignedIn?: boolean;
52 + /** Makes every settings write fail, as a full disk would. */
53 + readonly settingsWritesFail?: boolean;
54 + /** Holds a request open until it completes, to interleave other work with it. */
55 + readonly gate?: (sent: Sent) => Effect.Effect<void>;
56 +}) {
57 + const requests: Array<Sent> = [];
58 + const http = HttpClient.make((request) => {
59 + const url = new URL(request.url);
60 + const sent: Sent = {
61 + host: url.host,
62 + path: url.pathname,
63 + form: new URLSearchParams(
64 + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
65 + ),
66 + token: request.headers["authorization"]?.replace(/^Bearer /, ""),
67 + };
68 + return Effect.suspend(() => options.gate?.(sent) ?? Effect.void).pipe(
69 + Effect.map(() => {
70 + requests.push(sent);
71 + const reply = options.handle(sent);
72 + return HttpClientResponse.fromWeb(
73 + request,
74 + new Response(JSON.stringify(reply.body), {
75 + status: reply.status ?? 200,
76 + headers: { "content-type": "application/json" },
77 + }),
78 + );
79 + }),
80 + );
81 + });
82 + const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = () =>
83 + Effect.succeed({
84 + exitCode: ChildProcessSpawner.ExitCode(0),
85 + stdout: options.ghSignedIn === false ? "" : "gh-token\n",
86 + stderr: "",
87 + stdoutTruncated: false,
88 + stderrTruncated: false,
89 + });
90 + const host = TestSourceControlHost.layer({
91 + settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
92 + sourceControlHosts: {
93 + github: { signIns: options.signIns ?? {}, tokens: options.tokens ?? {} },
94 + },
95 + }),
96 + process: { run },
97 + });
98 + const failingWrites = Layer.effect(
99 + SourceControlHost.SourceControlHost,
100 + Effect.map(Effect.service(SourceControlHost.SourceControlHost), (service) => ({
101 + ...service,
102 + settings: {
103 + ...service.settings,
104 + update: () =>
105 + Effect.fail(
106 + new ServerSettingsError({ settingsPath: "settings.json", operation: "write-file" }),
107 + ),
108 + },
109 + })),
110 + ).pipe(Layer.provideMerge(host));
111 + const layer = GitHubAppAccess.layer.pipe(
112 + Layer.provideMerge(GitHubRest.layerWithDependencies),
113 + Layer.provideMerge(SourceControlRateLimit.layer),
114 + Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host),
115 + Layer.provide(NodeCrypto.layer),
116 + Layer.provide(Layer.succeed(HttpClient.HttpClient, http)),
117 + );
118 + return { layer, requests };
119 +}
120 +
121 +const savedSignIns = Effect.gen(function* () {
122 + const host = yield* SourceControlHost.SourceControlHost;
123 + const settings = yield* host.settings.get;
124 + return readSourceControlHostSettings(GitHubClient.settings, settings.sourceControlHosts.github)
125 + .signIns;
126 +});
127 +
128 +/** A REST read through the request policy, answering with the token it went out with. */
129 +const readUser = Effect.gen(function* () {
130 + const api = yield* GitHubRest.GitHubRest;
131 + return yield* api.rest({ host: "github.com", operation: "test", path: "user" });
132 +});
133 +
134 +const deviceCode = {
135 + device_code: "device-1",
136 + user_code: "ABCD-1234",
137 + verification_uri: "https://github.com/login/device",
138 + expires_in: 900,
139 + interval: 5,
140 +};
141 +
142 +const installedOn = (sent: Sent): Reply =>
143 + sent.path === "/user/installations"
144 + ? {
145 + body: {
146 + installations: [
147 + { id: 1, repository_selection: "all", account: { login: "pingdotgg" } },
148 + { id: 2, repository_selection: "selected", account: { login: "acme" } },
149 + ],
150 + },
151 + }
152 + : sent.path === "/user/installations/2/repositories"
153 + ? { body: { repositories: [{ full_name: "acme/one" }] } }
154 + : { status: 404, body: {} };
155 +
156 +beforeEach(() => {
157 + for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, "");
158 + vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client");
159 +});
160 +afterEach(() => {
161 + vi.unstubAllEnvs();
162 +});
163 +
164 +describe("GitHubAppSignIn", () => {
165 + it.effect("finishes a device-flow sign-in and saves the session", () => {
166 + const answers = [
167 + { error: "authorization_pending" },
168 + { error: "slow_down", interval: 10 },
169 + {
170 + access_token: "ghu_new",
171 + expires_in: 28_800,
172 + refresh_token: "ghr_new",
173 + refresh_token_expires_in: 15_897_600,
174 + },
175 + ];
176 + const { layer, requests } = harness({
177 + handle: (sent) =>
178 + sent.path === "/login/device/code" ? { body: deviceCode } : { body: answers.shift() },
179 + });
180 + return Effect.gen(function* () {
181 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
182 + expect(yield* signIn.start("github.com")).toEqual({
183 + userCode: "ABCD-1234",
184 + verificationUri: "https://github.com/login/device",
185 + expiresAt: 900_000,
186 + });
187 + const waiting = yield* Effect.forkChild(signIn.wait("github.com"));
188 + yield* TestClock.adjust("20 seconds");
189 + yield* Fiber.join(waiting);
190 +
191 + // `slow_down` stretches the interval: polls at 5s, 10s, then 20s.
192 + const polls = requests.filter((sent) => sent.path === "/login/oauth/access_token");
193 + expect(polls).toHaveLength(3);
194 + expect(polls[0]?.form.get("client_id")).toBe("Iv-test-client");
195 + expect(polls[0]?.form.get("device_code")).toBe("device-1");
196 + expect(JSON.parse((yield* savedSignIns)["github.com"] ?? "")).toEqual({
197 + accessToken: "ghu_new",
198 + accessTokenExpiresAt: 20_000 + 28_800_000,
199 + refreshToken: "ghr_new",
200 + refreshTokenExpiresAt: 20_000 + 15_897_600_000,
201 + });
202 + }).pipe(Effect.provide(layer));
203 + });
204 +
205 + it.effect("reports a sign-in cancelled on GitHub and saves nothing", () => {
206 + const { layer } = harness({
207 + handle: (sent) =>
208 + sent.path === "/login/device/code"
209 + ? { body: deviceCode }
210 + : { body: { error: "access_denied" } },
211 + });
212 + return Effect.gen(function* () {
213 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
214 + yield* signIn.start("github.com");
215 + const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
216 + yield* TestClock.adjust("5 seconds");
217 + expect((yield* Fiber.join(waiting)).reason).toBe("denied");
218 + expect(yield* savedSignIns).toEqual({});
219 + }).pipe(Effect.provide(layer));
220 + });
221 +
222 + it.effect("expires a code nobody entered", () => {
223 + const { layer } = harness({
224 + handle: (sent) =>
225 + sent.path === "/login/device/code"
226 + ? { body: { ...deviceCode, expires_in: 12 } }
227 + : { body: { error: "authorization_pending" } },
228 + });
229 + return Effect.gen(function* () {
230 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
231 + yield* signIn.start("github.com");
232 + const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
233 + yield* TestClock.adjust("15 seconds");
234 + expect((yield* Fiber.join(waiting)).reason).toBe("expired");
235 + }).pipe(Effect.provide(layer));
236 + });
237 +
238 + it.effect("cancels a sign-in so approving the code afterwards saves nothing", () => {
239 + const { layer, requests } = harness({
240 + handle: (sent) =>
241 + sent.path === "/login/device/code"
242 + ? { body: deviceCode }
243 + : { body: { access_token: "ghu_new", expires_in: 28_800 } },
244 + });
245 + return Effect.gen(function* () {
246 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
247 + yield* signIn.start("github.com");
248 + const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
249 + yield* signIn.cancel("github.com");
250 + yield* TestClock.adjust("10 seconds");
251 + expect((yield* Fiber.join(waiting)).reason).toBe("cancelled");
252 + expect(requests.map((sent) => sent.path)).toEqual(["/login/device/code"]);
253 + expect(yield* savedSignIns).toEqual({});
254 + }).pipe(Effect.provide(layer));
255 + });
256 +
257 + it.effect("refuses hosts the app is not registered on", () => {
258 + const { layer, requests } = harness({ handle: () => ({ body: {} }) });
259 + return Effect.gen(function* () {
260 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
261 + expect((yield* Effect.flip(signIn.start("ghe.acme.test"))).reason).toBe("unsupported");
262 + expect((yield* Effect.flip(signIn.wait("github.com"))).reason).toBe("not-started");
263 + expect(requests).toEqual([]);
264 + }).pipe(Effect.provide(layer));
265 + });
266 +
267 + it.effect("does nothing with the app when the server has no client ID", () => {
268 + vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "");
269 + const { layer, requests } = harness({
270 + signIns: { "github.com": session() },
271 + handle: () => ({ body: { login: "octocat" } }),
272 + });
273 + return Effect.gen(function* () {
274 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
275 + expect(signIn.enabled).toBe(false);
276 + expect((yield* Effect.flip(signIn.start("github.com"))).reason).toBe("unsupported");
277 + expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).reach("github.com", "acme/one")).toBe(
278 + "signed-out",
279 + );
280 + // A session saved while it was on stays put but is not used.
281 + yield* readUser;
282 + expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]);
283 + expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
284 + }).pipe(Effect.provide(layer));
285 + });
286 +
287 + describe("refresh", () => {
288 + const refreshed = {
289 + access_token: "ghu_refreshed",
290 + expires_in: 28_800,
291 + refresh_token: "ghr_refreshed",
292 + refresh_token_expires_in: 15_897_600,
293 + };
294 +
295 + it.effect("refreshes an expiring token once for concurrent requests", () => {
296 + const { layer, requests } = harness({
297 + signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
298 + handle: () => ({ body: refreshed }),
299 + });
300 + return Effect.gen(function* () {
301 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
302 + const tokens = yield* Effect.all([signIn.token("github.com"), signIn.token("github.com")], {
303 + concurrency: "unbounded",
304 + });
305 + expect(tokens).toEqual([Option.some("ghu_refreshed"), Option.some("ghu_refreshed")]);
306 + expect(requests).toHaveLength(1);
307 + expect(requests[0]?.form.get("grant_type")).toBe("refresh_token");
308 + expect(requests[0]?.form.get("refresh_token")).toBe("ghr_current");
309 + }).pipe(Effect.provide(layer));
310 + });
311 +
312 + it.effect("refreshes a token GitHub refused, and only that one", () => {
313 + const { layer, requests } = harness({
314 + signIns: { "github.com": session() },
315 + handle: () => ({ body: refreshed }),
316 + });
317 + return Effect.gen(function* () {
318 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
319 + yield* signIn.invalidate("github.com", "gh-token");
320 + expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current"));
321 + yield* signIn.invalidate("github.com", "ghu_current");
322 + expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_refreshed"));
323 + expect(requests).toHaveLength(1);
324 + }).pipe(Effect.provide(layer));
325 + });
326 +
327 + it.effect("signs out when GitHub refuses the refresh token", () => {
328 + const { layer } = harness({
329 + signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
330 + handle: () => ({ body: { error: "bad_refresh_token" } }),
331 + });
332 + return Effect.gen(function* () {
333 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
334 + expect(yield* signIn.token("github.com")).toEqual(Option.none());
335 + expect(yield* savedSignIns).toEqual({});
336 + }).pipe(Effect.provide(layer));
337 + });
338 +
339 + it.effect("keeps the session when a refresh fails for another reason", () => {
340 + const { layer } = harness({
341 + signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
342 + handle: () => ({ body: { error: "unauthorized_client" } }),
343 + });
344 + return Effect.gen(function* () {
345 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
346 + expect((yield* Effect.flip(signIn.token("github.com")))._tag).toBe("GitHubAppSessionError");
347 + expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
348 + }).pipe(Effect.provide(layer));
349 + });
350 +
351 + it.effect("serves the still-valid token when a refresh ahead of expiry fails", () => {
352 + const { layer } = harness({
353 + signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
354 + handle: () => ({ status: 502, body: {} }),
355 + });
356 + return Effect.gen(function* () {
357 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
358 + expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current"));
359 + }).pipe(Effect.provide(layer));
360 + });
361 +
362 + it.effect("serves a refreshed token GitHub issued even when saving it fails", () => {
363 + const { layer } = harness({
364 + signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
365 + settingsWritesFail: true,
366 + handle: () => ({ body: refreshed }),
367 + });
368 + return Effect.gen(function* () {
369 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
370 + const pending = yield* Effect.forkChild(signIn.token("github.com"));
371 + yield* TestClock.adjust("1 second");
372 + expect(yield* Fiber.join(pending)).toEqual(Option.some("ghu_refreshed"));
373 + }).pipe(Effect.provide(layer));
374 + });
375 +
376 + it.effect("does not bring a session back that was signed out while it refreshed", () => {
377 + const released = Deferred.makeUnsafe<void>();
378 + const requested = Deferred.makeUnsafe<void>();
379 + const { layer } = harness({
380 + signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
381 + gate: () =>
382 + Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(released))),
383 + handle: () => ({ body: refreshed }),
384 + });
385 + return Effect.gen(function* () {
386 + const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
387 + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
388 + const refreshing = yield* Effect.forkChild(signIn.token("github.com"));
389 + yield* Deferred.await(requested);
390 + yield* settings.update({ sourceControlHosts: { github: { signIns: {} } } });
391 + yield* Deferred.succeed(released, undefined);
392 + expect(yield* Fiber.join(refreshing)).toEqual(Option.none());
393 + expect(yield* savedSignIns).toEqual({});
394 + }).pipe(Effect.provide(layer));
395 + });
396 + });
397 +});
398 +
399 +describe("GitHub requests with the app sign-in", () => {
400 + const answerUser = (sent: Sent): Reply => ({ body: { login: sent.token ?? "anonymous" } });
401 +
402 + it.effect("uses the app before GH_TOKEN and gh, and a saved token before the app", () => {
403 + vi.stubEnv("GH_TOKEN", "from-env");
404 + const signedIn = harness({ signIns: { "github.com": session() }, handle: answerUser });
405 + const withToken = harness({
406 + signIns: { "github.com": session() },
407 + tokens: { "github.com": "saved-pat" },
408 + handle: answerUser,
409 + });
410 + return Effect.gen(function* () {
411 + yield* readUser.pipe(Effect.provide(signedIn.layer));
412 + yield* readUser.pipe(Effect.provide(withToken.layer));
413 + expect(signedIn.requests.map((sent) => sent.token)).toEqual(["ghu_current"]);
414 + expect(withToken.requests.map((sent) => sent.token)).toEqual(["saved-pat"]);
415 + });
416 + });
417 +
418 + it.effect("asks again with the user's own credential when the app gets not found", () => {
419 + const { layer, requests } = harness({
420 + signIns: { "github.com": session() },
421 + handle: (sent) =>
422 + sent.token === "ghu_current" ? { status: 404, body: {} } : answerUser(sent),
423 + });
424 + return Effect.gen(function* () {
425 + const response = yield* readUser;
426 + expect(JSON.parse(response.body)).toEqual({ login: "gh-token" });
427 + expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]);
428 + }).pipe(Effect.provide(layer));
429 + });
430 +
431 + it.effect("asks again when GitHub says the resource is not accessible by integration", () => {
432 + const { layer, requests } = harness({
433 + signIns: { "github.com": session() },
434 + handle: (sent) =>
435 + sent.token === "ghu_current"
436 + ? { status: 403, body: { message: "Resource not accessible by integration" } }
437 + : answerUser(sent),
438 + });
439 + return Effect.gen(function* () {
440 + yield* readUser;
441 + expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]);
442 + }).pipe(Effect.provide(layer));
443 + });
444 +
445 + it.effect("keeps the app's answer when there is no other credential", () => {
446 + const { layer, requests } = harness({
447 + signIns: { "github.com": session() },
448 + ghSignedIn: false,
449 + handle: () => ({ status: 404, body: {} }),
450 + });
451 + return Effect.gen(function* () {
452 + expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError");
453 + expect(requests.map((sent) => sent.token)).toEqual(["ghu_current"]);
454 + }).pipe(Effect.provide(layer));
455 + });
456 +
457 + it.effect("does not ask again after the user's own credential is refused", () => {
458 + const { layer, requests } = harness({ handle: () => ({ status: 404, body: {} }) });
459 + return Effect.gen(function* () {
460 + expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError");
461 + expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]);
462 + }).pipe(Effect.provide(layer));
463 + });
464 +
465 + it.effect("uses the gh login while the app session cannot refresh, and keeps the session", () => {
466 + const { layer, requests } = harness({
467 + signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
468 + handle: (sent) => (sent.host === "github.com" ? { status: 502, body: {} } : answerUser(sent)),
469 + });
470 + return Effect.gen(function* () {
471 + yield* readUser;
472 + expect(requests.filter((sent) => sent.path === "/user").map((sent) => sent.token)).toEqual([
473 + "gh-token",
474 + ]);
475 + expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
476 + }).pipe(Effect.provide(layer));
477 + });
478 +
479 + it.effect("refreshes the app token after GitHub rejects it", () => {
480 + let rejected = false;
481 + const { layer, requests } = harness({
482 + signIns: { "github.com": session() },
483 + handle: (sent) => {
484 + if (sent.path === "/login/oauth/access_token") {
485 + return { body: { access_token: "ghu_refreshed", expires_in: 28_800 } };
486 + }
487 + if (sent.token === "ghu_current" && !rejected) {
488 + rejected = true;
489 + return { status: 401, body: {} };
490 + }
491 + return answerUser(sent);
492 + },
493 + });
494 + return Effect.gen(function* () {
495 + expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiAuthenticationError");
496 + yield* readUser;
497 + expect(requests.map((sent) => sent.token ?? sent.path)).toEqual([
498 + "ghu_current",
499 + "/login/oauth/access_token",
500 + "ghu_refreshed",
501 + ]);
502 + }).pipe(Effect.provide(layer));
503 + });
504 +});
505 +
506 +describe("GitHubAppAccess", () => {
507 + it.effect("reads the installations as the app, even with a saved token", () => {
508 + const { layer, requests } = harness({
509 + signIns: { "github.com": session() },
510 + tokens: { "github.com": "saved-pat" },
511 + handle: installedOn,
512 + });
513 + return Effect.gen(function* () {
514 + const access = yield* GitHubAppAccess.GitHubAppAccess;
515 + expect(yield* access.reach("github.com", "pingdotgg/t3code")).toBe("covered");
516 + expect(yield* access.reach("github.com", "acme/one")).toBe("covered");
517 + expect(yield* access.reach("github.com", "acme/two")).toBe("not-covered");
518 + expect(yield* access.reach("github.com", "https://github.com/Acme/One.git")).toBe("covered");
519 + expect(new Set(requests.map((sent) => sent.token))).toEqual(new Set(["ghu_current"]));
520 + // One read of the installations serves every repository until it goes stale.
521 + expect(requests.filter((sent) => sent.path === "/user/installations")).toHaveLength(1);
522 + }).pipe(Effect.provide(layer));
523 + });
524 +
525 + it.effect("answers signed out without a session, and covered while GitHub fails", () => {
526 + const signedOut = harness({ handle: installedOn });
527 + const failing = harness({
528 + signIns: { "github.com": session() },
529 + handle: () => ({ status: 502, body: {} }),
530 + });
531 + return Effect.gen(function* () {
532 + expect(
533 + yield* Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) =>
534 + access.reach("github.com", "acme/one"),
535 + ).pipe(Effect.provide(signedOut.layer)),
536 + ).toBe("signed-out");
537 + const answers = yield* Effect.gen(function* () {
538 + const access = yield* GitHubAppAccess.GitHubAppAccess;
539 + return [
540 + yield* access.reach("github.com", "acme/one"),
541 + yield* access.reach("github.com", "acme/two"),
542 + ];
543 + }).pipe(Effect.provide(failing.layer));
544 + expect(answers).toEqual(["covered", "covered"]);
545 + // A failed read is kept briefly instead of asked again per request.
546 + expect(failing.requests).toHaveLength(1);
547 + });
548 + });
549 +
550 + it.effect("gives work on a repository the app cannot reach the user's credential", () => {
551 + const { layer } = harness({ signIns: { "github.com": session() }, handle: installedOn });
552 + return Effect.gen(function* () {
553 + const access = yield* GitHubAppAccess.GitHubAppAccess;
554 + const tokenFor = (repository: string) =>
555 + access
556 + .credentialFor("github.com", repository)
557 + .pipe(Effect.map((held) => Redacted.value(held.token)));
558 + expect(yield* tokenFor("pingdotgg/t3code")).toBe("ghu_current");
559 + expect(yield* tokenFor("someone/else")).toBe("gh-token");
560 + }).pipe(Effect.provide(layer));
561 + });
562 +
563 + it.effect("pins the user's credential while the app's reach is unknown", () => {
564 + const failing = (sent: Sent): Reply =>
565 + sent.path.startsWith("/user/installations") ? { status: 502, body: {} } : { body: {} };
566 + const withGh = harness({ signIns: { "github.com": session() }, handle: failing });
567 + const appOnly = harness({
568 + signIns: { "github.com": session() },
569 + ghSignedIn: false,
570 + handle: failing,
571 + });
572 + const tokenFor = Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) =>
573 + access
574 + .credentialFor("github.com", "pingdotgg/t3code")
575 + .pipe(Effect.map((held) => Redacted.value(held.token))),
576 + );
577 + return Effect.gen(function* () {
578 + expect(yield* tokenFor.pipe(Effect.provide(withGh.layer))).toBe("gh-token");
579 + expect(yield* tokenFor.pipe(Effect.provide(appOnly.layer))).toBe("ghu_current");
580 + });
581 + });
582 +
583 + it.effect("names the account the app sign-in acts as", () => {
584 + const { layer } = harness({
585 + signIns: { "github.com": session() },
586 + tokens: { "github.com": "saved-pat" },
587 + handle: (sent) => ({ body: { login: sent.token === "ghu_current" ? "octocat" : "other" } }),
588 + });
589 + return Effect.gen(function* () {
590 + expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).viewer("github.com")).toBe("octocat");
591 + }).pipe(Effect.provide(layer));
592 + });
593 +});
packages/source-control-github/src/server/GitHubAppSignIn.ts new
+467
@@ -0,0 +1,467 @@
1 +import {
2 + SourceControlProviderKind,
3 + SourceControlSignInError,
4 + type SourceControlSignInFailure,
5 + type SourceControlSignInPrompt,
6 +} from "@t3tools/contracts";
7 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
8 +import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
9 +import * as Clock from "effect/Clock";
10 +import * as Context from "effect/Context";
11 +import * as Deferred from "effect/Deferred";
12 +import * as Duration from "effect/Duration";
13 +import * as Effect from "effect/Effect";
14 +import * as Fiber from "effect/Fiber";
15 +import * as Layer from "effect/Layer";
16 +import * as Option from "effect/Option";
17 +import * as Ref from "effect/Ref";
18 +import * as Schema from "effect/Schema";
19 +import * as Schedule from "effect/Schedule";
20 +import * as Semaphore from "effect/Semaphore";
21 +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
22 +import * as HostProcess from "@t3tools/shared/HostProcess";
23 +
24 +import * as GitHubClient from "../shared/definition.ts";
25 +
26 +/**
27 + * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret).
28 + * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show.
29 + */
30 +export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID";
31 +
32 +const KIND = SourceControlProviderKind.make("github");
33 +const REQUEST_TIMEOUT = Duration.seconds(15);
34 +// Refresh ahead of expiry so a token never lapses between the check and a long request.
35 +const REFRESH_MARGIN_MS = Duration.toMillis(Duration.minutes(5));
36 +
37 +const GitHubAppSession = Schema.Struct({
38 + accessToken: Schema.String,
39 + /** Null when the app hands out tokens that do not expire. */
40 + accessTokenExpiresAt: Schema.NullOr(Schema.Number),
41 + refreshToken: Schema.NullOr(Schema.String),
42 + refreshTokenExpiresAt: Schema.NullOr(Schema.Number),
43 +});
44 +type GitHubAppSession = typeof GitHubAppSession.Type;
45 +
46 +const GitHubAppSessionJson = Schema.fromJsonString(GitHubAppSession);
47 +const decodeSession = Schema.decodeUnknownOption(GitHubAppSessionJson);
48 +const encodeSession = Schema.encodeSync(GitHubAppSessionJson);
49 +
50 +// GitHub answers both token grants with HTTP 200 and puts refusals in `error`.
51 +const TokenResponse = Schema.Struct({
52 + access_token: Schema.optional(Schema.String),
53 + expires_in: Schema.optional(Schema.Number),
54 + refresh_token: Schema.optional(Schema.String),
55 + refresh_token_expires_in: Schema.optional(Schema.Number),
56 + interval: Schema.optional(Schema.Number),
57 + error: Schema.optional(Schema.String),
58 + error_description: Schema.optional(Schema.String),
59 +});
60 +
61 +const DeviceCodeResponse = Schema.Struct({
62 + device_code: Schema.optional(Schema.String),
63 + user_code: Schema.optional(Schema.String),
64 + verification_uri: Schema.optional(Schema.String),
65 + expires_in: Schema.optional(Schema.Number),
66 + interval: Schema.optional(Schema.Number),
67 + error: Schema.optional(Schema.String),
68 + error_description: Schema.optional(Schema.String),
69 +});
70 +
71 +export class GitHubAppSessionError extends Schema.TaggedError<GitHubAppSessionError>()(
72 + "GitHubAppSessionError",
73 + { host: Schema.String, cause: Schema.Defect() },
74 +) {
75 + override get message(): string {
76 + return `Could not refresh the ${GitHubClient.APP_SIGN_IN.appName} sign-in for ${this.host}. Check the server's connection to GitHub, or sign in again in Settings → Source Control.`;
77 + }
78 +}
79 +
80 +export class GitHubAppSignIn extends Context.Service<
81 + GitHubAppSignIn,
82 + {
83 + /** Whether the server is configured with the app's client ID. */
84 + readonly enabled: boolean;
85 + /** The signed-in access token for `host`, refreshed when due; none when not signed in. */
86 + readonly token: (host: string) => Effect.Effect<Option.Option<string>, GitHubAppSessionError>;
87 + /** Refreshes on the next `token` when `rejected` is the token GitHub just refused. */
88 + readonly invalidate: (host: string, rejected: string) => Effect.Effect<void>;
89 + readonly start: (
90 + host: string,
91 + ) => Effect.Effect<SourceControlSignInPrompt, SourceControlSignInError>;
92 + /** Resolves once the sign-in `start` began has saved a session. */
93 + readonly wait: (host: string) => Effect.Effect<void, SourceControlSignInError>;
94 + readonly cancel: (host: string) => Effect.Effect<void>;
95 + }
96 +>()("@t3tools/source-control-github/server/GitHubAppSignIn") {}
97 +
98 +interface PendingSignIn {
99 + readonly deferred: Deferred.Deferred<void, SourceControlSignInError>;
100 + readonly fiber: Fiber.Fiber<boolean>;
101 +}
102 +
103 +const signInError = (host: string, reason: SourceControlSignInFailure, detail: string) =>
104 + new SourceControlSignInError({ provider: KIND, host, reason, detail });
105 +
106 +/** @public */
107 +export const make = Effect.gen(function* () {
108 + const sourceControlHost = yield* SourceControlHost.SourceControlHost;
109 + const httpClient = yield* HttpClient.HttpClient;
110 + const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? "";
111 + const enabled = clientId !== "";
112 + const scope = yield* Effect.scope;
113 + const refreshLock = yield* Semaphore.make(1);
114 + const refused = yield* Ref.make<ReadonlySet<string>>(new Set());
115 + const pending = yield* Ref.make<ReadonlyMap<string, PendingSignIn>>(new Map());
116 +
117 + const isAppHost = (host: string) =>
118 + enabled && GitHubClient.APP_SIGN_IN.hosts.includes(host.trim().toLowerCase());
119 +
120 + const readSignIns = sourceControlHost.settings.get.pipe(
121 + Effect.map(
122 + (settings) =>
123 + readSourceControlHostSettings(
124 + GitHubClient.settings,
125 + settings.sourceControlHosts[GitHubClient.definition.kind],
126 + ).signIns,
127 + ),
128 + Effect.orElseSucceed((): Readonly<Record<string, string>> => ({})),
129 + );
130 +
131 + const readSession = (host: string) =>
132 + readSignIns.pipe(Effect.map((signIns) => decodeSession(signIns[host] ?? "")));
133 +
134 + const writeSession = Effect.fn("GitHubAppSignIn.writeSession")(function* (
135 + host: string,
136 + session: GitHubAppSession | null,
137 + ) {
138 + const signIns = { ...(yield* readSignIns) };
139 + if (session === null) delete signIns[host];
140 + else signIns[host] = encodeSession(session);
141 + yield* sourceControlHost.settings.update({
142 + sourceControlHosts: { [GitHubClient.definition.kind]: { signIns } },
143 + });
144 + });
145 +
146 + /**
147 + * Writes `next` only while the stored session is still the one a refresh started from, so a
148 + * sign-out or a newer sign-in during the request is not undone.
149 + */
150 + const replaceSession = Effect.fn("GitHubAppSignIn.replaceSession")(function* (
151 + host: string,
152 + from: GitHubAppSession,
153 + next: GitHubAppSession | null,
154 + ) {
155 + const current = yield* readSession(host);
156 + if (Option.isNone(current) || current.value.accessToken !== from.accessToken) return false;
157 + yield* writeSession(host, next);
158 + return true;
159 + });
160 +
161 + const postForm = <S extends Schema.Top>(
162 + host: string,
163 + path: string,
164 + body: Record<string, string>,
165 + schema: S,
166 + ) =>
167 + httpClient
168 + .execute(
169 + HttpClientRequest.post(`https://${host}${path}`).pipe(
170 + HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }),
171 + HttpClientRequest.bodyUrlParams(body),
172 + ),
173 + )
174 + .pipe(
175 + Effect.flatMap(HttpClientResponse.filterStatusOk),
176 + Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
177 + Effect.timeout(REQUEST_TIMEOUT),
178 + );
179 +
180 + const sessionFrom = (
181 + now: number,
182 + response: typeof TokenResponse.Type & { readonly access_token: string },
183 + ): GitHubAppSession => ({
184 + accessToken: response.access_token,
185 + accessTokenExpiresAt:
186 + response.expires_in === undefined ? null : now + response.expires_in * 1_000,
187 + refreshToken: response.refresh_token ?? null,
188 + refreshTokenExpiresAt:
189 + response.refresh_token_expires_in === undefined
190 + ? null
191 + : now + response.refresh_token_expires_in * 1_000,
192 + });
193 +
194 + const refresh = Effect.fn("GitHubAppSignIn.refresh")(function* (
195 + host: string,
196 + session: GitHubAppSession,
197 + ) {
198 + const now = yield* Clock.currentTimeMillis;
199 + if (
200 + session.refreshToken === null ||
201 + (session.refreshTokenExpiresAt !== null && session.refreshTokenExpiresAt <= now)
202 + ) {
203 + yield* replaceSession(host, session, null).pipe(Effect.ignore);
204 + return Option.none<string>();
205 + }
206 + const response = yield* postForm(
207 + host,
208 + "/login/oauth/access_token",
209 + {
210 + client_id: clientId,
211 + grant_type: "refresh_token",
212 + refresh_token: session.refreshToken,
213 + },
214 + TokenResponse,
215 + ).pipe(Effect.mapError((cause) => new GitHubAppSessionError({ host, cause })));
216 + if (response.error === "bad_refresh_token") {
217 + // Final: the user revoked the app or the session lapsed.
218 + yield* Effect.logWarning("GitHub refused the app sign-in refresh; signing out.", { host });
219 + yield* replaceSession(host, session, null).pipe(Effect.ignore);
220 + return Option.none<string>();
221 + }
222 + if (response.access_token === undefined) {
223 + return yield* new GitHubAppSessionError({
224 + host,
225 + cause: new Error(`GitHub did not refresh the sign-in (${response.error ?? "no token"}).`),
226 + });
227 + }
228 + const next = sessionFrom(now, {
229 + ...response,
230 + access_token: response.access_token,
231 + });
232 + // GitHub has retired the old pair, so an unsaved new one is still the only usable token.
233 + const saved = yield* replaceSession(host, session, next).pipe(
234 + Effect.retry({ times: 2, schedule: Schedule.spaced(Duration.millis(250)) }),
235 + Effect.catch((cause) =>
236 + Effect.logError("Could not save the refreshed app sign-in; using it unsaved.", {
237 + host,
238 + cause,
239 + }).pipe(Effect.as(true)),
240 + ),
241 + );
242 + if (saved) return Option.some(next.accessToken);
243 + // Signed out or signed in again meanwhile: serve whatever is stored now.
244 + return Option.map(yield* readSession(host), (current) => current.accessToken);
245 + });
246 +
247 + const isFresh = (session: GitHubAppSession, now: number) =>
248 + session.accessTokenExpiresAt === null || now < session.accessTokenExpiresAt - REFRESH_MARGIN_MS;
249 +
250 + const token: GitHubAppSignIn["Service"]["token"] = Effect.fn("GitHubAppSignIn.token")(
251 + function* (rawHost) {
252 + const host = rawHost.trim().toLowerCase();
253 + if (!isAppHost(host)) return Option.none();
254 + const session = yield* readSession(host);
255 + if (Option.isNone(session)) return Option.none();
256 + const now = yield* Clock.currentTimeMillis;
257 + if (
258 + isFresh(session.value, now) &&
259 + !(yield* Ref.get(refused)).has(session.value.accessToken)
260 + ) {
261 + return Option.some(session.value.accessToken);
262 + }
263 + return yield* refreshLock.withPermits(1)(
264 + Effect.gen(function* () {
265 + // Another request may have refreshed while this one queued.
266 + const current = yield* readSession(host);
267 + if (Option.isNone(current)) return Option.none<string>();
268 + const refusedTokens = yield* Ref.get(refused);
269 + const now = yield* Clock.currentTimeMillis;
270 + if (isFresh(current.value, now) && !refusedTokens.has(current.value.accessToken)) {
271 + return Option.some(current.value.accessToken);
272 + }
273 + const usable = Option.some(current.value.accessToken).pipe(
274 + Option.filter(
275 + (accessToken) =>
276 + !refusedTokens.has(accessToken) &&
277 + (current.value.accessTokenExpiresAt === null ||
278 + now < current.value.accessTokenExpiresAt),
279 + ),
280 + );
281 + // A refresh ahead of expiry that fails leaves the still-valid token in use.
282 + return yield* refresh(host, current.value).pipe(
283 + Effect.catchTags({
284 + GitHubAppSessionError: (error) =>
285 + Option.isSome(usable) ? Effect.succeed(usable) : Effect.fail(error),
286 + }),
287 + );
288 + }),
289 + );
290 + },
291 + );
292 +
293 + const invalidate: GitHubAppSignIn["Service"]["invalidate"] = Effect.fn(
294 + "GitHubAppSignIn.invalidate",
295 + )(function* (rawHost, rejected) {
296 + const session = yield* readSession(rawHost.trim().toLowerCase());
297 + // A refused fallback token says nothing about the app session.
298 + if (Option.isNone(session) || session.value.accessToken !== rejected) return;
299 + yield* Ref.update(refused, (current) => new Set([...current, rejected]));
300 + });
301 +
302 + const poll = Effect.fn("GitHubAppSignIn.poll")(function* (
303 + host: string,
304 + deviceCode: string,
305 + expiresAt: number,
306 + initialInterval: number,
307 + ) {
308 + let interval = initialInterval;
309 + while (true) {
310 + yield* Effect.sleep(Duration.seconds(interval));
311 + const now = yield* Clock.currentTimeMillis;
312 + if (now >= expiresAt) {
313 + return yield* signInError(host, "expired", "The sign-in code expired. Start again.");
314 + }
315 + const answer = yield* postForm(
316 + host,
317 + "/login/oauth/access_token",
318 + {
319 + client_id: clientId,
320 + device_code: deviceCode,
321 + grant_type: "urn:ietf:params:oauth:grant-type:device_code",
322 + },
323 + TokenResponse,
324 + ).pipe(Effect.option);
325 + // A dropped poll is retried on the next tick; the code stays valid until it expires.
326 + if (Option.isNone(answer)) continue;
327 + const response = answer.value;
328 + if (response.access_token !== undefined) {
329 + const accessToken = response.access_token;
330 + return yield* writeSession(
331 + host,
332 + sessionFrom(yield* Clock.currentTimeMillis, { ...response, access_token: accessToken }),
333 + ).pipe(
334 + Effect.mapError(
335 + (cause) =>
336 + new SourceControlSignInError({
337 + provider: KIND,
338 + host,
339 + reason: "failed",
340 + detail: "The server could not save the sign-in.",
341 + cause,
342 + }),
343 + ),
344 + );
345 + }
346 + switch (response.error) {
347 + case "authorization_pending":
348 + continue;
349 + case "slow_down":
350 + interval = response.interval ?? interval + 5;
351 + continue;
352 + case "expired_token":
353 + return yield* signInError(host, "expired", "The sign-in code expired. Start again.");
354 + case "access_denied":
355 + return yield* signInError(host, "denied", "The sign-in was cancelled on GitHub.");
356 + default:
357 + return yield* signInError(
358 + host,
359 + "failed",
360 + response.error_description ??
361 + `GitHub refused the sign-in (${response.error ?? "no reason given"}).`,
362 + );
363 + }
364 + }
365 + });
366 +
367 + const start: GitHubAppSignIn["Service"]["start"] = Effect.fn("GitHubAppSignIn.start")(
368 + function* (rawHost) {
369 + const host = rawHost.trim().toLowerCase();
370 + if (!enabled) {
371 + return yield* signInError(
372 + host,
373 + "unsupported",
374 + `This server is not set up to sign in with ${GitHubClient.APP_SIGN_IN.appName}.`,
375 + );
376 + }
377 + if (!isAppHost(host)) {
378 + return yield* signInError(
379 + host,
380 + "unsupported",
381 + `${GitHubClient.APP_SIGN_IN.appName} only signs in to ${GitHubClient.APP_SIGN_IN.hosts.join(", ")}. Use a token or the GitHub CLI for ${host}.`,
382 + );
383 + }
384 + const code = yield* postForm(
385 + host,
386 + "/login/device/code",
387 + { client_id: clientId },
388 + DeviceCodeResponse,
389 + ).pipe(
390 + Effect.mapError(
391 + (cause) =>
392 + new SourceControlSignInError({
393 + provider: KIND,
394 + host,
395 + reason: "failed",
396 + detail: "The server could not reach GitHub to start the sign-in.",
397 + cause,
398 + }),
399 + ),
400 + );
401 + if (
402 + code.device_code === undefined ||
403 + code.user_code === undefined ||
404 + code.verification_uri === undefined ||
405 + code.expires_in === undefined
406 + ) {
407 + return yield* signInError(
408 + host,
409 + "failed",
410 + code.error_description ??
411 + `GitHub would not start the sign-in (${code.error ?? "no reason given"}).`,
412 + );
413 + }
414 + const expiresAt = (yield* Clock.currentTimeMillis) + code.expires_in * 1_000;
415 + const deferred = yield* Deferred.make<void, SourceControlSignInError>();
416 + const fiber = yield* poll(host, code.device_code, expiresAt, code.interval ?? 5).pipe(
417 + Effect.tap(() => Ref.set(refused, new Set())),
418 + Deferred.into(deferred),
419 + Effect.forkIn(scope),
420 + );
421 + const previous = yield* Ref.modify(pending, (current) => [
422 + current.get(host),
423 + new Map(current).set(host, { deferred, fiber }),
424 + ]);
425 + if (previous !== undefined) {
426 + yield* Deferred.fail(
427 + previous.deferred,
428 + signInError(host, "failed", "A newer sign-in replaced this one."),
429 + );
430 + yield* Fiber.interrupt(previous.fiber);
431 + }
432 + return {
433 + userCode: code.user_code,
434 + verificationUri: code.verification_uri,
435 + expiresAt,
436 + } satisfies SourceControlSignInPrompt;
437 + },
438 + );
439 +
440 + const wait: GitHubAppSignIn["Service"]["wait"] = Effect.fn("GitHubAppSignIn.wait")(
441 + function* (rawHost) {
442 + const host = rawHost.trim().toLowerCase();
443 + const current = (yield* Ref.get(pending)).get(host);
444 + if (current === undefined) {
445 + return yield* signInError(host, "not-started", "No sign-in is in progress. Start again.");
446 + }
447 + return yield* Deferred.await(current.deferred);
448 + },
449 + );
450 +
451 + const cancel: GitHubAppSignIn["Service"]["cancel"] = Effect.fn("GitHubAppSignIn.cancel")(
452 + function* (rawHost) {
453 + const host = rawHost.trim().toLowerCase();
454 + const current = (yield* Ref.get(pending)).get(host);
455 + if (current === undefined) return;
456 + yield* Deferred.fail(
457 + current.deferred,
458 + signInError(host, "cancelled", "The sign-in was cancelled."),
459 + );
460 + yield* Fiber.interrupt(current.fiber);
461 + },
462 + );
463 +
464 + return GitHubAppSignIn.of({ enabled, token, invalidate, start, wait, cancel });
465 +});
466 +
467 +export const layer = Layer.effect(GitHubAppSignIn, make);
packages/source-control-github/src/server/GitHubCredentials.test.ts
+7
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Redacted from "effect/Redacted";
6 +import { HttpClient } from "effect/http";
7 import { ChildProcessSpawner } from "effect/process";
8
9 import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
@@ -62,6 +63,12 @@ function harness(
63 }),
64 ),
65 Layer.provide(NodeCrypto.layer),
66 + Layer.provide(
67 + Layer.succeed(
68 + HttpClient.HttpClient,
69 + HttpClient.make((request) => Effect.die(`Unexpected request to ${request.url}`)),
70 + ),
71 + ),
72 );
73 return { layer, calls };
74 }
packages/source-control-github/src/server/GitHubCredentials.ts
+30 -16
@@ -29,7 +29,7 @@ export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
29 const TOKEN_TTL = Duration.minutes(5);
30 const MISSING_TTL = Duration.seconds(10);
31
32 -export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);
32 +export const GitHubCredentialSource = Schema.Literals(["settings", "app", "env", "gh"]);
33 export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
34
35 export interface GitHubCredential {
@@ -89,6 +89,14 @@ export class GitHubCredentials extends Context.Service<
89 readonly get: (
90 host: string,
91 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
92 + /** The token saved in Settings for `host`, which outranks every other source. */
93 + readonly saved: (
94 + host: string,
95 + ) => Effect.Effect<
96 + Option.Option<GitHubCredential>,
97 + GitHubHostDisabledError | GitHubNotSignedInError
98 + >;
99 + readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;
100 readonly invalidate: (host: string) => Effect.Effect<void>;
101 }
102 >()("@t3tools/source-control-github/server/GitHubCredentials") {}
@@ -225,25 +233,31 @@ export const make = Effect.gen(function* () {
233 : MISSING_TTL,
234 });
235
236 + const saved = Effect.fn("GitHubCredentials.saved")(function* (rawHost: string) {
237 + const host = normalizeHost(rawHost);
238 + if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
239 + if ((yield* hostChoice(host))?.enabled === false) {
240 + return yield* new GitHubHostDisabledError({ host });
241 + }
242 + const token = yield* savedToken(host);
243 + if (token === null) return Option.none<GitHubCredential>();
244 + return Option.some<GitHubCredential>({
245 + host,
246 + token: Redacted.make(token),
247 + source: "settings",
248 + fingerprint: yield* fingerprintOf(host, token),
249 + });
250 + });
251 +
252 return GitHubCredentials.of({
253 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
254 const host = normalizeHost(rawHost);
231 - if (!isGitHubHost(host)) return yield* new GitHubNotSignedInError({ host });
232 - const choice = yield* hostChoice(host);
233 - if (choice?.enabled === false) {
234 - return yield* new GitHubHostDisabledError({ host });
235 - }
236 - const saved = yield* savedToken(host);
237 - if (saved !== null) {
238 - return {
239 - host,
240 - token: Redacted.make(saved),
241 - source: "settings",
242 - fingerprint: yield* fingerprintOf(host, saved),
243 - } satisfies GitHubCredential;
244 - }
245 - return yield* Cache.get(cache, cacheKey(host, choice?.account));
255 + const fromSettings = yield* saved(host);
256 + if (Option.isSome(fromSettings)) return fromSettings.value;
257 + return yield* Cache.get(cache, cacheKey(host, (yield* hostChoice(host))?.account));
258 }),
259 + saved,
260 + fingerprint: fingerprintOf,
261 invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
262 const host = normalizeHost(rawHost);
263 return hostChoice(host).pipe(
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+18 -2
@@ -21,6 +21,14 @@ import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSour
21 import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
22 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
23 import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts";
24 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
25 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
26 +
27 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
28 + enabled: false,
29 + token: () => Effect.succeedNone,
30 + invalidate: () => Effect.void,
31 +});
32
33 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
34
@@ -112,6 +120,7 @@ const mockApi = Layer.succeed(
120 GitHubRest.GitHubRest.of({
121 rest: (input) => mockedExecute({ kind: "rest", ...input }),
122 credential: (host) => mockedCredential(host),
123 + appCredential: () => Effect.succeedNone,
124 }),
125 );
126
@@ -167,8 +176,10 @@ const mockHttp = Layer.succeed(
176
177 const layer = it.layer(
178 GitHubPullRequestApi.layer.pipe(
179 + Layer.provideMerge(GitHubAppAccess.layer),
180 Layer.provideMerge(mockApi),
181 Layer.provideMerge(GitHubRequestPolicy.layer),
182 + Layer.provideMerge(appSignedOut),
183 Layer.provideMerge(GitHubQuota.layer),
184 Layer.provideMerge(SourceControlRateLimit.layer),
185 Layer.provideMerge(mockHttp),
@@ -176,6 +187,8 @@ const layer = it.layer(
187 Layer.succeed(GitHubCredentials.GitHubCredentials, {
188 get: (host) =>
189 Effect.map(mockedCredential(host), (held) => ({ ...held, host, source: "gh" as const })),
190 + saved: () => Effect.succeedNone,
191 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
192 invalidate: () => Effect.void,
193 }),
194 ),
@@ -623,6 +636,8 @@ it.effect(
636 source: "gh" as const,
637 fingerprint: `${host}:${activeToken.length}${activeToken.at(-1)}`,
638 })),
639 + saved: () => Effect.succeedNone,
640 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
641 invalidate: () => Effect.void,
642 }),
643 );
@@ -648,8 +663,9 @@ it.effect(
663 );
664 const cli = yield* GitHubPullRequestApi.make.pipe(
665 Effect.provide(
651 - GitHubRest.layer.pipe(
652 - Layer.provideMerge(Layer.mergeAll(credentials, http)),
666 + GitHubAppAccess.layer.pipe(
667 + Layer.provideMerge(GitHubRest.layer),
668 + Layer.provideMerge(Layer.mergeAll(credentials, http, appSignedOut)),
669 Layer.provideMerge(GitHubQuota.layer),
670 Layer.provideMerge(SourceControlRateLimit.layer),
671 Layer.merge(TestSourceControlHost.layer()),
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+14 -3
@@ -45,6 +45,7 @@ import {
45 type PullRequestPreview,
46 } from "@t3tools/contracts";
47
48 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
49 import * as GitHubRest from "./GitHubRest.ts";
50 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
51 import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
@@ -405,7 +406,7 @@ export class GitHubPullRequestApi extends Context.Service<
406 GitHubPullRequestApi,
407 {
408 readonly withVerifiedCredential: <A, E, R>(
408 - input: { readonly cwd: string; readonly host: string },
409 + input: { readonly cwd: string; readonly host: string; readonly repository?: string },
410 use: (identity: {
411 readonly accountId: string;
412 readonly viewer: string;
@@ -886,6 +887,7 @@ interface RestReadInput<A> {
887 /** @public */
888 export const make = Effect.gen(function* () {
889 const api = yield* GitHubRest.GitHubRest;
890 + const appAccess = yield* GitHubAppAccess.GitHubAppAccess;
891 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
892 const httpClient = yield* HttpClient.HttpClient;
893 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
@@ -909,10 +911,18 @@ export const make = Effect.gen(function* () {
911 const decodeRoutingIdentity = Schema.decodeUnknownEffect(Schema.fromJsonString(RoutingIdentity));
912 const decodeViewerIdentity = Schema.decodeUnknownEffect(RoutingIdentity);
913 const captureVerifiedCredential = Effect.fn("GitHubPullRequestApi.captureVerifiedCredential")(
912 - function* (input: { readonly cwd: string; readonly host: string }) {
914 + function* (input: {
915 + readonly cwd: string;
916 + readonly host: string;
917 + readonly repository?: string;
918 + }) {
919 const unavailable = () => new GitHubViewerLoginUnavailableError({ cwd: input.cwd });
920 const host = input.host.toLowerCase();
915 - const { token, fingerprint: key } = yield* api.credential(host);
921 + // A pinned credential is never handed on to another, so pick one that reaches the repository.
922 + const { token, fingerprint: key } =
923 + input.repository === undefined
924 + ? yield* api.credential(host)
925 + : yield* appAccess.credentialFor(host, input.repository);
926 const credential = { host, token, credentialFingerprint: key };
927 return yield* Effect.acquireUseRelease(
928 Effect.sync(() => {
@@ -2391,6 +2401,7 @@ export const make = Effect.gen(function* () {
2401 if (input.stackNumber !== undefined)
2402 return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe(
2403 Effect.provideService(GitHubRest.GitHubRest, api),
2404 + Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess),
2405 Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy),
2406 Effect.provideService(HttpClient.HttpClient, httpClient),
2407 Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost),
packages/source-control-github/src/server/GitHubPullRequestProvider.credential.test.ts
+12 -1
@@ -12,6 +12,14 @@ import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
12 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
13 import * as GitHubQuota from "./GitHubQuota.ts";
14 import * as GitHubRest from "./GitHubRest.ts";
15 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
16 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
17 +
18 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
19 + enabled: false,
20 + token: () => Effect.succeedNone,
21 + invalidate: () => Effect.void,
22 +});
23
24 it.effect("keeps branch deletion on the credential that passed source repository permissions", () =>
25 Effect.gen(function* () {
@@ -27,6 +35,8 @@ it.effect("keeps branch deletion on the credential that passed source repository
35 source: "gh" as const,
36 fingerprint: `${host}:${activeToken}`,
37 })),
38 + saved: () => Effect.succeedNone,
39 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
40 invalidate: () => Effect.void,
41 }),
42 );
@@ -101,10 +111,11 @@ it.effect("keeps branch deletion on the credential that passed source repository
111 const provider = yield* GitHubPullRequestProvider.make.pipe(
112 Effect.provide(
113 GitHubPullRequestApi.layer.pipe(
114 + Layer.provideMerge(GitHubAppAccess.layer),
115 // GraphQL reads go over `http` too, through the same credential and quota as REST.
116 Layer.provide(
117 GitHubRest.layer.pipe(
107 - Layer.provideMerge(Layer.mergeAll(credentials, http)),
118 + Layer.provideMerge(Layer.mergeAll(credentials, http, appSignedOut)),
119 Layer.provideMerge(GitHubQuota.layer),
120 Layer.provideMerge(SourceControlRateLimit.layer),
121 ),
packages/source-control-github/src/server/GitHubRequestPolicy.ts
+156 -47
@@ -11,6 +11,10 @@ import * as Schema from "effect/Schema";
11 import * as Semaphore from "effect/Semaphore";
12 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
13
14 +import * as Option from "effect/Option";
15 +import * as Result from "effect/Result";
16 +
17 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
18 import * as GitHubCredentials from "./GitHubCredentials.ts";
19 import * as GitHubQuota from "./GitHubQuota.ts";
20
@@ -86,6 +90,7 @@ export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponse
90
91 export type GitHubApiError =
92 | GitHubCredentials.GitHubCredentialUnavailableError
93 + | GitHubAppSignIn.GitHubAppSessionError
94 | GitHubApiRequestError
95 | GitHubApiAuthenticationError
96 | GitHubApiRateLimitError
@@ -164,7 +169,12 @@ export type GitHubAnswer<A> = {
169 readonly status: number | undefined;
170 readonly headers: Readonly<Record<string, string | undefined>>;
171 } & (
167 - | { readonly _tag: "Ok"; readonly value: A }
172 + | {
173 + readonly _tag: "Ok";
174 + readonly value: A;
175 + /** GitHub left part of the answer out as not found or forbidden for this credential. */
176 + readonly withheld?: boolean;
177 + }
178 | { readonly _tag: "RateLimited" | "Unauthorized" | "NotFound" }
179 | { readonly _tag: "Failed"; readonly messages?: ReadonlyArray<string> | undefined }
180 );
@@ -188,40 +198,109 @@ export class GitHubRequestPolicy extends Context.Service<
198 input: GitHubRequest,
199 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
200 ) => Effect.Effect<A, E | GitHubApiError, R>;
201 + /**
202 + * The credential requests to `host` use: a token saved in Settings, else the app sign-in,
203 + * else `GH_TOKEN` or `gh`. `personal` skips the app, for repositories it cannot reach.
204 + */
205 readonly credential: (
206 host: string,
193 - ) => Effect.Effect<
194 - { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
195 - GitHubApiError
196 - >;
207 + options?: { readonly personal?: boolean },
208 + ) => Effect.Effect<GitHubHeldCredential, GitHubApiError>;
209 + /** The app sign-in's own credential, whatever else outranks it; none when not signed in. */
210 + readonly appCredential: (
211 + host: string,
212 + ) => Effect.Effect<Option.Option<GitHubHeldCredential>, GitHubAppSignIn.GitHubAppSessionError>;
213 }
214 >()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
215
216 +export interface GitHubHeldCredential {
217 + readonly token: Redacted.Redacted<string>;
218 + readonly fingerprint: string;
219 +}
220 +
221 +interface ChosenCredential extends GitHubHeldCredential {
222 + readonly fromApp: boolean;
223 +}
224 +
225 +/**
226 + * The app reaches only repositories where it is installed. A not-found or "not accessible by
227 + * integration" answer to its token is worth one more try with the user's own credential.
228 + */
229 +function refusedToApp<A>(answer: GitHubAnswer<A>): boolean {
230 + switch (answer._tag) {
231 + case "NotFound":
232 + return true;
233 + case "Ok":
234 + return answer.withheld === true;
235 + case "Failed":
236 + return (
237 + answer.status === 403 &&
238 + (answer.messages ?? []).some((message) => /not accessible by integration/i.test(message))
239 + );
240 + default:
241 + return false;
242 + }
243 +}
244 +
245 /** @public */
246 export const make = Effect.gen(function* () {
247 const credentials = yield* GitHubCredentials.GitHubCredentials;
248 + const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
249 const quota = yield* GitHubQuota.GitHubQuota;
250 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
251 const slots = yield* Semaphore.make(CONCURRENCY);
252
207 - const credential: GitHubRequestPolicy["Service"]["credential"] = Effect.fn(
208 - "GitHubRest.credential",
253 + const personalCredential = (host: string) =>
254 + credentials.get(host).pipe(
255 + Effect.map((held): ChosenCredential => ({
256 + token: held.token,
257 + fingerprint: held.fingerprint,
258 + fromApp: false,
259 + })),
260 + );
261 +
262 + const appCredential: GitHubRequestPolicy["Service"]["appCredential"] = Effect.fn(
263 + "GitHubRest.appCredential",
264 )(function* (host) {
210 - const normalized = normalizeHost(host);
265 + const token = yield* appSignIn.token(normalizeHost(host));
266 + if (Option.isNone(token)) return Option.none();
267 + return Option.some({
268 + token: Redacted.make(token.value),
269 + fingerprint: yield* credentials.fingerprint(normalizeHost(host), token.value),
270 + });
271 + });
272 +
273 + const choose = Effect.fn("GitHubRest.credential")(function* (host: string, personal: boolean) {
274 const pinned = yield* PinnedGitHubCredential;
275 if (pinned !== null) {
213 - if (pinned.host !== normalized) {
214 - return yield* new GitHubApiAuthenticationError({
215 - host: normalized,
216 - operation: "credential",
217 - });
276 + if (pinned.host !== host) {
277 + return yield* new GitHubApiAuthenticationError({ host, operation: "credential" });
278 }
219 - return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
279 + return {
280 + token: pinned.token,
281 + fingerprint: pinned.credentialFingerprint,
282 + fromApp: false,
283 + } satisfies ChosenCredential;
284 + }
285 + const saved = yield* credentials.saved(host);
286 + if (Option.isSome(saved)) {
287 + return { token: saved.value.token, fingerprint: saved.value.fingerprint, fromApp: false };
288 + }
289 + if (personal) return yield* personalCredential(host);
290 + const app = yield* Effect.result(appCredential(host));
291 + // An app session that cannot refresh right now steps aside for the user's own credential.
292 + if (Result.isFailure(app)) {
293 + return yield* personalCredential(host).pipe(Effect.mapError(() => app.failure));
294 }
221 - const held = yield* credentials.get(normalized);
222 - return { token: held.token, fingerprint: held.fingerprint };
295 + if (Option.isNone(app.success)) return yield* personalCredential(host);
296 + return { ...app.success.value, fromApp: true } satisfies ChosenCredential;
297 });
298
299 + const credential: GitHubRequestPolicy["Service"]["credential"] = (host, options) =>
300 + choose(normalizeHost(host), options?.personal === true).pipe(
301 + Effect.map(({ token, fingerprint }) => ({ token, fingerprint })),
302 + );
303 +
304 // The REST/GraphQL transport span owns request and quota metadata.
305 const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
306 input: GitHubRequest,
@@ -233,14 +312,17 @@ export const make = Effect.gen(function* () {
312 "github.host": host,
313 "github.operation": input.operation,
314 });
236 - const { token, fingerprint } = yield* credential(host);
315 const scope = yield* SourceControlRateLimit.CredentialScope;
316 // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
317 // records its own backoff under.
318 const key = { provider: SourceControlProviderKind.make("github"), host };
319
320 // Settlement annotates the request span with status and rate-limit attributes.
243 - const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {
321 + const settle = Effect.fnUntraced(function* (
322 + lease: number,
323 + answer: GitHubAnswer<A>,
324 + token: Redacted.Redacted<string>,
325 + ) {
326 yield* quota.observe(host, answer.headers);
327 yield* Effect.annotateCurrentSpan({
328 ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
@@ -264,6 +346,7 @@ export const make = Effect.gen(function* () {
346 }
347 case "Unauthorized":
348 // The source may hold a newer token than the one that was refused.
349 + yield* appSignIn.invalidate(host, Redacted.value(token));
350 yield* credentials.invalidate(host);
351 return yield* new GitHubApiAuthenticationError(context);
352 case "NotFound":
@@ -277,39 +360,65 @@ export const make = Effect.gen(function* () {
360 }
361 });
362
280 - const run = Effect.gen(function* () {
281 - const lease = yield* quota
282 - .admit(host, input.resource, { allowReserve: input.allowReserve })
363 + /** One send under `held`; `Retry` hands an app-refused request to the user's credential. */
364 + const attempt = (held: ChosenCredential) =>
365 + slots
366 + .withPermit(
367 + Effect.gen(function* () {
368 + const lease = yield* quota
369 + .admit(host, input.resource, { allowReserve: input.allowReserve })
370 + .pipe(
371 + Effect.andThen(
372 + limits.check(key, input.allowReserve ? { allowPaused: true } : undefined),
373 + ),
374 + Effect.tapError((paused) =>
375 + Effect.annotateCurrentSpan({
376 + "github.paused": true,
377 + "github.retry_at": paused.retryAt,
378 + }),
379 + ),
380 + );
381 + // One deadline covers the headers and the body: a host that answers headers and then
382 + // stalls must not hold a shared slot for undici's own five-minute body timeout.
383 + const answer = yield* send({
384 + ...REQUEST_HEADERS,
385 + authorization: `Bearer ${Redacted.value(held.token)}`,
386 + }).pipe(
387 + Effect.timeoutOrElse({
388 + duration: input.timeout ?? DEFAULT_TIMEOUT,
389 + orElse: () =>
390 + Effect.fail(
391 + new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() }),
392 + ),
393 + }),
394 + );
395 + if (held.fromApp && refusedToApp(answer)) {
396 + const personal = yield* Effect.option(personalCredential(host));
397 + if (Option.isSome(personal)) {
398 + yield* quota.observe(host, answer.headers);
399 + yield* limits.recordSuccess({ ...key, lease });
400 + yield* Effect.annotateCurrentSpan({ "github.app_refused": true });
401 + return { _tag: "Retry", with: personal.value } as const;
402 + }
403 + }
404 + return { _tag: "Done", value: yield* settle(lease, answer, held.token) } as const;
405 + }),
406 + )
407 + // The rate-limit scope follows the credential, so a pause on one account never blocks another.
408 .pipe(
284 - Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
285 - Effect.tapError((paused) =>
286 - Effect.annotateCurrentSpan({
287 - "github.paused": true,
288 - "github.retry_at": paused.retryAt,
289 - }),
290 - ),
409 + Effect.provideService(SourceControlRateLimit.CredentialScope, scope || held.fingerprint),
410 );
292 - // One deadline covers the headers and the body: a host that answers headers and then
293 - // stalls must not hold a shared slot for undici's own five-minute body timeout.
294 - const answer = yield* send({
295 - ...REQUEST_HEADERS,
296 - authorization: `Bearer ${Redacted.value(token)}`,
297 - }).pipe(
298 - Effect.timeoutOrElse({
299 - duration: input.timeout ?? DEFAULT_TIMEOUT,
300 - orElse: () =>
301 - Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),
302 - }),
303 - );
304 - return yield* settle(lease, answer);
305 - });
306 - // The rate-limit scope follows the credential, so a pause on one account never blocks another.
307 - return yield* slots
308 - .withPermit(run)
309 - .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
411 +
412 + // Only an app credential is handed on, so this runs at most twice.
413 + let held = yield* choose(host, false);
414 + while (true) {
415 + const outcome = yield* attempt(held);
416 + if (outcome._tag === "Done") return outcome.value;
417 + held = outcome.with;
418 + }
419 });
420
312 - return GitHubRequestPolicy.of({ request, credential });
421 + return GitHubRequestPolicy.of({ request, credential, appCredential });
422 });
423
424 export const layer = Layer.effect(GitHubRequestPolicy, make);
packages/source-control-github/src/server/GitHubRest.test.ts
+14 -1
@@ -16,6 +16,13 @@ import * as GitHubQuota from "./GitHubQuota.ts";
16 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
17 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
19 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
20 +
21 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
22 + enabled: false,
23 + token: () => Effect.succeedNone,
24 + invalidate: () => Effect.void,
25 +});
26
27 const NOW = Date.parse("2026-10-05T12:00:00.000Z");
28
@@ -37,6 +44,8 @@ function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Resp
44 fingerprint: `${host}:${tokens[0]}`,
45 };
46 }),
47 + saved: () => Effect.succeedNone,
48 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
49 invalidate: () =>
50 Effect.sync(() => {
51 invalidations++;
@@ -52,7 +61,7 @@ function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Resp
61 }),
62 );
63 const layer = GitHubRest.layer.pipe(
55 - Layer.provide(Layer.mergeAll(credentials, http)),
64 + Layer.provide(Layer.mergeAll(credentials, http, appSignedOut)),
65 Layer.provideMerge(GitHubQuota.layer),
66 Layer.provideMerge(SourceControlRateLimit.layer),
67 );
@@ -231,10 +240,14 @@ describe("GitHubRest", () => {
240 });
241
242 describe("GitHubCredentials", () => {
243 + const unexpectedHttp = HttpClient.make((request) =>
244 + Effect.die(`Unexpected request to ${request.url}`),
245 + );
246 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
247 GitHubCredentials.layer.pipe(
248 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
249 Layer.provide(NodeCrypto.layer),
250 + Layer.provide(Layer.succeed(HttpClient.HttpClient, unexpectedHttp)),
251 );
252
253 it.effect("does not cache a gh failure that is not about signing in", () => {
packages/source-control-github/src/server/GitHubRest.ts
+9 -8
@@ -4,11 +4,11 @@ import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 -import * as Redacted from "effect/Redacted";
7 import * as Schema from "effect/Schema";
8 import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http";
9
10 import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
11 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
12 import * as GitHubCredentials from "./GitHubCredentials.ts";
13 import * as GitHubQuota from "./GitHubQuota.ts";
14 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
@@ -49,12 +49,8 @@ export class GitHubRest extends Context.Service<
49 GitHubRest,
50 {
51 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
52 - readonly credential: (
53 - host: string,
54 - ) => Effect.Effect<
55 - { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
56 - GitHubApiError
57 - >;
52 + readonly credential: GitHubRequestPolicy.GitHubRequestPolicy["Service"]["credential"];
53 + readonly appCredential: GitHubRequestPolicy.GitHubRequestPolicy["Service"]["appCredential"];
54 }
55 >()("@t3tools/source-control-github/server/GitHubRest") {}
56
@@ -212,7 +208,11 @@ export const make = Effect.gen(function* () {
208 );
209 };
210
215 - return GitHubRest.of({ rest, credential: policy.credential });
211 + return GitHubRest.of({
212 + rest,
213 + credential: policy.credential,
214 + appCredential: policy.appCredential,
215 + });
216 });
217
218 export const layer = Layer.effect(GitHubRest, make).pipe(
@@ -226,5 +226,6 @@ export const layer = Layer.effect(GitHubRest, make).pipe(
226 */
227 export const layerWithDependencies = layer.pipe(
228 Layer.provideMerge(GitHubCredentials.layer),
229 + Layer.provideMerge(GitHubAppSignIn.layer),
230 Layer.provideMerge(GitHubQuota.layer),
231 );
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+14 -1
@@ -22,6 +22,13 @@ import * as GitHubCredentials from "./GitHubCredentials.ts";
22 import * as GitHubQuota from "./GitHubQuota.ts";
23 import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
24 import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
25 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
26 +
27 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
28 + enabled: false,
29 + token: () => Effect.succeedNone,
30 + invalidate: () => Effect.void,
31 +});
32
33 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
34
@@ -220,15 +227,19 @@ function harness(input: {
227 source: "gh" as const,
228 fingerprint: `${host}:token`,
229 })),
230 + saved: () => Effect.succeedNone,
231 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
232 invalidate: () => Effect.void,
233 }),
234 GitHubQuota.layer,
235 SourceControlRateLimit.layer,
236 + appSignedOut,
237 ),
238 ),
239 );
240 const layer = Layer.mergeAll(
241 host,
242 + appSignedOut,
243 Layer.mock(GitHubRest.GitHubRest)(input.api ?? {}),
244 policy,
245 Layer.succeed(HttpClient.HttpClient, graphQlHttp(graphql, graphqlCalls)),
@@ -831,6 +842,7 @@ it("reports every gh login and leads with the account Settings pin", () => {
842 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
843 hosts: { "github.com": { account: "work", enabled: true } },
844 tokens: {},
845 + signIns: {},
846 });
847 assert.deepStrictEqual(auth.account, Option.some("work"));
848 assert.deepStrictEqual(auth.accounts, [
@@ -844,6 +856,7 @@ it("reports unauthenticated when Settings turn off every signed-in host", () =>
856 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
857 hosts: { "github.com": { enabled: false } },
858 tokens: {},
859 + signIns: {},
860 });
861 assert.strictEqual(auth.status, "unauthenticated");
862 assert.deepStrictEqual(
@@ -863,7 +876,7 @@ it("names the environment token that overrides the Settings choice", () => {
876 tokenSource: "GH_TOKEN",
877 },
878 ]),
866 - { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
879 + { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {}, signIns: {} },
880 );
881 assert.deepStrictEqual(auth.account, Option.some("bot"));
882 assert.deepStrictEqual(
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+33 -9
@@ -27,6 +27,7 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson";
27 import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
28
29 import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
30 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
31 import * as GitHubRest from "./GitHubRest.ts";
32 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
33 import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
@@ -212,6 +213,9 @@ export const makeDiscovery = Effect.gen(function* () {
213 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
214 const process = sourceControlHost.process;
215 const environment = yield* HostProcess.Environment;
216 + const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
217 + const offerAppSignIn = <A extends SourceControlProviderDiscoveryItem>(item: A): A =>
218 + appSignIn.enabled ? { ...item, appSignIn: true } : item;
219
220 return {
221 type: "managed-cli",
@@ -234,9 +238,18 @@ export const makeDiscovery = Effect.gen(function* () {
238 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
239 });
240 const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
241 + const signedIn =
242 + appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";
243 const variable = environmentTokenVariable(environment);
238 - const tokenSource = savedToken ? "the token saved in Settings" : variable;
239 - if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) return cli;
244 + const appName = GitHubClient.APP_SIGN_IN.appName;
245 + const tokenSource = savedToken
246 + ? "the token saved in Settings"
247 + : signedIn
248 + ? `the ${appName} sign-in`
249 + : variable;
250 + if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) {
251 + return offerAppSignIn(cli);
252 + }
253 const viewer = yield* api
254 .rest({ host: "github.com", operation: "discovery", path: "user" })
255 .pipe(Effect.result);
@@ -244,7 +257,7 @@ export const makeDiscovery = Effect.gen(function* () {
257 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
258 : undefined;
259 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
247 - return {
260 + return offerAppSignIn({
261 ...cli,
262 status: "available" as const,
263 auth: {
@@ -255,24 +268,28 @@ export const makeDiscovery = Effect.gen(function* () {
268 host: "github.com",
269 detail: savedToken
270 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
258 - : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
271 + : signedIn
272 + ? `Signed in with ${appName}.`
273 + : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
274 })
275 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
276 ? providerAuth({
277 status: "unknown",
278 host: "github.com",
264 - detail: `Could not check ${savedToken ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
279 + detail: `Could not check ${savedToken || signedIn ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
280 })
281 : providerAuth({
282 status: "unauthenticated",
283 host: "github.com",
284 detail: savedToken
285 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
271 - : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
286 + : signedIn
287 + ? `GitHub refused the ${appName} sign-in. Sign in again in Settings → Source Control.`
288 + : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
289 })),
290 ...accounts,
291 },
275 - } satisfies SourceControlProviderDiscoveryItem;
292 + } satisfies SourceControlProviderDiscoveryItem);
293 }),
294 // Claim disabled hosts so errors identify the setting.
295 refineUnknownRemote: ({ context }) => {
@@ -337,6 +354,7 @@ function fromGitHubApiError(
354 case "GitHubApiNotFoundError":
355 return failure(notFound, error);
356 case "GitHubCliFailedError":
357 + case "GitHubAppSessionError":
358 case "GitHubApiResponseError":
359 case "GitHubApiRequestError":
360 return failure(error.message.trim() || "GitHub request failed.", error);
@@ -983,7 +1001,11 @@ export const make = Effect.gen(function* () {
1001 const locator =
1002 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1003 (/^[^/\s]+$/.test(bareName)
986 - ? { host: fallbackHost, owner: yield* readViewerLogin(fallbackHost), name: bareName }
1004 + ? {
1005 + host: fallbackHost,
1006 + owner: yield* readViewerLogin(fallbackHost),
1007 + name: bareName,
1008 + }
1009 : null);
1010 if (locator === null) return yield* failure("Repositories are named owner/name.");
1011 return repositoryCloneUrls(yield* readRepository(locator));
@@ -991,7 +1013,9 @@ export const make = Effect.gen(function* () {
1013 (effect, input) =>
1014 effect.pipe(
1015 Effect.mapError(
994 - providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
1016 + providerError("getRepositoryCloneUrls", input.cwd, {
1017 + repository: input.repository,
1018 + }),
1019 ),
1020 ),
1021 ),
packages/source-control-github/src/server/driver.ts
+35
@@ -1,12 +1,16 @@
1 +import { SourceControlSignInError, type SourceControlProviderKind } from "@t3tools/contracts";
2 import {
3 defineSourceControlDriver,
4 withOwnServices,
5 + type SourceControlSignIn,
6 } from "@t3tools/source-control-core/server/driver";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9
10 import { definition } from "../shared/definition.ts";
11
12 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
13 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
14 import * as GitHubMediaFetch from "./gitHubMediaFetch.ts";
15 import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
16 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
@@ -16,14 +20,45 @@ import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
20 // `GitHubRest.layerWithDependencies` carries the quota reserve every GitHub reader shares, so it
21 // must be built once; the driver is.
22 const services = GitHubPullRequestApi.layer.pipe(
23 + Layer.provideMerge(GitHubAppAccess.layer),
24 Layer.provideMerge(GitHubRest.layerWithDependencies),
25 );
26
27 +const makeSignIn = Effect.gen(function* () {
28 + const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
29 + const appAccess = yield* GitHubAppAccess.GitHubAppAccess;
30 + const kind: SourceControlProviderKind = definition.kind;
31 + return {
32 + start: appSignIn.start,
33 + wait: (host) =>
34 + appSignIn.wait(host).pipe(
35 + Effect.andThen(
36 + appAccess.viewer(host).pipe(
37 + Effect.mapError(
38 + (cause) =>
39 + new SourceControlSignInError({
40 + provider: kind,
41 + host,
42 + reason: "failed",
43 + detail: "Signed in, but GitHub would not say which account it belongs to.",
44 + cause,
45 + }),
46 + ),
47 + ),
48 + ),
49 + Effect.map((account) => ({ account })),
50 + ),
51 + cancel: appSignIn.cancel,
52 + access: appAccess.reach,
53 + } satisfies SourceControlSignIn;
54 +});
55 +
56 const makeInstance = Effect.all({
57 sourceControl: GitHubSourceControlProvider.make,
58 discovery: GitHubSourceControlProvider.makeDiscovery,
59 pullRequests: GitHubPullRequestProvider.make,
60 fetchMedia: GitHubMediaFetch.make,
61 + signIn: makeSignIn,
62 });
63
64 export const driver = defineSourceControlDriver({
packages/source-control-github/src/server/gitHubDiscovery.test.ts
+2
@@ -7,6 +7,7 @@ import * as Redacted from "effect/Redacted";
7 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8
9 import * as GitHubCredentials from "./GitHubCredentials.ts";
10 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
11 import * as GitHubRest from "./GitHubRest.ts";
12 import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
13
@@ -22,6 +23,7 @@ const makeDiscovery = (credential: GitHubRest.GitHubRest["Service"]["credential"
23 Effect.provide(
24 Layer.mergeAll(
25 Layer.mock(GitHubRest.GitHubRest)({ credential }),
26 + Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }),
27 TestSourceControlHost.layer(),
28 ),
29 ),
packages/source-control-github/src/server/gitHubGraphQlClient.test.ts
+40 -1
@@ -13,10 +13,20 @@ import * as GitHubCredentials from "./GitHubCredentials.ts";
13 import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
14 import * as GitHubQuota from "./GitHubQuota.ts";
15 import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
16 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
17 +
18 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
19 + enabled: false,
20 + token: () => Effect.succeedNone,
21 + invalidate: () => Effect.void,
22 +});
23
24 const NOW = Date.parse("2026-10-05T12:00:00.000Z");
25
19 -function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
26 +function harness(
27 + respond: (request: HttpClientRequest.HttpClientRequest) => Response,
28 + options?: { readonly appToken?: string },
29 +) {
30 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
31 let invalidations = 0;
32 const services = Layer.mergeAll(
@@ -28,6 +38,8 @@ function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Resp
38 source: "gh" as const,
39 fingerprint: `${host}:secret`,
40 }),
41 + saved: () => Effect.succeedNone,
42 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
43 invalidate: () =>
44 Effect.sync(() => {
45 invalidations++;
@@ -42,6 +54,13 @@ function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Resp
54 ),
55 GitHubQuota.layer,
56 SourceControlRateLimit.layer,
57 + options?.appToken === undefined
58 + ? appSignedOut
59 + : Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
60 + enabled: true,
61 + token: () => Effect.succeedSome(options.appToken ?? ""),
62 + invalidate: () => Effect.void,
63 + }),
64 );
65 const layer = GitHubRest.layer.pipe(Layer.provideMerge(services));
66 return { layer, requests, invalidations: () => invalidations };
@@ -74,6 +93,26 @@ const readStats = (host: string, number = 7) =>
93 const stats = { additions: 3, deletions: 1 };
94
95 describe("GitHubGraphQlAuth", () => {
96 + it.effect("asks again with the user's own credential when the app token gets NOT_FOUND", () => {
97 + const { layer, requests } = harness(
98 + (request) =>
99 + request.headers["authorization"] === "Bearer app-token"
100 + ? json({
101 + data: { _0_repository: null },
102 + errors: [{ type: "NOT_FOUND", message: "Could not resolve to a Repository" }],
103 + })
104 + : json({ data: { _0_repository: { pullRequest: stats } } }),
105 + { appToken: "app-token" },
106 + );
107 + return Effect.gen(function* () {
108 + expect(yield* readStats("github.com")).toEqual({ repository: { pullRequest: stats } });
109 + expect(requests.map((request) => request.headers["authorization"])).toEqual([
110 + "Bearer app-token",
111 + "Bearer secret",
112 + ]);
113 + }).pipe(Effect.provide(layer));
114 + });
115 +
116 it.effect(
117 "sends each host's lookups to its own endpoint with its token, never in one batch",
118 () => {
packages/source-control-github/src/server/gitHubGraphQlClient.ts
+10 -1
@@ -77,9 +77,18 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
77 headers: responseHeaders,
78 ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
79 });
80 + const withheld = (answer.errors ?? []).some(
81 + (error) => error["type"] === "NOT_FOUND" || error["type"] === "FORBIDDEN",
82 + );
83 return rateLimited
84 ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
82 - : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };
85 + : {
86 + _tag: "Ok" as const,
87 + value: answer,
88 + withheld,
89 + status,
90 + headers: responseHeaders,
91 + };
92 }),
93 Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
94 refused(error, { host, operation: target.operation }),
packages/source-control-github/src/server/githubStackActions.test.ts
+14
@@ -13,6 +13,14 @@ import * as GitHubQuota from "./GitHubQuota.ts";
13 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
14 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15 import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
16 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
17 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
18 +
19 +const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
20 + enabled: false,
21 + token: () => Effect.succeedNone,
22 + invalidate: () => Effect.void,
23 +});
24
25 type Call = ReadonlyArray<string>;
26 type Send = (call: Call, kind: "graphql" | "rest") => Effect.Effect<unknown>;
@@ -86,13 +94,19 @@ const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackActio
94 source: "gh" as const,
95 fingerprint: "fp",
96 }),
97 + saved: () => Effect.succeedNone,
98 + fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
99 invalidate: () => Effect.void,
100 }),
101 GitHubQuota.layer,
102 SourceControlRateLimit.layer,
103 + appSignedOut,
104 ),
105 ),
106 ),
107 + Layer.mock(GitHubAppAccess.GitHubAppAccess)({
108 + credentialFor: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
109 + }),
110 Layer.succeed(HttpClient.HttpClient, graphQlHttp(send)),
111 ),
112 ),
packages/source-control-github/src/server/githubStackRebase.test.ts
+3 -3
@@ -8,12 +8,12 @@ import * as Redacted from "effect/Redacted";
8 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
10
11 -import * as GitHubRest from "./GitHubRest.ts";
11 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
12 import { cascadeRebaseStack } from "./githubStackRebase.ts";
13
14 const layer = Layer.mergeAll(
15 - Layer.mock(GitHubRest.GitHubRest)({
16 - credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
15 + Layer.mock(GitHubAppAccess.GitHubAppAccess)({
16 + credentialFor: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
17 }),
18 TestSourceControlHost.layerWithRealGit(),
19 ).pipe(Layer.provideMerge(NodeServices.layer));
packages/source-control-github/src/server/githubStackRebase.ts
+4 -3
@@ -4,7 +4,7 @@ import * as Redacted from "effect/Redacted";
4 import * as Schema from "effect/Schema";
5 import * as Base64 from "effect/encoding/Base64";
6
7 -import * as GitHubRest from "./GitHubRest.ts";
7 +import * as GitHubAppAccess from "./GitHubAppAccess.ts";
8 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9
10 export interface CascadeLayer {
@@ -42,10 +42,11 @@ export const cascadeRebaseStack = Effect.fn("cascadeRebaseStack")(function* (inp
42 readonly layers: ReadonlyArray<CascadeLayer>;
43 readonly remote?: string;
44 }) {
45 - const api = yield* GitHubRest.GitHubRest;
45 + const appAccess = yield* GitHubAppAccess.GitHubAppAccess;
46 const { process } = yield* SourceControlHost.SourceControlHost;
47 const fileSystem = yield* FileSystem.FileSystem;
48 - const { token } = yield* api.credential(input.host);
48 + // A push takes one credential up front, so it must be one that reaches the repository.
49 + const { token } = yield* appAccess.credentialFor(input.host, input.repository);
50 const first = input.layers[0];
51 if (first === undefined) return 0;
52 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-stack-rebase-" }).pipe(
packages/source-control-github/src/shared/definition.ts
+10
@@ -8,6 +8,7 @@ import {
8 parseChangeRequestPath,
9 projectChangeRequestHost,
10 remoteWebOrigin,
11 + type SourceControlAppSignIn,
12 } from "@t3tools/source-control-core/shared/definition";
13
14 import { gitHubMediaUrl } from "./gitHubMedia.ts";
@@ -42,6 +43,14 @@ function isRepositoryPath(repository: string): boolean {
43 );
44 }
45
46 +/** Signing in through the T3 Code for GitHub app lifts the per-user API rate limit to the app's. */
47 +export const APP_SIGN_IN: SourceControlAppSignIn = {
48 + appName: "T3 Code for GitHub",
49 + hosts: ["github.com"],
50 + installUrl: "https://github.com/apps/t3-code-for-github/installations/new",
51 + revokeUrl: "https://github.com/settings/apps/authorizations",
52 +};
53 +
54 export const settings = makeProviderSettingsSchema(hostCredentialSettingsFields);
55 export type GitHubSettings = typeof settings.Type;
56
@@ -58,6 +67,7 @@ export const definition = defineSourceControl({
67 tokenEnvVar: "GH_TOKEN",
68 tokenAccess: "read and write access to pull requests and contents",
69 newTokenUrl: (host) => `https://${host}/settings/personal-access-tokens/new`,
70 + appSignIn: APP_SIGN_IN,
71 },
72 changeRequest: {
73 shortLabel: "PR",
packages/source-control-testing/src/TestSourceControlHost.ts
+4 -3
@@ -55,8 +55,10 @@ export const layer = (
55 Layer.effectContext(
56 Effect.gen(function* () {
57 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
58 + const update = (patch: ServerSettingsPatch) =>
59 + Ref.updateAndGet(settings, (current) => applyServerSettingsPatch(current, patch));
60 const host = SourceControlHost.SourceControlHost.of({
59 - settings: { get: Ref.get(settings) },
61 + settings: { get: Ref.get(settings), update },
62 process: {
63 run:
64 options.process?.run ??
@@ -66,8 +68,7 @@ export const layer = (
68 });
69 return Context.make(SourceControlHost.SourceControlHost, host).pipe(
70 Context.add(TestSourceControlHostSettings, {
69 - update: (patch) =>
70 - Ref.update(settings, (current) => applyServerSettingsPatch(current, patch)),
71 + update: (patch) => Effect.asVoid(update(patch)),
72 }),
73 );
74 }),