mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The GitHub chat channel lets an agent review pull requests and answer comments through a GitHub App > - Each GitHub call gets a repository-scoped installation token from `githubBotRepositoryToken` > - That function minted a new token on every call. To mint, it resolved every App secret through the secret service, and each resolution wrote one audit row > - The review-check head poll calls it about every 5 minutes for each waiting check. On staging this made the secret audit insert one of the busiest statements in the database > - This pull request keeps a minted token in memory until shortly before it expires, and checks the connection's current state on every call > - The benefit is far fewer database writes and reads, fewer GitHub token mints, and an audit log that records real secret use ## Linked Issues or Issue Description **What happened?** On paperclip.staging (commita18479bbba, measured at 19:05Z on 2026-11-14), `secret_access_events` got about 285 rows in 60 s. These were 44 resolutions each of the GitHub App connection's `credentials.appId`, `privateKey`, `installationId`, `webhookSecret`, `clientId` and `clientSecret` (+21 `slug`), with `consumer_type` `tool_connection` and actor `system`. That is about 4.7 audit inserts/s. The matching `secret_versions` and binding reads ran at about 3.6/s each in Neon. These were among the busiest statements on the database. **Expected behavior** A GitHub installation token is valid for one hour. Paperclip should reuse it and resolve the App secrets only when it mints a new token. **Steps to reproduce** 1. Connect a GitHub App chat endpoint and get pull request reviews into the `received` review-check state (staging had 84 `github_review_check` actions). 2. Let the review-check worker poll the pull request head (23 polls/min measured on staging). 3. Count `secret_access_events` rows per minute. Each poll adds one row per App secret and mints a new token at GitHub. **Paperclip version or commit** master ata18479bbba(the commit serving paperclip.staging at the time of measurement). **Where in the code** `githubBotRepositoryToken` in `server/src/services/chat-github-client.ts`. Callers: `chat-github-checks.ts` (review-check head poll), `chat-github-response-comments.ts` and `chat-github-reviews.ts`. ## What Changed - `githubBotRepositoryToken` keeps a minted token in a per-process, in-memory cache (at most 512 entries, least recently used first out). It never persists or logs tokens. - The cache uses the token until 5 minutes before GitHub's `expires_at` (capped at one hour). If GitHub does not give a usable expiry, the token is not kept. - The cache key holds the company, endpoint, repository id, the exact permission set, and an authority revision. The revision holds the connection id, the endpoint's runtime generation (pause, revoke and availability changes advance it), and for each mint credential its secret ref, version selector, secret status, current version, `updatedAt`, and binding. The installation id is a secret, so its secret ref and version identify it in the key. - Each call reads the current authority from the database in two narrow statements: one row from the endpoint and connection join (status, enabled, refs, runtime generation), and the three mint secrets with their bindings (status and version columns only, no secret values). The endpoint and connection status checks run on every call, as before. - If a status check fails, all cached tokens for that endpoint are dropped. A token cannot survive a revoke, pause, disable or credential change. - Secrets are resolved only when a token is minted, and only the three that minting uses (`appId`, `privateKey`, `installationId`). So the audit log gets three rows per mint instead of one row per App secret per call. - New `githubBotRepositoryClient` sends repository requests. If GitHub returns 401 for a cached token, it drops that token, mints a new one, and sends the request once more. A 401 for a newly minted token is not retried. The review-check, response-comment and review paths use this client. - The token policy stays in the GitHub chat client module (`rules/module-boundaries.mdc`). The callers only change how they get a request function. ## Verification - New test file `server/src/__tests__/github-repository-token-cache.test.ts` (embedded Postgres, real secret service, mocked GitHub fetch): - `mints once and resolves the App's secrets only when it mints`: red on master (second call minted `installation-token-2`), green now. It also checks that only the three mint secrets are audited. - `refreshes a token shortly before GitHub's expiry`: reused at +54 min, minted again at +56 min. - `never keeps a token GitHub issues for less than the safety margin` - `mints again after a credential rotation and uses the new credential`: rotates the installation id secret and checks that the new mint uses it. - `mints again after the connection's credential refs change` - `never serves a cached token across a pause, revoke or disabled connection`: includes a pause and resume with no call in between. - `mints a separate token for each repository` - `replaces a cached token GitHub rejects and retries the request once`: also checks that a 401 for a new token is not retried. - On master, 5 of the 8 tests fail. All 8 pass with this change. - Focused suites pass locally: every server test file that matches `github`, plus `chat-sdk-runtime.adapters`, `chat-provider-inventory`, `idle-completed-history` and `connection-management.integration` (41 of 42 files, 955 of 956 tests). The one failure, `github-connection-enrollment-work.test.ts`, also fails on unchanged master (`expected +0 to be 1`), so this change did not cause it. - `pnpm --filter @paperclipai/server typecheck` passes. - CI supplies the full typecheck, build and test coverage for the final revision. ## Risks - Low risk. A cached token is used only while the endpoint, connection and mint secrets are unchanged, and the status checks still read current database state on every call. - A GitHub-side revoke of a token (for example, an App uninstall) makes GitHub return 401. The client then mints again once. If the installation is gone, the mint fails as before. - The cache is per process. Each server process mints its own token, at most once per hour per repository and permission set. - Two concurrent first calls for the same key can both mint. This is the same as before and is rare. - No schema, migration or API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
505 lines
17 KiB
TypeScript
505 lines
17 KiB
TypeScript
import { createPrivateKey, createSign } from "node:crypto";
|
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
|
import {
|
|
chatEndpoints,
|
|
companySecretBindings,
|
|
companySecrets,
|
|
toolConnections,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { secretService } from "./secrets.js";
|
|
import { HttpError, conflict, forbidden, unprocessable } from "../errors.js";
|
|
import { githubPublicationRetry, githubProviderRetry, GITHUB_INLINE_RETRY_WINDOW_MS, GITHUB_INLINE_MAX_ATTEMPTS } from "./chat-channels/github/retry.js";
|
|
|
|
export function githubAppJwt(
|
|
appId: string,
|
|
privateKey: string,
|
|
now = new Date(),
|
|
): string {
|
|
const epoch = Math.floor(now.getTime() / 1000);
|
|
const encode = (value: unknown) =>
|
|
Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
const unsigned = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({ iat: epoch - 60, exp: epoch + 540, iss: appId })}`;
|
|
const signer = createSign("RSA-SHA256");
|
|
signer.update(unsigned);
|
|
signer.end();
|
|
return `${unsigned}.${signer.sign(createPrivateKey(privateKey)).toString("base64url")}`;
|
|
}
|
|
|
|
/** Fixed origin, no redirects, bounded responses, no credential-bearing errors. */
|
|
export async function githubBotRequest<T>(
|
|
fetchImpl: typeof fetch,
|
|
token: string | null,
|
|
path: string,
|
|
options: { method?: string; body?: unknown; accept?: string } = {},
|
|
): Promise<T> {
|
|
const deadline = Date.now() + GITHUB_INLINE_RETRY_WINDOW_MS;
|
|
const safeToRetry = (options.method ?? "GET") === "GET" ||
|
|
(options.method === "POST" && /^\/app\/installations\/[1-9][0-9]*\/access_tokens$/.test(path));
|
|
for (let attempt = 1; ; attempt++) {
|
|
try {
|
|
return await githubBotRequestOnce<T>(fetchImpl, token, path, options, Math.min(25_000, Math.max(1, deadline - Date.now())));
|
|
} catch (error) {
|
|
const retry = githubPublicationRetry(error, attempt);
|
|
const delay = Date.parse(retry.retryAt) - Date.now();
|
|
if (!safeToRetry || !retry.retryable || attempt >= GITHUB_INLINE_MAX_ATTEMPTS || Date.now() + delay >= deadline) throw error;
|
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
}
|
|
}
|
|
}
|
|
|
|
async function githubBotRequestOnce<T>(
|
|
fetchImpl: typeof fetch,
|
|
token: string | null,
|
|
path: string,
|
|
options: { method?: string; body?: unknown; accept?: string },
|
|
timeoutMs: number,
|
|
): Promise<T> {
|
|
if (
|
|
!path.startsWith("/") ||
|
|
path.startsWith("//") ||
|
|
path.includes("\\") ||
|
|
path.split("/").includes("..")
|
|
)
|
|
throw forbidden("Invalid GitHub operation path");
|
|
let response: Response;
|
|
try {
|
|
response = await fetchImpl(`https://api.github.com${path}`, {
|
|
method: options.method ?? "GET",
|
|
redirect: "error",
|
|
signal: AbortSignal.timeout(timeoutMs),
|
|
headers: {
|
|
accept: options.accept ?? "application/vnd.github+json",
|
|
"x-github-api-version": "2022-11-28",
|
|
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
...(options.body !== undefined
|
|
? { "content-type": "application/json" }
|
|
: {}),
|
|
},
|
|
...(options.body !== undefined
|
|
? { body: JSON.stringify(options.body) }
|
|
: {}),
|
|
});
|
|
} catch {
|
|
throw unprocessable(
|
|
"GitHub is temporarily unavailable. Retry this operation.",
|
|
{ code: "github_bot_temporarily_unavailable", retryable: true },
|
|
);
|
|
}
|
|
if (!response.ok) {
|
|
let secondaryRateLimit = false;
|
|
if (response.status === 403) {
|
|
const reader = response.body?.getReader();
|
|
try {
|
|
const chunks: Uint8Array[] = [];
|
|
let size = 0;
|
|
while (reader) {
|
|
const part = await reader.read();
|
|
if (part.done) break;
|
|
size += part.value.byteLength;
|
|
if (size > 8192) break;
|
|
chunks.push(part.value);
|
|
}
|
|
secondaryRateLimit = /secondary rate limit|rate limit exceeded|abuse detection/i.test(Buffer.concat(chunks).toString("utf8"));
|
|
} catch {
|
|
} finally {
|
|
await reader?.cancel().catch(() => {});
|
|
reader?.releaseLock();
|
|
}
|
|
}
|
|
await response.body?.cancel();
|
|
throw unprocessable(
|
|
`GitHub rejected this operation (HTTP ${response.status}).`,
|
|
githubProviderRetry(response, secondaryRateLimit),
|
|
);
|
|
}
|
|
if (response.status === 204) return undefined as T;
|
|
const reader = response.body?.getReader();
|
|
if (!reader) throw unprocessable("GitHub returned an empty response", { code: "github_bot_invalid_response", retryable: true });
|
|
const chunks: Uint8Array[] = [];
|
|
let size = 0;
|
|
try {
|
|
while (true) {
|
|
const part = await reader.read();
|
|
if (part.done) break;
|
|
size += part.value.byteLength;
|
|
if (size > 8 * 1024 * 1024)
|
|
throw unprocessable(
|
|
"GitHub response exceeds the review limit. Narrow the request or report incomplete coverage.",
|
|
);
|
|
chunks.push(part.value);
|
|
}
|
|
const body = Buffer.concat(chunks).toString("utf8");
|
|
try {
|
|
return (options.accept?.includes("diff") ? body : JSON.parse(body)) as T;
|
|
} catch {
|
|
throw unprocessable("GitHub returned an invalid response", { code: "github_bot_invalid_response", retryable: true });
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof Error && "status" in error) throw error;
|
|
throw unprocessable("GitHub response was interrupted. Retry this operation.", { code: "github_bot_temporarily_unavailable", retryable: true });
|
|
} finally {
|
|
await reader.cancel().catch(() => {});
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
|
|
/** Resolve only this endpoint's vaulted App. Never consult personal grants. */
|
|
export async function githubBotCredentials(
|
|
db: Db,
|
|
companyId: string,
|
|
endpointId: string,
|
|
) {
|
|
const [row] = await db
|
|
.select({ endpoint: chatEndpoints, connection: toolConnections })
|
|
.from(chatEndpoints)
|
|
.innerJoin(
|
|
toolConnections,
|
|
and(
|
|
eq(toolConnections.id, chatEndpoints.connectionId),
|
|
eq(toolConnections.companyId, companyId),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(chatEndpoints.companyId, companyId),
|
|
eq(chatEndpoints.id, endpointId),
|
|
eq(chatEndpoints.provider, "github"),
|
|
),
|
|
);
|
|
if (!row || ["archived", "revoked", "paused"].includes(row.endpoint.status))
|
|
throw conflict("GitHub bot connection is unavailable");
|
|
const secrets = secretService(db);
|
|
const credentials: Record<string, string> = {};
|
|
for (const key of [
|
|
"appId",
|
|
"privateKey",
|
|
"installationId",
|
|
"webhookSecret",
|
|
"clientId",
|
|
"clientSecret",
|
|
"identityCodeVerifier",
|
|
]) {
|
|
const ref = row.connection.credentialSecretRefs.find(
|
|
(r) => r.configPath === `credentials.${key}`,
|
|
);
|
|
if (!ref) continue;
|
|
credentials[key] = await secrets.resolveSecretValue(
|
|
companyId,
|
|
ref.secretId,
|
|
ref.versionSelector ?? "latest",
|
|
{
|
|
consumerType: "tool_connection",
|
|
consumerId: row.connection.id,
|
|
configPath: ref.configPath,
|
|
actorType: "system",
|
|
actorId: null,
|
|
},
|
|
);
|
|
}
|
|
if (!credentials.appId || !credentials.privateKey)
|
|
throw conflict("Connect the GitHub App before continuing");
|
|
return {
|
|
...row,
|
|
credentials,
|
|
appJwt: githubAppJwt(credentials.appId, credentials.privateKey),
|
|
};
|
|
}
|
|
|
|
const GITHUB_REPOSITORY_TOKEN_PERMISSIONS = {
|
|
contents: "read",
|
|
metadata: "read",
|
|
issues: "write",
|
|
pull_requests: "write",
|
|
checks: "write",
|
|
} as const;
|
|
/** Only these secrets are needed to mint; the App's other credentials are not read here. */
|
|
const GITHUB_MINT_CREDENTIALS = ["appId", "privateKey", "installationId"] as const;
|
|
const GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS = 5 * 60_000;
|
|
const GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS = 60 * 60_000;
|
|
const GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT = 512;
|
|
|
|
type CachedRepositoryToken = { token: string; endpointId: string; refreshAt: number };
|
|
type RepositoryToken = { token: string; key: string; cached: boolean };
|
|
|
|
// Per process and in memory only. Tokens are never persisted or logged.
|
|
const repositoryTokens = new Map<string, CachedRepositoryToken>();
|
|
|
|
function forgetEndpointRepositoryTokens(endpointId: string) {
|
|
for (const [key, entry] of repositoryTokens)
|
|
if (entry.endpointId === endpointId) repositoryTokens.delete(key);
|
|
}
|
|
|
|
function rememberRepositoryToken(key: string, entry: CachedRepositoryToken) {
|
|
repositoryTokens.delete(key);
|
|
if (repositoryTokens.size >= GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) {
|
|
const now = Date.now();
|
|
for (const [stale, cached] of repositoryTokens)
|
|
if (cached.refreshAt <= now) repositoryTokens.delete(stale);
|
|
}
|
|
// Map order is least recently used first.
|
|
for (const oldest of repositoryTokens.keys()) {
|
|
if (repositoryTokens.size < GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) break;
|
|
repositoryTokens.delete(oldest);
|
|
}
|
|
repositoryTokens.set(key, entry);
|
|
}
|
|
|
|
/**
|
|
* Current minting authority, read from the database on every call. The
|
|
* revision covers everything that changes what a token may do: the endpoint's
|
|
* runtime generation (bumped on pause, revoke and availability changes), the
|
|
* connection, and each mint credential's secret ref, selected version, state
|
|
* and binding. Any change makes every token cached under the old revision
|
|
* unreachable. Secret values are not read here.
|
|
*/
|
|
async function githubBotRepositoryAuthority(
|
|
db: Db,
|
|
companyId: string,
|
|
endpointId: string,
|
|
) {
|
|
const [row] = await db
|
|
.select({
|
|
endpointStatus: chatEndpoints.status,
|
|
runtimeGeneration: sql<unknown>`${chatEndpoints.setup}->'runtimeGeneration'`,
|
|
connectionId: toolConnections.id,
|
|
enabled: toolConnections.enabled,
|
|
connectionStatus: toolConnections.status,
|
|
refs: toolConnections.credentialSecretRefs,
|
|
})
|
|
.from(chatEndpoints)
|
|
.innerJoin(
|
|
toolConnections,
|
|
and(
|
|
eq(toolConnections.id, chatEndpoints.connectionId),
|
|
eq(toolConnections.companyId, companyId),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(chatEndpoints.companyId, companyId),
|
|
eq(chatEndpoints.id, endpointId),
|
|
eq(chatEndpoints.provider, "github"),
|
|
),
|
|
);
|
|
if (!row || ["archived", "revoked", "paused"].includes(row.endpointStatus))
|
|
throw conflict("GitHub bot connection is unavailable");
|
|
const [appId, privateKey, installationId] = GITHUB_MINT_CREDENTIALS.map(
|
|
(key) => row.refs.find((ref) => ref.configPath === `credentials.${key}`),
|
|
);
|
|
if (!appId || !privateKey)
|
|
throw conflict("Connect the GitHub App before continuing");
|
|
if (
|
|
!row.enabled ||
|
|
row.connectionStatus !== "active" ||
|
|
!["active", "verifying"].includes(row.endpointStatus)
|
|
)
|
|
throw conflict("GitHub bot connection is not active");
|
|
if (!installationId) throw conflict("Verify the GitHub App installation first");
|
|
const refs = [appId, privateKey, installationId];
|
|
const secrets = await db
|
|
.select({
|
|
id: companySecrets.id,
|
|
status: companySecrets.status,
|
|
latestVersion: companySecrets.latestVersion,
|
|
updatedAt: companySecrets.updatedAt,
|
|
bindingId: companySecretBindings.id,
|
|
bindingPath: companySecretBindings.configPath,
|
|
bindingSelector: companySecretBindings.versionSelector,
|
|
bindingUpdatedAt: companySecretBindings.updatedAt,
|
|
})
|
|
.from(companySecrets)
|
|
.leftJoin(
|
|
companySecretBindings,
|
|
and(
|
|
eq(companySecretBindings.secretId, companySecrets.id),
|
|
eq(companySecretBindings.companyId, companyId),
|
|
eq(companySecretBindings.targetType, "tool_connection"),
|
|
eq(companySecretBindings.targetId, row.connectionId),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(companySecrets.companyId, companyId),
|
|
inArray(companySecrets.id, [...new Set(refs.map((ref) => ref.secretId))]),
|
|
),
|
|
);
|
|
const revision = JSON.stringify([
|
|
row.connectionId,
|
|
row.runtimeGeneration ?? 0,
|
|
refs.map((ref) => {
|
|
const selector = ref.versionSelector ?? "latest";
|
|
const secret = secrets.find((candidate) => candidate.id === ref.secretId);
|
|
const binding = secrets.find(
|
|
(candidate) =>
|
|
candidate.id === ref.secretId && candidate.bindingPath === ref.configPath,
|
|
);
|
|
return [
|
|
ref.configPath,
|
|
ref.secretId,
|
|
selector,
|
|
secret
|
|
? [
|
|
secret.status,
|
|
selector === "latest" ? secret.latestVersion : selector,
|
|
secret.updatedAt.getTime(),
|
|
]
|
|
: null,
|
|
binding
|
|
? [binding.bindingId, binding.bindingSelector, binding.bindingUpdatedAt?.getTime()]
|
|
: null,
|
|
];
|
|
}),
|
|
]);
|
|
return { connectionId: row.connectionId, refs, revision };
|
|
}
|
|
|
|
async function githubBotRepositoryTokenFor(
|
|
db: Db,
|
|
companyId: string,
|
|
endpointId: string,
|
|
repositoryId: string,
|
|
fetchImpl: typeof fetch,
|
|
options: { refresh?: boolean } = {},
|
|
): Promise<RepositoryToken> {
|
|
let authority: Awaited<ReturnType<typeof githubBotRepositoryAuthority>>;
|
|
try {
|
|
authority = await githubBotRepositoryAuthority(db, companyId, endpointId);
|
|
} catch (error) {
|
|
// A connection that cannot mint must not keep its earlier tokens either.
|
|
forgetEndpointRepositoryTokens(endpointId);
|
|
throw error;
|
|
}
|
|
if (!/^[1-9][0-9]*$/.test(repositoryId) || !Number.isSafeInteger(Number(repositoryId)))
|
|
throw conflict("Verify the GitHub App installation first");
|
|
const key = JSON.stringify([
|
|
companyId,
|
|
endpointId,
|
|
repositoryId,
|
|
GITHUB_REPOSITORY_TOKEN_PERMISSIONS,
|
|
authority.revision,
|
|
]);
|
|
const cached = repositoryTokens.get(key);
|
|
if (cached && !options.refresh && cached.refreshAt > Date.now()) {
|
|
rememberRepositoryToken(key, cached);
|
|
return { token: cached.token, key, cached: true };
|
|
}
|
|
if (cached) repositoryTokens.delete(key);
|
|
// Resolve (and audit) the App's secrets only when a token is actually minted.
|
|
const secrets = secretService(db);
|
|
const values: string[] = [];
|
|
for (const ref of authority.refs)
|
|
values.push(
|
|
await secrets.resolveSecretValue(
|
|
companyId,
|
|
ref.secretId,
|
|
ref.versionSelector ?? "latest",
|
|
{
|
|
consumerType: "tool_connection",
|
|
consumerId: authority.connectionId,
|
|
configPath: ref.configPath,
|
|
actorType: "system",
|
|
actorId: null,
|
|
},
|
|
),
|
|
);
|
|
const [appId, privateKey, installationId] = values;
|
|
if (!appId || !privateKey)
|
|
throw conflict("Connect the GitHub App before continuing");
|
|
if (!installationId) throw conflict("Verify the GitHub App installation first");
|
|
const issued = await githubBotRequest<{ token?: string; expires_at?: string }>(
|
|
fetchImpl,
|
|
githubAppJwt(appId, privateKey),
|
|
`/app/installations/${encodeURIComponent(installationId)}/access_tokens`,
|
|
{
|
|
method: "POST",
|
|
body: {
|
|
repository_ids: [Number(repositoryId)],
|
|
permissions: GITHUB_REPOSITORY_TOKEN_PERMISSIONS,
|
|
},
|
|
},
|
|
);
|
|
if (!issued.token)
|
|
throw unprocessable("GitHub did not issue an installation token");
|
|
const now = Date.now();
|
|
const refreshAt =
|
|
Math.min(
|
|
Date.parse(issued.expires_at ?? ""),
|
|
now + GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS,
|
|
) - GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS;
|
|
// Without a usable expiry the token serves this call only.
|
|
if (Number.isFinite(refreshAt) && refreshAt > now)
|
|
rememberRepositoryToken(key, { token: issued.token, endpointId, refreshAt });
|
|
return { token: issued.token, key, cached: false };
|
|
}
|
|
|
|
/**
|
|
* Least-privilege short-lived token restricted to the single task repository.
|
|
* Reused until shortly before GitHub's expiry while the connection's current
|
|
* authority is unchanged.
|
|
*/
|
|
export async function githubBotRepositoryToken(
|
|
db: Db,
|
|
companyId: string,
|
|
endpointId: string,
|
|
repositoryId: string,
|
|
fetchImpl = fetch,
|
|
) {
|
|
return (
|
|
await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl)
|
|
).token;
|
|
}
|
|
|
|
export type GitHubBotRepositoryRequest = <T>(
|
|
path: string,
|
|
options?: Parameters<typeof githubBotRequest>[3],
|
|
) => Promise<T>;
|
|
|
|
function githubUnauthorized(error: unknown) {
|
|
return (
|
|
error instanceof HttpError &&
|
|
!!error.details &&
|
|
typeof error.details === "object" &&
|
|
(error.details as { providerStatus?: unknown }).providerStatus === 401
|
|
);
|
|
}
|
|
|
|
/**
|
|
* GitHub requests with a repository token. When GitHub rejects a cached token
|
|
* (401), that token is dropped and the request is sent once more with a newly
|
|
* minted one. GitHub did not act on the rejected request, so the retry is safe.
|
|
*/
|
|
export async function githubBotRepositoryClient(
|
|
db: Db,
|
|
companyId: string,
|
|
endpointId: string,
|
|
repositoryId: string,
|
|
fetchImpl = fetch,
|
|
): Promise<GitHubBotRepositoryRequest> {
|
|
let current = Promise.resolve(
|
|
await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl),
|
|
);
|
|
return async <T>(path: string, options?: Parameters<typeof githubBotRequest>[3]) => {
|
|
const used = current;
|
|
const issued = await used;
|
|
try {
|
|
return await githubBotRequest<T>(fetchImpl, issued.token, path, options);
|
|
} catch (error) {
|
|
if (!issued.cached || !githubUnauthorized(error)) throw error;
|
|
if (current === used) {
|
|
if (repositoryTokens.get(issued.key)?.token === issued.token)
|
|
repositoryTokens.delete(issued.key);
|
|
current = githubBotRepositoryTokenFor(
|
|
db,
|
|
companyId,
|
|
endpointId,
|
|
repositoryId,
|
|
fetchImpl,
|
|
{ refresh: true },
|
|
);
|
|
}
|
|
return githubBotRequest<T>(fetchImpl, (await current).token, path, options);
|
|
}
|
|
};
|
|
}
|