Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(skill): read private GitHub repos with a token saved in the Vault (#23680)

Lobehub Coder7e1df88edb2b
diff --git a/apps/server/src/modules/GitHub/index.ts b/apps/server/src/modules/GitHub/index.ts
index b2d9c53d525..99a99c9fb36 100644
--- a/apps/server/src/modules/GitHub/index.ts
+++ b/apps/server/src/modules/GitHub/index.ts
@@ -149,12 +149,27 @@ export class GitHub {
return `https://raw.githubusercontent.com/${info.owner}/${info.repo}/${info.branch}/${info.filePath}`;
}
- async resolveCommit(info: GitHubRepoInfo) {
- const repoUrl = `https://api.github.com/repos/${encodeURIComponent(info.owner)}/${encodeURIComponent(info.repo)}`;
- const response = await fetch(`${repoUrl}/commits/${encodeURIComponent(info.branch)}`, {
- headers: { 'Accept': 'application/vnd.github.sha', 'User-Agent': this.userAgent },
- signal: AbortSignal.timeout(15_000),
- });
+ private apiRepoUrl(info: GitHubRepoInfo) {
+ return `https://api.github.com/repos/${encodeURIComponent(info.owner)}/${encodeURIComponent(info.repo)}`;
+ }
+
+ /**
+ * Resolve a ref to its commit. With `token`, the request is authenticated
+ * (api.github.com only) and a rejected token throws `GitHubAuthError`.
+ */
+ async resolveCommit(info: GitHubRepoInfo, token?: string) {
+ const response = await fetch(
+ `${this.apiRepoUrl(info)}/commits/${encodeURIComponent(info.branch)}`,
+ {
+ headers: {
+ 'Accept': 'application/vnd.github.sha',
+ 'User-Agent': this.userAgent,
+ ...(token && { Authorization: `Bearer ${token}` }),
+ },
+ signal: AbortSignal.timeout(15_000),
+ },
+ );
+ if (token && response.status === 401) throw new GitHubAuthError('GitHub token was rejected');
// A missing repository answers 404, a missing ref answers 422.
if (response.status === 404 || response.status === 422)
throw new GitHubNotFoundError('GitHub repository or ref not found', response.status);
@@ -183,6 +198,36 @@ export class GitHub {
return this.readArchive(response);
}
+ /**
+ * Download a commit's archive with a token. Only the api.github.com request
+ * carries the token; the archive it redirects to is pre-signed and fetched
+ * without credentials.
+ */
+ async downloadTokenZip(info: GitHubRepoInfo, commit: string, token: string) {
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new GitHubParseError('Invalid commit SHA');
+ const response = await fetch(`${this.apiRepoUrl(info)}/zipball/${commit}`, {
+ headers: {
+ 'Accept': 'application/vnd.github+json',
+ 'Authorization': `Bearer ${token}`,
+ 'User-Agent': this.userAgent,
+ },
+ redirect: 'manual',
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.status === 401) throw new GitHubAuthError('GitHub token was rejected');
+ if (response.status === 404 || response.status === 403)
+ throw new GitHubNotFoundError('GitHub repository or commit is inaccessible', response.status);
+ if (response.status >= 300 && response.status < 400) {
+ await response.body?.cancel();
+ const location = response.headers.get('location');
+ if (!location) throw new GitHubDownloadError('Missing GitHub archive location');
+ return this.downloadSnapshotZip(
+ new URL(location, response.url || this.apiRepoUrl(info)).href,
+ );
+ }
+ return this.readArchive(response);
+ }
+
/**
* Download a ref's archive and read the commit it was cut from out of the ZIP
* comment. Uses no REST API quota, so it still works when `resolveCommit` is
@@ -366,6 +411,14 @@ export class GitHubDownloadError extends GitHubError {
}
}
+/** The token sent with a request was rejected (401). */
+export class GitHubAuthError extends GitHubError {
+ constructor(message: string) {
+ super(message);
+ this.name = 'GitHubAuthError';
+ }
+}
+
export class GitHubRateLimitError extends GitHubError {
constructor(message: string) {
super(message);
diff --git a/apps/server/src/routers/lambda/agentSkills.ensure.test.ts b/apps/server/src/routers/lambda/agentSkills.ensure.test.ts
index 1a17db06a34..f93e400d41d 100644
--- a/apps/server/src/routers/lambda/agentSkills.ensure.test.ts
+++ b/apps/server/src/routers/lambda/agentSkills.ensure.test.ts
@@ -95,6 +95,7 @@ describe('agentSkills.ensureFromMarket', () => {
expect(mocks.modelConstructor).toHaveBeenCalledWith({}, 'user', 'workspace');
expect(mocks.importerConstructor).toHaveBeenLastCalledWith({}, 'user', 'workspace', {
githubProxy: expect.any(Function),
+ githubToken: expect.any(Function),
workspaceRole: 'member',
});
expect(mocks.importFromUrl).toHaveBeenCalledWith(
diff --git a/apps/server/src/routers/lambda/agentSkills.ts b/apps/server/src/routers/lambda/agentSkills.ts
index 53f069a72e1..fcc1b4d5d88 100644
--- a/apps/server/src/routers/lambda/agentSkills.ts
+++ b/apps/server/src/routers/lambda/agentSkills.ts
@@ -19,6 +19,7 @@ import {
SkillResourceError,
SkillResourceService,
} from '@/server/services/skill';
+import { resolveVaultGitHubToken, workspaceOwned } from '@/server/services/skill/vaultGitHubToken';
import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
@@ -91,13 +92,30 @@ const skillProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
return market.proxyOAuthRequest(request);
};
+ // Read lazily: only a repository the anonymous request cannot read asks the Vault.
+ const githubToken = async () => {
+ const { marketAccessToken, marketUserInfo } = await resolveMarketUserContext(ctx);
+ const market = new MarketService({
+ accessToken: marketAccessToken ?? ctx.marketAccessToken,
+ userInfo: marketUserInfo,
+ }).market;
+ return resolveVaultGitHubToken([
+ market.creds,
+ ...(workspaceId ? [workspaceOwned(market.organizations.creds({ workspaceId }))] : []),
+ ]);
+ };
+
return opts.next({
ctx: {
githubProxy,
+ githubToken,
fileModel: new FileModel(ctx.serverDB, ctx.userId, workspaceId),
fileService: new FileService(ctx.serverDB, ctx.userId, workspaceId),
marketService: new MarketService({ userInfo: { userId: ctx.userId } }),
- skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, workspaceId, { githubProxy }),
+ skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, workspaceId, {
+ githubProxy,
+ githubToken,
+ }),
skillModel,
},
});
@@ -120,6 +138,7 @@ const skillWriteProcedure = skillProcedure
ctx: {
skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined, {
githubProxy: ctx.githubProxy,
+ githubToken: ctx.githubToken,
workspaceRole: (ctx as { workspaceRole?: string }).workspaceRole,
}),
},
diff --git a/apps/server/src/services/skill/githubRepository.test.ts b/apps/server/src/services/skill/githubRepository.test.ts
index 15235356740..18d07b25a48 100644
--- a/apps/server/src/services/skill/githubRepository.test.ts
+++ b/apps/server/src/services/skill/githubRepository.test.ts
@@ -87,3 +87,88 @@ it('rejects a connector snapshot that does not match the selected commit', async
'different commit',
);
});
+
+const token = 'ghp_vaulttoken';
+const vaultSource = (vaultToken = vi.fn().mockResolvedValue(token)) =>
+ new GitHubSkillRepository(new GitHub(), proxy, vaultToken);
+const authOf = (init?: RequestInit) => new Headers(init?.headers).get('authorization');
+
+it('resolves a private ref with the Vault token before asking the connector', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(missing())
+ .mockResolvedValueOnce(new Response(commit));
+ vi.stubGlobal('fetch', fetch);
+ const record = vi.spyOn(redisService.gitHubRefs, 'record');
+ expect(await vaultSource().resolveCommit(info)).toEqual({ commit, public: false });
+ expect(authOf(fetch.mock.calls[0][1])).toBeNull();
+ expect(fetch.mock.calls[1][0]).toBe('https://api.github.com/repos/owner/private/commits/HEAD');
+ expect(authOf(fetch.mock.calls[1][1])).toBe(`Bearer ${token}`);
+ expect(record).not.toHaveBeenCalled();
+ expect(proxy).not.toHaveBeenCalled();
+});
+
+it('does not cache a token-resolved ref for everyone in update checks', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValueOnce(missing()).mockResolvedValueOnce(new Response(commit)),
+ );
+ const remember = vi
+ .spyOn(redisService.gitHubRefs, 'remember')
+ .mockImplementation(async (_info, resolve) => resolve());
+ expect(await vaultSource().resolveCommit(info, true)).toEqual({ commit, public: false });
+ expect(remember).toHaveBeenCalledTimes(1);
+});
+
+it('sends the Vault token only to api.github.com when downloading a private archive', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(missing())
+ .mockResolvedValueOnce(new Response(null, { headers: { location: signed }, status: 302 }))
+ .mockResolvedValueOnce(new Response('zip'));
+ vi.stubGlobal('fetch', fetch);
+ expect(await vaultSource().downloadCommitZip(info, commit)).toEqual(Buffer.from('zip'));
+ expect(fetch.mock.calls[1][0]).toBe(
+ `https://api.github.com/repos/owner/private/zipball/${commit}`,
+ );
+ expect(authOf(fetch.mock.calls[1][1])).toBe(`Bearer ${token}`);
+ expect(fetch.mock.calls[2][0]).toBe(signed);
+ expect(authOf(fetch.mock.calls[2][1])).toBeNull();
+ expect(proxy).not.toHaveBeenCalled();
+});
+
+it('falls through to the connector when GitHub rejects the Vault token', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(missing())
+ .mockResolvedValueOnce(new Response(null, { status: 401 }));
+ vi.stubGlobal('fetch', fetch);
+ proxy.mockResolvedValue({ data: snapshot, status: 200 });
+ const vaultToken = vi.fn().mockResolvedValue(token);
+ const repo = vaultSource(vaultToken);
+ expect(await repo.resolveCommit(info)).toEqual({ commit, public: false });
+ expect(proxy).toHaveBeenCalledTimes(1);
+
+ // A rejected token is not retried for the rest of the request.
+ fetch.mockResolvedValueOnce(missing());
+ proxy.mockResolvedValue({ data: snapshot, status: 200 });
+ await repo.resolveCommit(info);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(vaultToken).toHaveBeenCalledTimes(1);
+});
+
+it('falls through to the connector when the Vault token cannot read the repository', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(missing()));
+ proxy.mockResolvedValue({ data: { error: { code: 'NOT_CONNECTED' } }, status: 403 });
+ await expect(vaultSource().resolveCommit(info)).rejects.toMatchObject({
+ code: 'CONNECT_GITHUB',
+ message: expect.stringContaining('GITHUB_TOKEN'),
+ });
+});
+
+it('does not ask the Vault for a missing ref', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 422 })));
+ const vaultToken = vi.fn();
+ await expect(vaultSource(vaultToken).resolveCommit(info)).rejects.toMatchObject({ status: 422 });
+ expect(vaultToken).not.toHaveBeenCalled();
+});
diff --git a/apps/server/src/services/skill/githubRepository.ts b/apps/server/src/services/skill/githubRepository.ts
index e80184c8811..a61bab0d8f9 100644
--- a/apps/server/src/services/skill/githubRepository.ts
+++ b/apps/server/src/services/skill/githubRepository.ts
@@ -2,6 +2,7 @@ import { z } from 'zod';
import {
type GitHub,
+ GitHubAuthError,
GitHubNotFoundError,
GitHubRateLimitError,
type GitHubRepoInfo,
@@ -12,6 +13,8 @@ import { redisService } from '@/server/services/redis';
import { SkillImportError } from './errors';
type GitHubProxy = MarketService['proxyOAuthRequest'];
+/** Resolves the caller's GitHub token from their Vault, or undefined when none is saved. */
+export type GitHubTokenResolver = () => Promise<string | undefined>;
const snapshotQuery = `query SkillArchive($owner: String!, $repo: String!, $ref: String!) {
repository(owner: $owner, name: $repo) {
@@ -33,28 +36,62 @@ const envelopeSchema = z.object({
const connectorRequired = () =>
new SkillImportError(
- 'Check the repository URL. For a private repository, connect GitHub in Settings → Connectors and retry.',
+ 'Check the repository URL. For a private repository, connect GitHub in Settings → Connectors, or add a GitHub token (GITHUB_TOKEN) to your Vault, and retry.',
'CONNECT_GITHUB',
);
const unavailable = () =>
new SkillImportError(
- 'Check the repository URL and branch, and confirm your GitHub connector can read the repository.',
+ 'Check the repository URL and branch, and confirm your GitHub connector or the GitHub token (GITHUB_TOKEN) in your Vault can read the repository.',
'GITHUB_ACCESS',
);
/** Request-scoped. Only anonymous ref lookups may enter the shared Redis cache. */
export class GitHubSkillRepository {
private archiveUrls = new Map<string, string>();
+ private token?: Promise<string | undefined>;
constructor(
private readonly github: GitHub,
private readonly proxy?: GitHubProxy,
+ private readonly vaultToken?: GitHubTokenResolver,
) {}
private key(info: GitHubRepoInfo, commit: string) {
return JSON.stringify([info.owner, info.repo, commit]);
}
+ /** Read once per request; a token GitHub rejects is dropped for the rest of it. */
+ private vaultGitHubToken() {
+ if (!this.vaultToken) return Promise.resolve(undefined);
+ this.token ??= this.vaultToken().catch(() => undefined);
+ return this.token;
+ }
+
+ /**
+ * The anonymous request could not read the repository. Try the Vault token
+ * before the connector; undefined means the token is missing or cannot read it.
+ */
+ private async withVaultToken<T>(
+ cause: unknown,
+ run: (token: string) => Promise<T>,
+ ): Promise<T | undefined> {
+ if (!(cause instanceof GitHubNotFoundError || cause instanceof GitHubRateLimitError)) return;
+ if (cause instanceof GitHubNotFoundError && cause.status === 422) return;
+ const token = await this.vaultGitHubToken();
+ if (!token) return;
+ try {
+ return await run(token);
+ } catch (error) {
+ if (error instanceof GitHubAuthError) {
+ this.token = Promise.resolve(undefined);
+ return;
+ }
+ // The token cannot read it either; the connector may still.
+ if (error instanceof GitHubNotFoundError || error instanceof GitHubRateLimitError) return;
+ throw error;
+ }
+ }
+
private async connectedSnapshot(info: GitHubRepoInfo, ref: string, cause: unknown) {
if (
!this.proxy ||
@@ -100,6 +137,11 @@ export class GitHubSkillRepository {
if (!cached) await redisService.gitHubRefs.record(info, commit);
return { commit, public: true };
} catch (error) {
+ const commit = await this.withVaultToken(error, (token) =>
+ this.github.resolveCommit(info, token),
+ );
+ // Private to this caller: never enters the shared ref or package caches.
+ if (commit) return { commit, public: false };
const snapshot = await this.connectedSnapshot(info, info.branch, error).catch((failure) => {
// Preserve the anonymous ref-archive fallback when the public API is
// rate limited and the connector cannot supply a snapshot.
@@ -116,6 +158,10 @@ export class GitHubSkillRepository {
try {
return await this.github.downloadCommitZip(info, commit);
} catch (error) {
+ const archive = await this.withVaultToken(error, (token) =>
+ this.github.downloadTokenZip(info, commit, token),
+ );
+ if (archive) return archive;
const snapshot = await this.connectedSnapshot(info, commit, error);
if (snapshot.oid !== commit)
throw new SkillImportError('GitHub returned a different commit', 'DOWNLOAD_FAILED');
diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.ts
index 820b3946e21..b8b78c4e824 100644
--- a/apps/server/src/services/skill/importer.ts
+++ b/apps/server/src/services/skill/importer.ts
@@ -35,7 +35,7 @@ import { redisService } from '@/server/services/redis';
import { SkillImportError, SkillManifestError, SkillParseError } from './errors';
import { readGitHubArchive } from './githubArchive';
-import { GitHubSkillRepository } from './githubRepository';
+import { GitHubSkillRepository, type GitHubTokenResolver } from './githubRepository';
import {
checkGitHubRows,
installedFingerprint,
@@ -87,14 +87,23 @@ export class SkillImporter {
db: LobeChatDatabase,
userId: string,
workspaceId?: string,
- options?: { githubProxy?: MarketService['proxyOAuthRequest']; workspaceRole?: string },
+ options?: {
+ githubProxy?: MarketService['proxyOAuthRequest'];
+ /** The caller's GitHub token from their Vault, tried before the connector. */
+ githubToken?: GitHubTokenResolver;
+ workspaceRole?: string;
+ },
) {
this.skillModel = new AgentSkillModel(db, userId, workspaceId);
this.parser = new SkillParser();
this.resourceService = new SkillResourceService(db, userId, workspaceId);
this.fileService = new FileService(db, userId, workspaceId);
this.github = new GitHub({ userAgent: 'LobeHub-Skill-Importer' });
- this.repository = new GitHubSkillRepository(this.github, options?.githubProxy);
+ this.repository = new GitHubSkillRepository(
+ this.github,
+ options?.githubProxy,
+ options?.githubToken,
+ );
this.userId = userId;
this.workspaceId = workspaceId;
this.workspaceRole = options?.workspaceRole;
diff --git a/apps/server/src/services/skill/vaultGitHubToken.test.ts b/apps/server/src/services/skill/vaultGitHubToken.test.ts
new file mode 100644
index 00000000000..1b7bebe5057
--- /dev/null
+++ b/apps/server/src/services/skill/vaultGitHubToken.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+import type { UserCredSummary } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ findGitHubToken,
+ resolveVaultGitHubToken,
+ type VaultCredsReader,
+ workspaceOwned,
+} from './vaultGitHubToken';
+
+const cred = (id: number, patch: Partial<UserCredSummary>): UserCredSummary => ({
+ createdAt: '',
+ id,
+ key: `key-${id}`,
+ name: `Cred ${id}`,
+ type: 'kv-env',
+ updatedAt: '',
+ ...patch,
+});
+
+const reader = (
+ creds: UserCredSummary[],
+ plaintext: Record<number, Record<string, string>>,
+): VaultCredsReader & { get: ReturnType<typeof vi.fn> } => ({
+ get: vi.fn(async (id: number) => ({ plaintext: plaintext[id] })),
+ list: async () => ({ data: creds }),
+});
+
+describe('findGitHubToken', () => {
+ it('prefers the credential keyed github and reads GITHUB_TOKEN from it', async () => {
+ const vault = reader([cred(1, { name: 'GitHub work' }), cred(2, { key: 'github' })], {
+ 1: { GITHUB_TOKEN: 'ghp_other' },
+ 2: { OTHER: 'x', GITHUB_TOKEN: ' ghp_main ' },
+ });
+ expect(await findGitHubToken(vault)).toBe('ghp_main');
+ expect(vault.get).toHaveBeenCalledWith(2, { decrypt: true });
+ });
+
+ it('accepts GH_TOKEN, a single value of a GitHub-named credential, or a GitHub-prefixed value', async () => {
+ expect(await findGitHubToken(reader([cred(1, { key: 'gh' })], { 1: { GH_TOKEN: 't1' } }))).toBe(
+ 't1',
+ );
+ expect(
+ await findGitHubToken(reader([cred(1, { name: 'My GitHub' })], { 1: { TOKEN: 't2' } })),
+ ).toBe('t2');
+ expect(
+ await findGitHubToken(
+ reader([cred(1, { maskedPreview: 'github_pat_****abcd' })], { 1: { PAT: 'github_pat_x' } }),
+ ),
+ ).toBe('github_pat_x');
+ });
+
+ it('never decrypts unrelated, OAuth or file credentials', async () => {
+ const vault = reader(
+ [
+ cred(1, { key: 'openai', maskedPreview: 'sk-****' }),
+ cred(2, { key: 'github', type: 'oauth' }),
+ cred(3, { key: 'github-key', type: 'file' }),
+ ],
+ {},
+ );
+ expect(await findGitHubToken(vault)).toBeUndefined();
+ expect(vault.get).not.toHaveBeenCalled();
+ });
+
+ it('skips a credential that cannot be decrypted', async () => {
+ const vault = reader([cred(1, { key: 'github' }), cred(2, { name: 'github 2' })], {
+ 2: { GITHUB_TOKEN: 'ghp_2' },
+ });
+ vault.get.mockRejectedValueOnce(new Error('forbidden'));
+ expect(await findGitHubToken(vault)).toBe('ghp_2');
+ });
+});
+
+describe('resolveVaultGitHubToken', () => {
+ it('reads personal credentials before workspace ones and survives a failing Vault', async () => {
+ const broken: VaultCredsReader = {
+ get: vi.fn(),
+ list: vi.fn().mockRejectedValue(new Error('market down')),
+ };
+ const personal = reader([cred(1, { key: 'github' })], { 1: { GITHUB_TOKEN: 'ghp_me' } });
+ expect(await resolveVaultGitHubToken([broken, personal])).toBe('ghp_me');
+ });
+
+ it('uses only workspace-owned credentials that are not private', async () => {
+ const org = reader(
+ [
+ cred(1, { key: 'github', ownerType: 'user' }),
+ cred(2, { key: 'github', ownerType: 'organization', visibility: 'private' }),
+ cred(3, { key: 'github', ownerType: 'organization', visibility: 'public' }),
+ ],
+ { 1: { GITHUB_TOKEN: 'a' }, 2: { GITHUB_TOKEN: 'b' }, 3: { GITHUB_TOKEN: 'c' } },
+ );
+ expect(await resolveVaultGitHubToken([workspaceOwned(org)])).toBe('c');
+ });
+});
diff --git a/apps/server/src/services/skill/vaultGitHubToken.ts b/apps/server/src/services/skill/vaultGitHubToken.ts
new file mode 100644
index 00000000000..2dcbc98066d
--- /dev/null
+++ b/apps/server/src/services/skill/vaultGitHubToken.ts
@@ -0,0 +1,98 @@
+import type { CredWithPlaintext, UserCredSummary } from '@lobechat/types';
+import debug from 'debug';
+
+const log = debug('lobe-chat:service:skill-vault-github-token');
+
+/** Value names read as a GitHub token, in order of preference. */
+export const GITHUB_TOKEN_NAMES = ['GITHUB_TOKEN', 'GH_TOKEN', 'GITHUB_PAT', 'GITHUB_ACCESS_TOKEN'];
+
+/** Prefixes GitHub gives its tokens (classic, fine-grained, OAuth, app user, app server). */
+const GITHUB_TOKEN_PREFIX = /^(?:ghp_|github_pat_|gho_|ghu_|ghs_)/;
+
+/** At most this many credentials are decrypted while looking for the token. */
+const MAX_DECRYPTS = 5;
+
+export interface VaultCredsReader {
+ get: (id: number, options: { decrypt: boolean }) => Promise<Partial<CredWithPlaintext>>;
+ list: () => Promise<{ data?: UserCredSummary[] }>;
+}
+
+const namesGitHub = (cred: UserCredSummary) =>
+ /github/i.test(cred.key) || /github/i.test(cred.name) || /^gh(?:[-_]?token)?$/i.test(cred.key);
+
+/**
+ * Rank a KV credential as a GitHub token holder: key `github` first, then a key
+ * or name mentioning GitHub, then any whose masked value has a GitHub prefix.
+ */
+const rank = (cred: UserCredSummary) => {
+ if (cred.type !== 'kv-env' && cred.type !== 'kv-header') return 0;
+ if (cred.key.toLowerCase() === 'github') return 3;
+ if (namesGitHub(cred)) return 2;
+ if (cred.maskedPreview && GITHUB_TOKEN_PREFIX.test(cred.maskedPreview)) return 1;
+ return 0;
+};
+
+/** The token in a decrypted credential, by value name, else its only value. */
+export const tokenFrom = (cred: UserCredSummary, plaintext?: Record<string, string>) => {
+ if (!plaintext) return;
+ const entries = Object.entries(plaintext);
+ const byName = new Map(entries.map(([name, value]) => [name.toUpperCase(), value?.trim()]));
+ for (const name of GITHUB_TOKEN_NAMES) {
+ const value = byName.get(name);
+ if (value) return value;
+ }
+ if (entries.length !== 1) return;
+ const value = entries[0][1]?.trim();
+ if (value && (GITHUB_TOKEN_PREFIX.test(value) || namesGitHub(cred))) return value;
+};
+
+/** The first GitHub token found among a Vault's KV credentials. */
+export const findGitHubToken = async (reader: VaultCredsReader) => {
+ const { data = [] } = await reader.list();
+ const candidates = data
+ .map((cred) => ({ cred, rank: rank(cred) }))
+ .filter(({ rank }) => rank > 0)
+ .sort((a, b) => b.rank - a.rank)
+ .slice(0, MAX_DECRYPTS);
+ for (const { cred } of candidates) {
+ try {
+ const { plaintext } = await reader.get(cred.id, { decrypt: true });
+ const token = tokenFrom(cred, plaintext);
+ if (token) {
+ log('using Vault credential key=%s', cred.key);
+ return token;
+ }
+ } catch (error) {
+ log('could not read Vault credential key=%s: %s', cred.key, (error as Error).message);
+ }
+ }
+};
+
+/**
+ * The caller's GitHub token from their Vault: personal credentials first, then
+ * (in a workspace) the workspace's own credentials that are not kept private.
+ * A Vault that cannot be read is treated as holding no token.
+ */
+export const resolveVaultGitHubToken = async (readers: VaultCredsReader[]) => {
+ for (const reader of readers) {
+ try {
+ const token = await findGitHubToken(reader);
+ if (token) return token;
+ } catch (error) {
+ log('could not list Vault credentials: %s', (error as Error).message);
+ }
+ }
+};
+
+/** Keep only credentials a workspace owns and shares with every member. */
+export const workspaceOwned = (reader: VaultCredsReader): VaultCredsReader => ({
+ get: (id, options) => reader.get(id, options),
+ list: async () => {
+ const { data = [] } = await reader.list();
+ return {
+ data: data.filter(
+ (cred) => cred.ownerType === 'organization' && cred.visibility !== 'private',
+ ),
+ };
+ },
+});