@devries-cameron20 / t3code-1 / commits / d694c44d07
Fork 0

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

fix(server): a saved source control token that can't be read no longer falls back to another account (#31646)

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

Julius Marminge committed Nov 5, 2026 at 15:08 UTC d694c44d07842a2b403b6c4dd98950ba6e1c6339
16 files changed +266 -85
apps/server/src/secrets/settingsSecretValue.ts
+8 -12
@@ -1,16 +1,18 @@
1 import {
2 isSecretReference,
3 secretReferencesInSettings,
4 + SettingsSecretUnresolvedError,
5 type SettingsSecretValue,
6 withSettingsSecrets,
7 } from "@t3tools/contracts";
8 import type * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
9 import * as Effect from "effect/Effect";
9 -import * as Schema from "effect/Schema";
10 +import type * as Schema from "effect/Schema";
11
12 /**
13 * Replaces each reference in the slots `schema` declares as `SettingsSecretValue` with the secret
13 - * it names, read in one batch. An unreadable secret comes back as `""`, so it behaves as unset.
14 + * it names, read in one batch. A secret that cannot be read, or reads empty, keeps its reference,
15 + * which `requireSettingsSecretLiteral` turns into an error for the consumer of that field.
16 */
17 export const resolveSettingsSecrets = Effect.fn("SettingsSecrets.resolve")(function* <
18 Settings extends Readonly<Record<string, unknown>>,
@@ -20,19 +22,13 @@ export const resolveSettingsSecrets = Effect.fn("SettingsSecrets.resolve")(funct
22 const values = yield* resolver.read(pending.map(({ reference }) => reference));
23 return withSettingsSecrets(
24 settings,
23 - pending.map((slot, index) => ({ ...slot, value: values[index] ?? "" })),
25 + pending.flatMap((slot, index) => {
26 + const value = values[index];
27 + return value === undefined || value.trim() === "" ? [] : [{ ...slot, value }];
28 + }),
29 );
30 });
31
27 -export class SettingsSecretUnresolvedError extends Schema.TaggedError<SettingsSecretUnresolvedError>()(
28 - "SettingsSecretUnresolvedError",
29 - { provider: Schema.String },
30 -) {
31 - override get message(): string {
32 - return `Could not read the credential from the secret provider "${this.provider}". Unlock or fix it in Settings, then try again.`;
33 - }
34 -}
35 -
32 /**
33 * The secret a credential setting holds or names. A named secret that cannot be read, or reads
34 * empty, fails instead of passing for a missing token, so callers that would fall back to another
apps/server/src/sourceControl/sourceControlHostSecrets.test.ts
+2 -2
@@ -58,11 +58,11 @@ it.effect(
58 }),
59 );
60
61 -it.effect("treats a reference the provider cannot read as an unset credential", () =>
61 +it.effect("keeps a reference the provider cannot read, so it never passes for an unset one", () =>
62 Effect.gen(function* () {
63 const { reads, resolver } = countingResolver();
64 const resolved = yield* resolveSourceControlHostSecrets(resolver, hosts, "gitcafe");
65 - assert.deepEqual(resolved.gitcafe, { token: "" });
65 + assert.deepEqual(resolved.gitcafe, { token: source("missing#token") });
66 assert.deepEqual(reads, ["missing#token"]);
67 }),
68 );
packages/contracts/src/settingsSecretValue.ts
+30
@@ -1,3 +1,4 @@
1 +import * as Effect from "effect/Effect";
2 import * as Schema from "effect/Schema";
3 import * as SchemaAST from "effect/SchemaAST";
4
@@ -22,6 +23,35 @@ export function settingsSecretLiteral(value: SettingsSecretValue | undefined): s
23 return typeof value === "string" ? value : "";
24 }
25
26 +export class SettingsSecretUnresolvedError extends Schema.TaggedError<SettingsSecretUnresolvedError>()(
27 + "SettingsSecretUnresolvedError",
28 + { provider: Schema.String },
29 +) {
30 + override get message(): string {
31 + return `Could not read the credential from the secret provider "${this.provider}". Unlock or fix it in Settings, then try again.`;
32 + }
33 +}
34 +
35 +/**
36 + * The literal a credential setting holds once its secret is resolved. A reference still in place
37 + * could not be read, and fails instead of passing for a missing token, so callers that would fall
38 + * back to another credential cannot silently switch accounts.
39 + */
40 +export const requireSettingsSecretLiteral = (
41 + value: SettingsSecretValue | undefined,
42 + secretProviders: Readonly<Record<string, { readonly label: string } | undefined>>,
43 +): Effect.Effect<string, SettingsSecretUnresolvedError> =>
44 + isSecretReference(value)
45 + ? Effect.fail(
46 + new SettingsSecretUnresolvedError({
47 + provider:
48 + (Object.hasOwn(secretProviders, value.provider)
49 + ? secretProviders[value.provider]?.label.trim()
50 + : undefined) || value.provider,
51 + }),
52 + )
53 + : Effect.succeed(value ?? "");
54 +
55 export function acceptsSecretReference(schema: Schema.Top): boolean {
56 return Schema.resolveAnnotationsKey(schema)?.settingsSecretReference === true;
57 }
packages/source-control-bitbucket/src/server/BitbucketApi.test.ts
+19 -1
@@ -1,4 +1,4 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
1 +import { SecretProviderId, SourceControlProviderKind } from "@t3tools/contracts";
2 import { assert, it, vi } from "@effect/vitest";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as ConfigProvider from "effect/ConfigProvider";
@@ -669,6 +669,24 @@ it.effect("prefers credentials saved in settings over the environment, without a
669 });
670 yield* bitbucket.probeAuth;
671 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
672 +
673 + // A reference left in place by getWithSecrets is one its secret provider could not read.
674 + const requests = execute.mock.calls.length;
675 + yield* settings.update({
676 + sourceControlHosts: {
677 + bitbucket: {
678 + accessToken: { provider: SecretProviderId.make("vault"), reference: "bb#token" },
679 + },
680 + },
681 + });
682 + const auth = yield* bitbucket.probeAuth;
683 + assert.strictEqual(auth.status, "unauthenticated");
684 + assert.include(Option.getOrThrow(auth.detail), '"vault"');
685 + const error = yield* Effect.flip(
686 + bitbucket.listPullRequests({ cwd: "/repo", headSelector: "feature", state: "open" }),
687 + );
688 + assert.strictEqual(error._tag, "SettingsSecretUnresolvedError");
689 + assert.strictEqual(execute.mock.calls.length, requests);
690 }).pipe(Effect.provide(layer));
691 });
692
packages/source-control-bitbucket/src/server/BitbucketApi.ts
+48 -30
@@ -9,9 +9,11 @@ import * as Schema from "effect/Schema";
9 import * as Semaphore from "effect/Semaphore";
10 import {
11 NonNegativeInt,
12 - settingsSecretLiteral,
12 + requireSettingsSecretLiteral,
13 + SettingsSecretUnresolvedError,
14 SourceControlProviderKind,
15 TrimmedNonEmptyString,
16 + type ServerSettings,
17 type SourceControlProviderAuth,
18 type SourceControlProviderInfo,
19 type SourceControlRepositoryCloneUrls,
@@ -277,6 +279,7 @@ export const BitbucketApiError = Schema.Union([
279 BitbucketPullRequestBodyReadError,
280 BitbucketCheckoutError,
281 SourceControlRateLimit.SourceControlRateLimitPausedError,
282 + SettingsSecretUnresolvedError,
283 ]);
284 export type BitbucketApiError = typeof BitbucketApiError.Type;
285 const isBitbucketApiError = Schema.is(BitbucketApiError);
@@ -563,23 +566,24 @@ function credentialFrom(input: {
566 return null;
567 }
568
566 -function resolveCredential(
569 +const resolveCredential = Effect.fn("BitbucketApi.resolveCredential")(function* (
570 settings: BitbucketClient.BitbucketSettings,
571 + secretProviders: ServerSettings["secretProviders"],
572 env: Config.Success<typeof BitbucketApiEnvConfig>,
569 -): BitbucketCredential | null {
573 +) {
574 + const accessToken = yield* requireSettingsSecretLiteral(settings.accessToken, secretProviders);
575 + const apiToken = HEADER_SAFE.test(accessToken)
576 + ? ""
577 + : yield* requireSettingsSecretLiteral(settings.apiToken, secretProviders);
578 return (
571 - credentialFrom({
572 - accessToken: settingsSecretLiteral(settings.accessToken),
573 - email: settings.email,
574 - apiToken: settingsSecretLiteral(settings.apiToken),
575 - }) ??
579 + credentialFrom({ accessToken, email: settings.email, apiToken }) ??
580 credentialFrom({
581 accessToken: Option.getOrElse(env.accessToken, () => ""),
582 email: Option.getOrElse(env.email, () => ""),
583 apiToken: Option.getOrElse(env.apiToken, () => ""),
584 })
585 );
582 -}
586 +});
587
588 function authFromCredential(credential: BitbucketCredential | null): SourceControlProviderAuth {
589 if (credential?.kind === "access-token") {
@@ -669,25 +673,27 @@ export const make = Effect.gen(function* () {
673 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
674
675 const currentCredential = host.settings.getWithSecrets(BitbucketClient.definition.kind).pipe(
672 - Effect.map((settings) =>
673 - resolveCredential(
674 - readSourceControlHostSettings(
675 - BitbucketClient.settings,
676 - settings.sourceControlHosts[BitbucketClient.definition.kind],
677 - ),
678 - config,
676 + Effect.map((settings) => ({
677 + bitbucket: readSourceControlHostSettings(
678 + BitbucketClient.settings,
679 + settings.sourceControlHosts[BitbucketClient.definition.kind],
680 ),
680 - ),
681 + secretProviders: settings.secretProviders,
682 + })),
683 Effect.catch((error) =>
684 // No cause: a settings decode error can quote a hand-edited token.
685 Effect.logWarning("failed to read Bitbucket credentials from settings", {
686 operation: error.operation,
687 }).pipe(
686 - Effect.as(
687 - resolveCredential(readSourceControlHostSettings(BitbucketClient.settings, {}), config),
688 - ),
688 + Effect.as({
689 + bitbucket: readSourceControlHostSettings(BitbucketClient.settings, {}),
690 + secretProviders: {},
691 + }),
692 ),
693 ),
694 + Effect.flatMap(({ bitbucket, secretProviders }) =>
695 + resolveCredential(bitbucket, secretProviders, config),
696 + ),
697 );
698
699 const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
@@ -756,13 +762,10 @@ export const make = Effect.gen(function* () {
762 throttled(
763 request.method,
764 withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
759 - Effect.flatMap(httpClient.execute),
760 - Effect.mapError(
761 - (cause) =>
762 - new BitbucketRequestError({
763 - operation,
764 - cause,
765 - }),
765 + Effect.flatMap((authed) =>
766 + httpClient
767 + .execute(authed)
768 + .pipe(Effect.mapError((cause) => new BitbucketRequestError({ operation, cause }))),
769 ),
770 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
771 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
@@ -960,9 +963,15 @@ export const make = Effect.gen(function* () {
963 ? base
964 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
965 return withAuth(withBody).pipe(
963 - Effect.flatMap(httpClient.execute),
964 - Effect.mapError(
965 - (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
966 + Effect.flatMap((request) =>
967 + httpClient
968 + .execute(request)
969 + .pipe(
970 + Effect.mapError(
971 + (cause): BitbucketApiError =>
972 + new BitbucketRequestError({ operation: "request", cause }),
973 + ),
974 + ),
975 ),
976 Effect.flatMap((response) => {
977 const location = response.headers.location;
@@ -1042,6 +1051,15 @@ export const make = Effect.gen(function* () {
1051 Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
1052 ),
1053 ),
1054 + Effect.catchTags({
1055 + SettingsSecretUnresolvedError: (error) =>
1056 + Effect.succeed<SourceControlProviderAuth>({
1057 + status: "unauthenticated",
1058 + account: Option.none(),
1059 + host: Option.some("bitbucket.org"),
1060 + detail: Option.some(error.message),
1061 + }),
1062 + }),
1063 ),
1064 listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {
1065 return resolveRepository(input).pipe(
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+5 -2
@@ -61,7 +61,10 @@ export function bitbucketViewerPermissions(input: {
61 export function bitbucketProviderFailure(
62 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
63 ): PullRequestProviderFailure {
64 - if (error._tag === "BitbucketResponseError" && error.status === 401) {
64 + if (
65 + (error._tag === "BitbucketResponseError" && error.status === 401) ||
66 + error._tag === "SettingsSecretUnresolvedError"
67 + ) {
68 return { reason: "unauthenticated" };
69 }
70 if (error._tag === "SourceControlRateLimitPausedError") {
@@ -135,7 +138,7 @@ export const make = Effect.gen(function* () {
138 provider: SourceControlProviderKind.make("bitbucket"),
139 operation,
140 ...bitbucketProviderFailure(error),
138 - detail: error.detail,
141 + detail: error._tag === "SettingsSecretUnresolvedError" ? error.message : error.detail,
142 cause: error,
143 });
144
packages/source-control-core/src/server/SourceControlHost.ts
+3 -2
@@ -70,8 +70,9 @@ export class SourceControlHost extends Context.Service<
70 readonly get: Effect.Effect<ServerSettings, ServerSettingsError>;
71 /**
72 * Like `get`, with each secret provider reference in one host kind's credentials replaced
73 - * by the secret it names. An unreadable reference reads as unset. Only a reader of that
74 - * kind should call it: resolving can wait on a secret provider.
73 + * by the secret it names. An unreadable reference stays in place; read the field with
74 + * `requireSettingsSecretLiteral` so it fails rather than passing for an unset credential.
75 + * Only a reader of that kind should call it: resolving can wait on a secret provider.
76 */
77 readonly getWithSecrets: (kind: string) => Effect.Effect<ServerSettings, ServerSettingsError>;
78 /** For credentials the host obtains itself, such as a sign-in it refreshes. */
packages/source-control-gitcafe/src/server/GitCafeApi.ts
+1 -1
@@ -82,7 +82,7 @@ const credentialFailure = (
82 ): typeof GitCafeApiFailure.Type =>
83 error._tag === "GitCafeCliMissingError"
84 ? "missing-tool"
85 - : error._tag === "GitCafeNotSignedInError"
85 + : error._tag === "GitCafeNotSignedInError" || error._tag === "SettingsSecretUnresolvedError"
86 ? "unauthenticated"
87 : "failed";
88
packages/source-control-gitcafe/src/server/GitCafeCredentials.test.ts
+19
@@ -1,4 +1,5 @@
1 import { assert, describe, it } from "@effect/vitest";
2 +import { SecretProviderId } from "@t3tools/contracts";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Redacted from "effect/Redacted";
@@ -94,6 +95,24 @@ describe("GitCafeCredentials", () => {
95
96 yield* settings.update({ sourceControlHosts: { gitcafe: { token: "" } } });
97 assert.strictEqual((yield* credentials.get("git.cafe")).source, "env");
98 +
99 + // A reference left in place by getWithSecrets is one its secret provider could not read,
100 + // here one naming a removed provider whose id is also an Object.prototype key.
101 + yield* settings.update({
102 + sourceControlHosts: {
103 + gitcafe: {
104 + token: { provider: SecretProviderId.make("constructor"), reference: "cafe#token" },
105 + },
106 + },
107 + });
108 + const error = yield* Effect.flip(credentials.get("git.cafe"));
109 + assert.strictEqual(error._tag, "SettingsSecretUnresolvedError");
110 + assert.include(error.message, '"constructor"');
111 + assert.strictEqual(
112 + (yield* Effect.flip(credentials.cliEnv("git.cafe")))._tag,
113 + "SettingsSecretUnresolvedError",
114 + );
115 + assert.strictEqual(calls.length, 1);
116 }).pipe(Effect.provide(layer));
117 });
118
packages/source-control-gitcafe/src/server/GitCafeCredentials.ts
+20 -12
@@ -1,4 +1,7 @@
1 -import { settingsSecretLiteral } from "@t3tools/contracts";
1 +import {
2 + requireSettingsSecretLiteral,
3 + type SettingsSecretUnresolvedError,
4 +} from "@t3tools/contracts";
5 import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
6 import * as Cache from "effect/Cache";
7 import * as Context from "effect/Context";
@@ -55,7 +58,8 @@ export class GitCafeCliFailedError extends Schema.TaggedError<GitCafeCliFailedEr
58 export type GitCafeCredentialUnavailableError =
59 | GitCafeCliMissingError
60 | GitCafeNotSignedInError
58 - | GitCafeCliFailedError;
61 + | GitCafeCliFailedError
62 + | SettingsSecretUnresolvedError;
63
64 export class GitCafeCredentials extends Context.Service<
65 GitCafeCredentials,
@@ -64,7 +68,9 @@ export class GitCafeCredentials extends Context.Service<
68 host: string,
69 ) => Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError>;
70 readonly invalidate: (host: string) => Effect.Effect<void>;
67 - readonly cliEnv: (host: string) => Effect.Effect<Readonly<Record<string, string>>>;
71 + readonly cliEnv: (
72 + host: string,
73 + ) => Effect.Effect<Readonly<Record<string, string>>, SettingsSecretUnresolvedError>;
74 }
75 >()("@t3tools/source-control-gitcafe/server/GitCafeCredentials") {}
76
@@ -130,16 +136,18 @@ export const make = Effect.gen(function* () {
136 normalizeHost(host) !== DEFAULT_HOST
137 ? Effect.succeed(null)
138 : sourceControlHost.settings.getWithSecrets(GitCafeClient.definition.kind).pipe(
133 - Effect.map(
134 - (settings) =>
135 - settingsSecretLiteral(
136 - readSourceControlHostSettings(
137 - GitCafeClient.settings,
138 - settings.sourceControlHosts[GitCafeClient.definition.kind],
139 - ).token,
140 - ) || null,
139 + Effect.map((settings) => ({
140 + token: readSourceControlHostSettings(
141 + GitCafeClient.settings,
142 + settings.sourceControlHosts[GitCafeClient.definition.kind],
143 + ).token,
144 + secretProviders: settings.secretProviders,
145 + })),
146 + Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
147 + Effect.flatMap(({ token, secretProviders }) =>
148 + requireSettingsSecretLiteral(token, secretProviders),
149 ),
142 - Effect.orElseSucceed(() => null),
150 + Effect.map((token) => token || null),
151 );
152
153 const lookup = Effect.fn("GitCafeCredentials.lookup")(function* (
packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts
+22 -2
@@ -109,12 +109,32 @@ export const makeDiscovery = Effect.gen(function* () {
109 installHint: cliDiscovery.installHint,
110 probe: (cwd: string) =>
111 credentials.cliEnv(AUTH_HOST).pipe(
112 + Effect.result,
113 Effect.flatMap((env) =>
114 probeSourceControlProvider({
115 cwd,
116 spec: cliDiscovery,
116 - process: { run: (input) => process.run({ ...input, env: { ...input.env, ...env } }) },
117 - }),
117 + process: {
118 + run: (input) =>
119 + process.run({
120 + ...input,
121 + env: { ...input.env, ...(Result.isSuccess(env) ? env.success : {}) },
122 + }),
123 + },
124 + }).pipe(
125 + Effect.map((item) =>
126 + Result.isSuccess(env)
127 + ? item
128 + : {
129 + ...item,
130 + auth: providerAuth({
131 + status: "unauthenticated",
132 + host: AUTH_HOST,
133 + detail: env.failure.message,
134 + }),
135 + },
136 + ),
137 + ),
138 ),
139 ),
140 refineUnknownRemote: () => Effect.succeed(null),
packages/source-control-github/src/server/GitHubCredentials.test.ts
+23 -1
@@ -6,7 +6,7 @@ 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";
9 +import { DEFAULT_SERVER_SETTINGS, SecretProviderId, SecretProviderKind } from "@t3tools/contracts";
10 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
12 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
@@ -137,9 +137,31 @@ describe("GitHubCredentials", () => {
137 const { layer, calls } = harness({}, [], { "github.com": "saved-token" });
138 return Effect.gen(function* () {
139 const credentials = yield* GitHubCredentials.GitHubCredentials;
140 + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
141 const credential = yield* credentials.get("github.com");
142 expect(Redacted.value(credential.token)).toBe("saved-token");
143 expect(credential.source).toBe("settings");
144 +
145 + // A reference left in place by getWithSecrets is one its secret provider could not read.
146 + yield* settings.update({
147 + secretProviders: {
148 + [SecretProviderId.make("vault")]: {
149 + kind: SecretProviderKind.make("one_password"),
150 + label: "Work vault",
151 + config: {},
152 + },
153 + },
154 + sourceControlHosts: {
155 + github: {
156 + tokens: {
157 + "github.com": { provider: SecretProviderId.make("vault"), reference: "gh#token" },
158 + },
159 + },
160 + },
161 + });
162 + const error = yield* Effect.flip(credentials.get("github.com"));
163 + expect(error._tag).toBe("SettingsSecretUnresolvedError");
164 + expect(error.message).toContain('"Work vault"');
165 expect(calls).toEqual([]);
166 }).pipe(Effect.provide(layer));
167 });
packages/source-control-github/src/server/GitHubCredentials.ts
+16 -6
@@ -16,7 +16,11 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
16
17 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18 import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
19 -import { settingsSecretLiteral, type ServerSettings } from "@t3tools/contracts";
19 +import {
20 + requireSettingsSecretLiteral,
21 + type ServerSettings,
22 + type SettingsSecretUnresolvedError,
23 +} from "@t3tools/contracts";
24
25 import * as GitHubClient from "../shared/definition.ts";
26
@@ -81,7 +85,8 @@ export type GitHubCredentialUnavailableError =
85 | GitHubCliMissingError
86 | GitHubNotSignedInError
87 | GitHubHostDisabledError
84 - | GitHubCliFailedError;
88 + | GitHubCliFailedError
89 + | SettingsSecretUnresolvedError;
90
91 export class GitHubCredentials extends Context.Service<
92 GitHubCredentials,
@@ -94,7 +99,7 @@ export class GitHubCredentials extends Context.Service<
99 host: string,
100 ) => Effect.Effect<
101 Option.Option<GitHubCredential>,
97 - GitHubHostDisabledError | GitHubNotSignedInError
102 + GitHubHostDisabledError | GitHubNotSignedInError | SettingsSecretUnresolvedError
103 >;
104 readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;
105 readonly invalidate: (host: string) => Effect.Effect<void>;
@@ -195,10 +200,15 @@ export const make = Effect.gen(function* () {
200
201 const savedToken = (host: string) =>
202 sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(
198 - Effect.map(
199 - (settings) => settingsSecretLiteral(readSettings(settings).tokens[host]).trim() || null,
203 + Effect.map((settings) => ({
204 + token: readSettings(settings).tokens[host],
205 + secretProviders: settings.secretProviders,
206 + })),
207 + Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),
208 + Effect.flatMap(({ token, secretProviders }) =>
209 + requireSettingsSecretLiteral(token, secretProviders),
210 ),
201 - Effect.orElseSucceed(() => null),
211 + Effect.map((token) => token.trim() || null),
212 );
213
214 const cacheKey = (host: string, account: string | undefined) =>
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+1
@@ -111,6 +111,7 @@ function gitHubProviderFailure(
111 return { reason: "missing-tool" };
112 case "GitHubNotSignedInError":
113 case "GitHubHostDisabledError":
114 + case "SettingsSecretUnresolvedError":
115 case "GitHubApiAuthenticationError":
116 return { reason: "unauthenticated" };
117 case "GitHubApiRateLimitError":
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+21 -7
@@ -1,4 +1,4 @@
1 -import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";
1 +import { requireSettingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";
2 import * as DateTime from "effect/DateTime";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
@@ -222,12 +222,12 @@ export const makeDiscovery = Effect.gen(function* () {
222 label: discovery.label,
223 installHint: discovery.installHint,
224 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
225 + const current = yield* sourceControlHost.settings
226 + .getWithSecrets(GitHubClient.definition.kind)
227 + .pipe(Effect.orElseSucceed(() => undefined));
228 const settings = readSourceControlHostSettings(
229 GitHubClient.settings,
227 - yield* sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(
228 - Effect.map((current) => current.sourceControlHosts[GitHubClient.definition.kind]),
229 - Effect.orElseSucceed(() => undefined),
230 - ),
230 + current?.sourceControlHosts[GitHubClient.definition.kind],
231 );
232 const cli = yield* probeSourceControlProvider({
233 cwd,
@@ -236,8 +236,21 @@ export const makeDiscovery = Effect.gen(function* () {
236 },
237 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
238 });
239 - const token = settings.tokens["github.com"];
240 - const savedToken = settingsSecretLiteral(token).trim() !== "";
239 + const saved = yield* Effect.result(
240 + requireSettingsSecretLiteral(settings.tokens["github.com"], current?.secretProviders ?? {}),
241 + );
242 + if (Result.isFailure(saved) && settings.hosts["github.com"]?.enabled !== false) {
243 + return offerAppSignIn({
244 + ...cli,
245 + status: "available" as const,
246 + auth: providerAuth({
247 + status: "unauthenticated",
248 + host: "github.com",
249 + detail: saved.failure.message,
250 + }),
251 + });
252 + }
253 + const savedToken = Result.isSuccess(saved) && saved.success.trim() !== "";
254 const signedIn =
255 appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";
256 const variable = environmentTokenVariable(environment);
@@ -339,6 +352,7 @@ function fromGitHubApiError(
352 );
353 case "GitHubNotSignedInError":
354 case "GitHubHostDisabledError":
355 + case "SettingsSecretUnresolvedError":
356 return failure(error.message, error);
357 case "GitHubApiAuthenticationError":
358 return failure(
packages/source-control-github/src/server/gitHubDiscovery.test.ts
+28 -7
@@ -92,9 +92,26 @@ const referencedTokenSettings = decodeSettings({
92 });
93
94 it.effect.each([
95 - { name: "readable", token: "resolved-token", source: "the token saved in Settings" },
96 - { name: "unreadable", token: "", source: "GH_TOKEN from the server environment" },
97 -])("checks the $name GitHub token reference against the API", (scenario) =>
95 + {
96 + name: "a readable",
97 + token: "resolved-token",
98 + status: "authenticated",
99 + detail: "the token saved in Settings",
100 + },
101 + {
102 + name: "no",
103 + token: "",
104 + status: "authenticated",
105 + detail: "GH_TOKEN from the server environment",
106 + },
107 + // getWithSecrets leaves a reference its secret provider could not read in place.
108 + {
109 + name: "an unreadable",
110 + token: { provider: "vault", reference: "op://v/gh" },
111 + status: "unauthenticated",
112 + detail: 'secret provider "vault"',
113 + },
114 +])("reports $name saved GitHub token instead of another credential", (scenario) =>
115 Effect.gen(function* () {
116 const paths: Array<string> = [];
117 const discovery = yield* GitHubSourceControlProvider.makeDiscovery.pipe(
@@ -153,9 +170,13 @@ it.effect.each([
170 );
171 if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
172 const item = yield* discovery.probe("/repo");
156 - assert.deepStrictEqual(paths, ["user"]);
157 - assert.strictEqual(item.auth.status, "authenticated");
158 - assert.deepStrictEqual(item.auth.account, Option.some("octocat"));
159 - assert.include(Option.getOrThrow(item.auth.detail), scenario.source);
173 + const authenticated = scenario.status === "authenticated";
174 + assert.deepStrictEqual(paths, authenticated ? ["user"] : []);
175 + assert.strictEqual(item.auth.status, scenario.status);
176 + assert.deepStrictEqual(
177 + item.auth.account,
178 + authenticated ? Option.some("octocat") : Option.none(),
179 + );
180 + assert.include(Option.getOrThrow(item.auth.detail), scenario.detail);
181 }),
182 );