Skip to content

Commit 3016993

Browse files
feat: sign in to GitHub through the T3 Code for GitHub app
GitHub requests from T3 Code share the user's personal 5,000/hr API limit with everything else they run. Signing in through a GitHub App owned by an Enterprise Cloud org gets per-user tokens with a higher limit. Adds an optional "Sign in with GitHub" credential next to saved tokens, GH_TOKEN and the gh login. The server runs GitHub's device flow with the app's public client ID, keeps the session as a secret setting, and refreshes it before expiry. The app token is used only for repositories an installation covers; others fall back to the user's own credential. PR views and new clones suggest installing the app where it is missing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0894156 commit 3016993

50 files changed

Lines changed: 2279 additions & 236 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/features/projects/AddProjectScreen.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
8787
import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
8888
import { uuidv4 } from "../../lib/uuid";
8989
import { useAtomCommand } from "../../state/use-atom-command";
90+
import { suggestAppAccessForRemote } from "./suggestAppAccess";
9091
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
9192
import {
9293
useRemoteConnectionStatus,
@@ -1320,6 +1321,10 @@ export function AddProjectDestinationScreen(props: {
13201321
const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
13211322
reportFailure: false,
13221323
});
1324+
const checkAppAccess = useAtomCommand(sourceControlEnvironment.checkAppAccess, {
1325+
reportFailure: false,
1326+
reportDefect: false,
1327+
});
13231328
const navigation = useNavigation();
13241329
const environment = useEnvironmentFromParam(props.environmentId);
13251330
const canWriteSourceControl = useEnvironmentScope(
@@ -1383,6 +1388,7 @@ export function AddProjectDestinationScreen(props: {
13831388
if (AsyncResult.isFailure(startResult)) {
13841389
setError(errorMessage(Cause.squash(startResult.cause)));
13851390
} else {
1391+
void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
13861392
// Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
13871393
const project = await waitForProject(
13881394
{ environmentId: environment.environmentId, projectId },
@@ -1423,6 +1429,7 @@ export function AddProjectDestinationScreen(props: {
14231429
if (AsyncResult.isFailure(cloneResult)) {
14241430
setError(errorMessage(Cause.squash(cloneResult.cause)));
14251431
} else {
1432+
void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
14261433
const createResult = await createProject(cloneResult.value.cwd, originRoute);
14271434
if (createResult && AsyncResult.isFailure(createResult)) {
14281435
setError(errorMessage(Cause.squash(createResult.cause)));
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import { pullRequestLabelColor } from "./pullRequestList";
8282
import { PullRequestReactions } from "./PullRequestReactions";
8383
import { composerPullRequests } from "../../state/pull-requests";
8484
import { useEnvironmentQuery } from "../../state/query";
85+
import { SourceControlAppAccessNotice } from "./SourceControlAppAccessNotice";
8586
import { usePullToRefresh } from "../../state/use-pull-to-refresh";
8687
import {
8788
resolveNativeReviewDiffView,
@@ -720,6 +721,12 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
720721
<View>
721722
{tab === "overview" && identity ? (
722723
<View>
724+
<SourceControlAppAccessNotice
725+
environmentId={params.environmentId}
726+
provider={identity.provider}
727+
host={params.host}
728+
repository={params.repository}
729+
/>
723730
{pr ? (
724731
<PullRequestOverview
725732
pr={pr}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ vi.mock("../../state/preferences", () => ({
4545
updateMobilePreferencesAtom: {},
4646
}));
4747
vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
48+
vi.mock("./components/SourceControlSignInSection", () => ({
49+
SourceControlSignInSection: () => null,
50+
}));
4851
vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
4952
vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
5053
vi.mock("../../state/session", () => ({

‎apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
2828
import { SettingsChoiceRow } from "./components/SettingsChoiceRow";
2929
import { SettingsSection } from "./components/SettingsSection";
3030
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
31+
import { SourceControlSignInSection } from "./components/SourceControlSignInSection";
3132
import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
3233
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
3334
import { useSettingsWriter } from "./useSettingsWriter";
@@ -395,6 +396,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
395396

396397
{props.page === "source-control" ? (
397398
<>
399+
{projectSelected ? null : (
400+
<SourceControlSignInSection
401+
environments={selectedTargets}
402+
canWrite={(environmentId) => writableEnvironments.has(environmentId)}
403+
/>
404+
)}
398405
<SettingsSection title="Pull requests">
399406
<SettingsSwitchRow
400407
icon={PullRequestGlyph.merged}
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
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 { useState } from "react";
11+
import { Alert, Linking } from "react-native";
12+
13+
import { serverEnvironment } from "../../../state/server";
14+
import { sourceControlEnvironment } from "../../../state/sourceControl";
15+
import { useAtomCommand } from "../../../state/use-atom-command";
16+
import type { SettingsTarget } from "../settings-environment-filter";
17+
import { SettingsRow } from "./SettingsRow";
18+
import { SettingsSection } from "./SettingsSection";
19+
20+
const failureMessage = (cause: Cause.Cause<unknown>) => {
21+
const error = Cause.squash(cause);
22+
return error instanceof Error ? error.message : String(error);
23+
};
24+
25+
const openUrl = (url: string) => void Linking.openURL(url).catch(() => undefined);
26+
27+
const appSignInHosts = sourceControlClients.definitions.flatMap((definition) =>
28+
definition.credentials?.appSignIn === undefined
29+
? []
30+
: [{ definition, appSignIn: definition.credentials.appSignIn }],
31+
);
32+
33+
/** Signing an environment in through a forge's own app, such as T3 Code for GitHub. */
34+
export function SourceControlSignInSection(props: {
35+
readonly environments: readonly SettingsTarget[];
36+
readonly canWrite: (environmentId: EnvironmentId) => boolean;
37+
}) {
38+
if (props.environments.length === 0) return null;
39+
return (
40+
<>
41+
{appSignInHosts.map(({ definition, appSignIn }) => (
42+
<SettingsSection key={definition.kind} title={definition.label}>
43+
{props.environments.map((environment) => (
44+
<AppSignInRow
45+
key={environment.environmentId}
46+
environment={environment}
47+
label={props.environments.length > 1 ? environment.label : appSignIn.appName}
48+
definition={definition}
49+
appSignIn={appSignIn}
50+
disabled={!props.canWrite(environment.environmentId)}
51+
/>
52+
))}
53+
</SettingsSection>
54+
))}
55+
</>
56+
);
57+
}
58+
59+
function AppSignInRow(props: {
60+
readonly environment: SettingsTarget;
61+
readonly label: string;
62+
readonly definition: SourceControlDefinition;
63+
readonly appSignIn: SourceControlAppSignIn;
64+
readonly disabled: boolean;
65+
}) {
66+
const { environment, definition, appSignIn } = props;
67+
const environmentId = environment.environmentId;
68+
const host = appSignIn.hosts[0] ?? "";
69+
const { signIns } = readHostCredentialSettings(
70+
environment.serverConfig.settings,
71+
definition.kind,
72+
);
73+
const signedIn = (signIns[host] ?? "").length > 0;
74+
const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
75+
const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
76+
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
77+
label: `sign out of ${appSignIn.appName}`,
78+
});
79+
const [pending, setPending] = useState<SourceControlSignInPrompt | "starting" | null>(null);
80+
81+
const showCode = (prompt: SourceControlSignInPrompt) => {
82+
void Clipboard.setStringAsync(prompt.userCode).catch(() => undefined);
83+
Alert.alert(
84+
prompt.userCode,
85+
`Enter this code on GitHub, then approve ${appSignIn.appName}. It is copied. The server finishes signing in even if you leave the app.`,
86+
[
87+
{ text: "Cancel", style: "cancel", onPress: () => setPending(null) },
88+
{ text: "Open GitHub", onPress: () => openUrl(prompt.verificationUri) },
89+
],
90+
);
91+
};
92+
93+
const signIn = async () => {
94+
setPending("starting");
95+
const input = { provider: definition.kind, host };
96+
const started = await start({ environmentId, input });
97+
if (started._tag !== "Success") {
98+
setPending(null);
99+
Alert.alert("Could not start the sign-in", failureMessage(started.cause));
100+
return;
101+
}
102+
const prompt = started.value;
103+
setPending(prompt);
104+
showCode(prompt);
105+
const finished = await wait({ environmentId, input });
106+
setPending((current) => (current === prompt ? null : current));
107+
if (finished._tag !== "Success") {
108+
Alert.alert("Sign-in did not finish", failureMessage(finished.cause));
109+
}
110+
};
111+
112+
const signOut = () =>
113+
void updateSettings({
114+
environmentId,
115+
// Send the whole map; other hosts' redaction markers preserve their sessions.
116+
input: {
117+
patch: {
118+
sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
119+
},
120+
},
121+
});
122+
123+
const onPress = () => {
124+
if (signedIn) {
125+
Alert.alert(
126+
appSignIn.appName,
127+
"Signed in. GitHub requests use the app's higher rate limit, in repositories where the app is installed.",
128+
[
129+
{ text: "Install on an organization", onPress: () => openUrl(appSignIn.installUrl) },
130+
{ text: "Sign out", style: "destructive", onPress: signOut },
131+
{ text: "Cancel", style: "cancel" },
132+
],
133+
);
134+
} else if (pending !== null && pending !== "starting") {
135+
showCode(pending);
136+
} else if (pending === null) {
137+
void signIn();
138+
}
139+
};
140+
141+
return (
142+
<SettingsRow
143+
icon="person.crop.circle"
144+
label={props.label}
145+
value={
146+
signedIn
147+
? "Signed in"
148+
: pending === "starting"
149+
? "Starting…"
150+
: pending !== null
151+
? `Enter ${pending.userCode}`
152+
: "Sign in"
153+
}
154+
disabled={props.disabled}
155+
onPress={onPress}
156+
/>
157+
);
158+
}

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ export const RPC_REQUIRED_SCOPES = {
144144
[WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
145145
[WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
146146
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
147+
[WS_METHODS.sourceControlAppAccess]: AuthOrchestrationReadScope,
147148
[WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
148149
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
149150
[WS_METHODS.projectsListIgnoredFiles]: AuthFilesystemReadScope,

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ const RPC_AGGREGATES = {
140140
[WS_METHODS.sourceControlLookupRepository]: "source-control",
141141
[WS_METHODS.sourceControlCloneRepository]: "source-control",
142142
[WS_METHODS.sourceControlPublishRepository]: "source-control",
143+
[WS_METHODS.sourceControlSignInStart]: "source-control",
144+
[WS_METHODS.sourceControlSignInWait]: "source-control",
145+
[WS_METHODS.sourceControlAppAccess]: "source-control",
143146
[WS_METHODS.projectCloneStart]: "source-control",
144147
[WS_METHODS.projectCloneCancel]: "source-control",
145148
[WS_METHODS.projectCloneRetry]: "source-control",

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1565,7 +1565,7 @@ export const make = Effect.gen(function* () {
15651565
}
15661566
const result = yield* api
15671567
.withVerifiedCredential(
1568-
{ cwd: project.project.workspaceRoot, host: project.host },
1568+
{ cwd: project.project.workspaceRoot, host: project.host, repository: project.repository },
15691569
(identity) =>
15701570
identity.accountId === input.expectedAccountId
15711571
? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)
@@ -2066,7 +2066,11 @@ export const make = Effect.gen(function* () {
20662066
return input.action === "delete-branch" && project.api.withVerifiedCredential !== undefined
20672067
? project.api
20682068
.withVerifiedCredential(
2069-
{ cwd: project.project.workspaceRoot, host: project.host },
2069+
{
2070+
cwd: project.project.workspaceRoot,
2071+
host: project.host,
2072+
repository: project.repository,
2073+
},
20702074
() => operation.pipe(Effect.result),
20712075
)
20722076
.pipe(

0 commit comments

Comments
 (0)