openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,393 lines • 51.6 kB
JavaScript
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { c as isSecretRef, l as isValidEnvSecretRefId } from "./ref-contract-b8L-9DrQ.mjs";
import { f as normalizeResolvedSecretInputString } from "./types.secrets-BmNLLnHp.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs";
import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { f as resolveAgentWorkspaceDir, o as resolveAgentEntry } from "./agent-scope-config-DmXgFGKP.mjs";
import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Un as record, qn as strictObject, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { a as captureExternalSessionCommitGuard, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { n as isManagedGitHubProfileId } from "./github-identity-profile-id-C9wvLmtG.mjs";
import { i as writeHiddenGitHubSecretRecord, n as listHiddenGitHubSecretRecords, r as readHiddenGitHubSecretRecord, t as deleteHiddenGitHubSecretRecord } from "./secret-store-hidden-github-qvQ-BJHF.mjs";
import { n as createOAuthRefreshResponseError, t as createOAuthRefreshError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs";
import { a as resolveConfiguredGitHubHost, i as resolveConfiguredGitHubApiBaseUrl, n as GITHUB_PUBLIC_HOST, o as withGitHubToken, t as CLEARED_GITHUB_CREDENTIALS } from "./github-host-CjR25cOO.mjs";
import "./http-body-B9w7rzPz.mjs";
import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs";
import { t as createStaleWhileRevalidateCache } from "./stale-while-revalidate-cache-BRZEfv_f.mjs";
import { n as resolveGitHubHost, t as resolveGitHubApiBaseUrl } from "./github-host-runtime-CMm44VF1.mjs";
import { c as readGitAuthor, i as createGitHubReadIdentity, l as readNativeGitHubToken, n as GitHubIdentityError, o as normalizeGitHubToken, r as clearNativeGitHubTokenCache, s as readCachedNativeGitHubToken, t as GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES, u as startGitHubIdentityOperation } from "./github-read-identity-DyhbpOtm.mjs";
import { i as githubOAuthScopes, n as githubOAuthProfileId, o as githubOAuthTimestamp, r as githubOAuthRefreshFields, s as validGitHubDeviceTiming, t as githubOAuthDeviceFields } from "./github-oauth-values-B750ECKI.mjs";
import { t as AGENT_GIT_CONFIG_PARAMETERS } from "./git-maintenance-env-l0LyckfF.mjs";
import path from "node:path";
import { createHash, createPrivateKey, createSign, randomBytes } from "node:crypto";
import fs from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { root } from "@openclaw/fs-safe/root";
import { readSecretFile } from "@openclaw/fs-safe/secret";
import { parseDocument, stringify } from "yaml";
//#region src/agents/github-oauth-client.ts
const GITHUB_OAUTH_CLIENT_ID = "Ov23liUjOXHi28w2fDlH";
const GITHUB_OAUTH_DEVICE_CODE_URL = "https://github.com/login/device/code";
const GITHUB_OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
const GITHUB_OAUTH_VERIFICATION_URL = "https://github.com/login/device";
const GITHUB_OAUTH_SCOPE = "repo workflow read:org gist offline_access";
const GITHUB_OAUTH_REQUEST_TIMEOUT_MS = 3e4;
const GITHUB_OAUTH_RESPONSE_MAX_BYTES = 16384;
const GITHUB_OAUTH_STRING_MAX_CHARS = 2048;
const GITHUB_OAUTH_SCOPE_MAX_CHARS = 4096;
const GITHUB_OAUTH_SCOPE_MAX_COUNT = 32;
const GITHUB_OAUTH_SCOPE_MAX_LENGTH = 64;
const GITHUB_OAUTH_MAX_DURATION_SECONDS = 31622400;
const GITHUB_OAUTH_MAX_INTERVAL_SECONDS = 3600;
const verifiedCredentials = createStaleWhileRevalidateCache({
maxEntries: 32,
ttlMs: 6e4,
cacheable: (e) => e.status === "available"
});
function clearGitHubCredentialVerificationCache() {
clearNativeGitHubTokenCache();
verifiedCredentials.clear();
}
const GITHUB_OAUTH_ERROR_CODE_SET = /* @__PURE__ */ new Set([
"authorization_pending",
"slow_down",
"expired_token",
"unsupported_grant_type",
"incorrect_client_credentials",
"incorrect_device_code",
"bad_verification_code",
"access_denied",
"device_flow_disabled",
"unverified_user_email",
"bad_refresh_token"
]);
function githubOAuthProtocolError(e) {
return /* @__PURE__ */ new Error(`GitHub OAuth ${e} response was invalid`);
}
function readBoundedString(e, t, n = GITHUB_OAUTH_STRING_MAX_CHARS) {
if (typeof e !== "string" || e.length === 0 || e.length > n || e.trim() !== e) throw githubOAuthProtocolError(t);
return e;
}
function readPositiveInteger(e, t, n) {
if (typeof e !== "number" || !Number.isSafeInteger(e) || e <= 0 || e > n) throw githubOAuthProtocolError(t);
return e;
}
function normalizeGitHubScopes(e, t) {
if (typeof e !== "string" || e.length > GITHUB_OAUTH_SCOPE_MAX_CHARS) throw githubOAuthProtocolError(t);
const n = e.split(/[\s,]+/u).filter(Boolean).map((e) => {
if (e.length > GITHUB_OAUTH_SCOPE_MAX_LENGTH || !/^[a-z0-9:_-]+$/u.test(e)) throw githubOAuthProtocolError(t);
return e;
});
const r = [...new Set(n)].toSorted();
if (r.length > GITHUB_OAUTH_SCOPE_MAX_COUNT) throw githubOAuthProtocolError(t);
return r;
}
function parseGitHubOAuthTokenPair(e, t) {
if (e.token_type !== "bearer") throw githubOAuthProtocolError(t);
const n = normalizeGitHubScopes(e.scope, t);
if (![
"repo",
"workflow",
"read:org",
"gist"
].every((e) => n.includes(e))) throw githubOAuthProtocolError(t);
const r = readBoundedString(e.access_token, t);
const i = readBoundedString(e.refresh_token, t);
registerSecretValueForRedaction(r);
registerSecretValueForRedaction(i);
return {
accessToken: r,
tokenType: "bearer",
scopes: n,
expiresInSeconds: readPositiveInteger(e.expires_in, t, GITHUB_OAUTH_MAX_DURATION_SECONDS),
refreshToken: i,
refreshTokenExpiresInSeconds: readPositiveInteger(e.refresh_token_expires_in, t, GITHUB_OAUTH_MAX_DURATION_SECONDS)
};
}
function isGitHubOAuthErrorCode(e) {
return typeof e === "string" && GITHUB_OAUTH_ERROR_CODE_SET.has(e);
}
function parseGitHubOAuthError(e, t) {
const n = e.error;
if (!isGitHubOAuthErrorCode(n)) throw githubOAuthProtocolError(t);
const r = e.interval === void 0 ? void 0 : readPositiveInteger(e.interval, t, GITHUB_OAUTH_MAX_INTERVAL_SECONDS);
return {
code: n,
...r !== void 0 ? { intervalSeconds: r } : {}
};
}
function parseJsonObject(e, t) {
let n;
try {
n = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(e));
} catch {
throw githubOAuthProtocolError(t);
}
const r = asOptionalRecord(n);
if (!r) throw githubOAuthProtocolError(t);
return r;
}
async function postGitHubOAuthForm(e, t, n, r) {
const i = resolveTimerTimeoutMs(r.timeoutMs, GITHUB_OAUTH_REQUEST_TIMEOUT_MS, 1);
const a = AbortSignal.timeout(i);
const o = r.signal ? AbortSignal.any([r.signal, a]) : a;
let s = false;
let c = false;
try {
await r.assertCurrent?.();
o.throwIfAborted();
s = true;
const a = await fetch(e, {
method: "POST",
redirect: "error",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: t,
signal: o
});
c = true;
return {
response: a,
body: await readGitHubResponse(a, n, i)
};
} catch (e) {
if (n !== "token refresh") throw e;
throw createOAuthRefreshError("GitHub OAuth token refresh failed", s ? {
version: 1,
phase: c ? "after-token-response" : "token-response",
outcome: "unknown"
} : {
version: 1,
phase: "before-dispatch",
outcome: "not-attempted",
recovery: {
kind: "later",
evidence: "dispatch-not-started"
}
});
}
}
async function readGitHubResponse(e, t, n) {
return parseJsonObject(await readResponseWithLimit(e, GITHUB_OAUTH_RESPONSE_MAX_BYTES, {
chunkTimeoutMs: n,
timeoutMs: n,
onOverflow: () => githubOAuthProtocolError(t),
onIdleTimeout: () => githubOAuthProtocolError(t),
onTimeout: () => githubOAuthProtocolError(t)
}), t);
}
/** Public credentials use their fixed issuer; other issuers require an explicit endpoint. */
async function verifyGitHubCredential(e, t = {}) {
registerSecretValueForRedaction(e);
try {
readBoundedString(e, "account");
if (/\s/u.test(e)) return { status: "unavailable" };
const n = t.apiBaseUrl ?? resolveConfiguredGitHubApiBaseUrl();
const r = createHash("sha256").update(`${n}\0${e}`).digest("hex");
const create = async () => {
const r = resolveTimerTimeoutMs(t.timeoutMs, GITHUB_OAUTH_REQUEST_TIMEOUT_MS, 1);
const i = AbortSignal.timeout(r);
const a = await fetch(`${n}/user`, {
method: "GET",
redirect: "error",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${e}`
},
signal: t.signal ? AbortSignal.any([t.signal, i]) : i
});
if (a.status !== 200) {
a.body?.cancel().catch(() => void 0);
const e = a.status === 429 || a.status === 403 && (a.headers.get("x-ratelimit-remaining") === "0" || a.headers.has("retry-after"));
return { status: a.status === 401 ? "unavailable" : e ? "rate_limited" : "unverified" };
}
const o = await readGitHubResponse(a, "account", r);
const s = readPositiveInteger(o.id, "account", Number.MAX_SAFE_INTEGER);
const c = readBoundedString(o.login, "account", 100);
const l = o.avatar_url == null ? null : readBoundedString(o.avatar_url, "account");
const u = normalizeGitHubScopes(a.headers.get("x-oauth-scopes") ?? "", "account");
const d = {
status: "available",
account: {
accountId: s,
login: c,
avatarUrl: l
},
scopes: u
};
Object.freeze(d.account);
Object.freeze(d.scopes);
Object.freeze(d);
return d;
};
if (t.signal || t.timeoutMs !== void 0) return await create();
const { value: i, stale: a } = await verifiedCredentials.read(r, create, { allowStale: t.allowStale === true });
return a && i.status === "available" ? {
...i,
stale: true
} : i;
} catch {
return { status: "unverified" };
}
}
function throwGitHubOAuthHttpError(e, t) {
throw new Error(`GitHub OAuth ${t} request failed (HTTP ${e.status})`);
}
async function exchangeGitHubOAuthToken(e, t, n) {
const { response: r, body: i } = await postGitHubOAuthForm(GITHUB_OAUTH_ACCESS_TOKEN_URL, new URLSearchParams({
client_id: GITHUB_OAUTH_CLIENT_ID,
...e
}), t, n);
if (t === "token refresh" && (!r.ok || i.error !== void 0)) {
const e = createOAuthRefreshResponseError("GitHub OAuth token refresh", r.status, i);
if (i.access_token !== void 0 || !isGitHubOAuthErrorCode(i.error)) throw e;
return { error: {
...parseGitHubOAuthError(i, t),
failure: e
} };
}
if (i.error !== void 0 && i.access_token !== void 0) throw githubOAuthProtocolError(t);
if (i.error !== void 0) return { error: parseGitHubOAuthError(i, t) };
if (!r.ok) throwGitHubOAuthHttpError(r, t);
try {
return { tokens: parseGitHubOAuthTokenPair(i, t) };
} catch (e) {
if (t !== "token refresh") throw e;
throw createOAuthRefreshError("GitHub OAuth token refresh response was invalid", {
version: 1,
phase: "after-token-response",
outcome: "unknown"
});
}
}
async function requestGitHubOAuthDeviceCode(e = {}) {
const { response: t, body: n } = await postGitHubOAuthForm(GITHUB_OAUTH_DEVICE_CODE_URL, new URLSearchParams({
client_id: GITHUB_OAUTH_CLIENT_ID,
scope: GITHUB_OAUTH_SCOPE
}), "device authorization", e);
if (!t.ok) throwGitHubOAuthHttpError(t, "device authorization");
const r = readBoundedString(n.device_code, "device authorization");
const i = readBoundedString(n.user_code, "device authorization", 64);
if (!/^[A-Za-z0-9_-]{40}$/u.test(r) || !/^[A-Z0-9]{4}-[A-Z0-9]{4}$/u.test(i)) throw githubOAuthProtocolError("device authorization");
if (n.verification_uri !== GITHUB_OAUTH_VERIFICATION_URL) throw githubOAuthProtocolError("device authorization");
return {
deviceCode: r,
userCode: i,
verificationUri: GITHUB_OAUTH_VERIFICATION_URL,
expiresInSeconds: readPositiveInteger(n.expires_in, "device authorization", GITHUB_OAUTH_MAX_DURATION_SECONDS),
intervalSeconds: readPositiveInteger(n.interval, "device authorization", GITHUB_OAUTH_MAX_INTERVAL_SECONDS)
};
}
async function pollGitHubOAuthDeviceToken(e) {
const t = readBoundedString(e.deviceCode, "device token");
if (!/^[A-Za-z0-9_-]{40}$/u.test(t)) throw githubOAuthProtocolError("device token");
const n = await exchangeGitHubOAuthToken({
device_code: t,
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
}, "device token", e);
if (n.error) {
const { code: e, intervalSeconds: t } = n.error;
switch (e) {
case "authorization_pending":
case "expired_token":
case "access_denied": return { status: e };
case "slow_down": return {
status: e,
...t !== void 0 ? { intervalSeconds: t } : {}
};
default: return {
status: "error",
code: e
};
}
}
return {
status: "authorized",
tokens: n.tokens
};
}
async function refreshGitHubOAuthToken(e) {
const t = await exchangeGitHubOAuthToken({
grant_type: "refresh_token",
refresh_token: readBoundedString(e.refreshToken, "token refresh")
}, "token refresh", e);
if (t.error) return {
status: "error",
code: t.error.code,
failure: t.error.failure
};
return {
status: "refreshed",
tokens: t.tokens
};
}
//#endregion
//#region src/agents/github-oauth-records.ts
const OAUTH_RECORD_PREFIX = "github-oauth-";
const OPAQUE_ID_PATTERN = /^[a-f0-9]{32}$/u;
const DEVICE_REQUEST_ID_PATTERN = /^github-device-[a-f0-9]{32}$/u;
const requestIdSchema = string().regex(DEVICE_REQUEST_ID_PATTERN);
const scope = _enum(["system", "agent"]);
const agentId = string().min(1).max(128).refine((e) => normalizeAgentId(e) === e);
const authorValue = string().refine((e) => e.trim().length > 0);
function strictRecord(e) {
return unknown().refine((e) => e === null || typeof e !== "object" || !Object.hasOwn(e, "__proto__")).pipe(strictObject(e));
}
const identityConfig = strictRecord({
profileId: githubOAuthProfileId,
kind: literal("oauth").optional(),
allowInSandbox: boolean().optional(),
gitAuthor: strictRecord({
name: authorValue.optional(),
email: authorValue.optional()
}).refine((e) => Object.keys(e).length > 0).optional()
}).nullable();
const authorizationFields = {
agentId,
scope,
expectedIdentity: identityConfig,
agentLifecycleBinding: strictRecord({
agentId,
provenance: strictRecord({
agentId,
createdVia: _enum([
"operator",
"agent",
"template"
]),
creatorAgentId: agentId.nullable(),
createdAtMs: githubOAuthTimestamp
}).nullable()
}).refine((e) => e.provenance === null || e.provenance.agentId === e.agentId).optional().catch(void 0)
};
function validAgentBinding(e) {
return e.scope === "agent" ? e.agentLifecycleBinding?.agentId === e.agentId : e.agentLifecycleBinding === void 0;
}
function omitMissingAgentBinding(e) {
if (e.agentLifecycleBinding === void 0) delete e.agentLifecycleBinding;
return e;
}
const deviceRecordSchema = strictRecord({
version: literal(1),
requestId: requestIdSchema,
...githubOAuthDeviceFields,
...authorizationFields
}).refine(validAgentBinding).refine(validGitHubDeviceTiming).transform(omitMissingAgentBinding);
const pendingInitialSchema = strictRecord({
requestId: requestIdSchema,
scope,
agentId,
expectedIdentity: identityConfig,
agentLifecycleBinding: authorizationFields.agentLifecycleBinding
}).refine(validAgentBinding).transform(omitMissingAgentBinding);
const oauthRecordSchema = strictRecord({
version: literal(1),
profileId: githubOAuthProfileId,
agentId,
scope,
...githubOAuthRefreshFields,
scopes: githubOAuthScopes.refine((e) => {
const t = [...new Set(e)].toSorted((e, t) => e.localeCompare(t));
return t.length === e.length && t.every((t, n) => t === e[n]);
}),
createdAtMs: githubOAuthTimestamp,
pendingInitial: pendingInitialSchema.optional(),
pendingRefresh: literal(true).optional(),
refreshClaim: string().uuid().optional(),
refreshFailure: _enum(["expired", "failed"]).optional()
}).refine((e) => e.accessExpiresAtMs > e.createdAtMs && e.refreshExpiresAtMs > e.accessExpiresAtMs && (!e.pendingInitial || e.pendingInitial.scope === e.scope && e.pendingInitial.agentId === e.agentId) && !(e.pendingInitial && e.pendingRefresh) && !(e.pendingRefresh && e.refreshFailure));
function createGitHubOAuthRecord(e) {
return {
version: 1,
profileId: e.profileId,
scope: e.scope,
agentId: e.agentId,
accountId: e.account.accountId,
login: e.account.login,
refreshToken: e.tokens.refreshToken,
accessExpiresAtMs: e.now + e.tokens.expiresInSeconds * 1e3,
refreshExpiresAtMs: e.now + e.tokens.refreshTokenExpiresInSeconds * 1e3,
scopes: e.tokens.scopes,
createdAtMs: e.now,
...e.pendingInitial ? { pendingInitial: e.pendingInitial } : {}
};
}
function githubDeviceRecordName(e) {
if (!DEVICE_REQUEST_ID_PATTERN.test(e)) throw new Error("GitHub device authorization request id is invalid.");
return e;
}
function githubOAuthRecordName(e) {
if (!isManagedGitHubProfileId(e)) throw new Error("Managed GitHub profile id is invalid.");
return `${OAUTH_RECORD_PREFIX}${e.slice(4)}`;
}
function parseGitHubOAuthProfileId(e) {
const t = e.startsWith(OAUTH_RECORD_PREFIX) ? e.slice(13) : "";
return OPAQUE_ID_PATTERN.test(t) ? `ghp_${t}` : void 0;
}
function parseGitHubRecord(e, t) {
let n;
try {
n = JSON.parse(e);
} catch {
return;
}
const r = t.safeParse(n);
return r.success ? r.data : void 0;
}
async function writeGitHubDeviceAuthorizationRecord(e) {
const t = parseGitHubRecord(JSON.stringify(e), deviceRecordSchema);
if (!t || t.requestId !== e.requestId) throw new Error("GitHub device authorization record is invalid.");
await writeHiddenGitHubSecretRecord({
name: githubDeviceRecordName(e.requestId),
value: JSON.stringify(t)
});
}
async function readGitHubDeviceAuthorizationRecord(e) {
return parseGitHubDeviceAuthorizationRecord(await readHiddenGitHubSecretRecord({ name: githubDeviceRecordName(e) }), e);
}
function parseGitHubDeviceAuthorizationRecord(e, t) {
const n = e === void 0 ? void 0 : parseGitHubRecord(e, deviceRecordSchema);
return n?.requestId === t ? n : void 0;
}
async function deleteGitHubDeviceAuthorizationRecord(e) {
await deleteHiddenGitHubSecretRecord({ name: githubDeviceRecordName(e) });
}
async function listGitHubDeviceAuthorizationRecords() {
return parseDeviceRecords(await listHiddenGitHubSecretRecords({ prefix: "github-device" }));
}
function parseDeviceRecords(e) {
return e.flatMap(({ name: e, value: t }) => {
if (!DEVICE_REQUEST_ID_PATTERN.test(e)) return [];
return [{
requestId: e,
record: parseGitHubDeviceAuthorizationRecord(t, e)
}];
});
}
async function writeGitHubOAuthRecord(e, t) {
const n = parseGitHubOAuthRecord(JSON.stringify(e), e.profileId);
if (!n || n.profileId !== e.profileId) throw new Error("GitHub OAuth record is invalid.");
await writeHiddenGitHubSecretRecord({
name: githubOAuthRecordName(e.profileId),
value: JSON.stringify(n),
...t ? { expectedValue: JSON.stringify(oauthRecordSchema.parse(t)) } : {}
});
}
function parseGitHubOAuthRecord(e, t) {
const n = e === void 0 ? void 0 : parseGitHubRecord(e, oauthRecordSchema);
return n?.profileId === t ? n : void 0;
}
async function inspectGitHubOAuthRecord(e) {
const t = await readHiddenGitHubSecretRecord({ name: githubOAuthRecordName(e) });
if (t === void 0) return { state: "missing" };
const n = parseGitHubOAuthRecord(t, e);
return n ? {
state: "valid",
record: n
} : { state: "invalid" };
}
async function deleteGitHubOAuthRecord(e) {
await deleteHiddenGitHubSecretRecord({ name: githubOAuthRecordName(e) });
}
async function listGitHubOAuthRecords() {
return parseOAuthRecords(await listHiddenGitHubSecretRecords({ prefix: "github-oauth" }));
}
function parseOAuthRecords(e) {
return e.flatMap(({ name: e, value: t }) => {
const n = parseGitHubOAuthProfileId(e);
return n ? [{
profileId: n,
record: parseGitHubOAuthRecord(t, n)
}] : [];
});
}
async function listGitHubAuthorizationRecords() {
const e = await listHiddenGitHubSecretRecords({});
return {
deviceRecords: parseDeviceRecords(e),
oauthRecords: parseOAuthRecords(e)
};
}
//#endregion
//#region src/agents/github-app-identity.ts
const id = number().int().positive().max(Number.MAX_SAFE_INTEGER);
const permissions = record(string(), _enum([
"read",
"write",
"admin"
]));
const repositorySchema = object({
id,
full_name: string().max(256)
});
const appSchema = object({
id,
slug: string().regex(/^[A-Za-z0-9-]{1,39}$/u),
permissions
});
const installationSchema = object({
id,
app_id: id,
account: object({ id }),
suspended_at: string().nullable(),
permissions
});
const tokenSchema = object({
token: string().min(1).max(2048).regex(/^[^\s\p{Cc}]+$/u),
expires_at: string().datetime({ offset: true }),
permissions
});
const botSchema = object({
id,
login: string(),
type: literal("Bot"),
avatar_url: string().nullable()
});
const repositoriesSchema = object({
total_count: id,
repositories: array(repositorySchema).max(100)
});
const installationMetadata = /* @__PURE__ */ new WeakMap();
/** Display consumers reuse verified issuer facts without retaining or minting an execution token. */
function readGitHubAppInstallationMetadata(e, t, n) {
const r = installationMetadata.get(e);
return r && r.host === t && r.apiBaseUrl === n && r.value.verifiedUntil > Date.now() && isDeepStrictEqual(e, r.snapshot) ? r.value : void 0;
}
function failure() {
return new GitHubIdentityError("unverified");
}
function permits(e, t) {
const n = {
read: 1,
write: 2,
admin: 3
};
return Object.entries(t).every(([t, r]) => (n[e[t] ?? ""] ?? 0) >= (n[r] ?? 0));
}
function jwt(e, t) {
const n = Math.floor(Date.now() / 1e3);
const encode = (e) => Buffer.from(JSON.stringify(e)).toString("base64url");
const r = `${encode({
alg: "RS256",
typ: "JWT"
})}.${encode({
iss: String(e),
iat: n - 60,
exp: n + 540
})}`;
const i = createPrivateKey(t);
if (i.asymmetricKeyType !== "rsa") throw failure();
const a = createSign("RSA-SHA256");
a.update(r);
a.end();
return `${r}.${a.sign(i).toString("base64url")}`;
}
async function prepareAppGitHubIdentity(e, t, n, r, i, a) {
if (!e.allowAppInstallation) throw new GitHubIdentityError("unavailable");
const o = structuredClone(t);
const assertCurrent = () => {
e.assertCurrent?.();
if (resolveGitHubHost() !== i || resolveGitHubApiBaseUrl() !== a || !isDeepStrictEqual(t, o)) throw new GitHubIdentityError("changed");
};
assertCurrent();
let s = t;
const c = e.requestedRepository?.toLowerCase();
if (c !== void 0) {
const e = t.app.repositories.find((e) => e.fullName.toLowerCase() === c);
if (!e) throw new GitHubIdentityError("unavailable");
s = {
...t,
app: {
...t.app,
repositories: [e]
}
};
}
if (process.env.FACTORY_AUTH_MODE === "github") {
if (!e.readNativeCredential) throw new GitHubIdentityError("unavailable");
await e.readNativeCredential(r, {
kind: "repository-admission",
host: i,
selection: s
});
assertCurrent();
}
const l = assertCurrent;
/** A caller-admitted subset; the original selection still owns display metadata and currency. */
const u = s.app.repositories;
/** Each execution retains its own bounded installation token and revocation owner. */
const prepareInstallation = async () => {
const e = structuredClone(t);
let n = false;
let r;
const assertInstallationCurrent = () => {
l();
if (n || !isDeepStrictEqual(t, e)) throw new GitHubIdentityError("changed");
};
const o = assertInstallationCurrent;
const s = Date.now();
const issueInstallation = async () => {
const n = u ?? t.app.repositories;
const r = {
metadata: "read",
...t.app.permissions
};
const assertIssuanceCurrent = () => {
o();
if (!isDeepStrictEqual(t, e)) throw new GitHubIdentityError("changed");
};
const c = normalizeResolvedSecretInputString({
value: t.app.privateKey,
path: "tools.github.app.privateKey"
});
if (!c) throw new GitHubIdentityError("unavailable");
registerSecretValueForRedaction(c);
let l;
const d = AbortSignal.timeout(1e4);
const request = async (e, t, n, r) => {
assertIssuanceCurrent();
const i = await fetch(`${a}${e}`, {
method: r === void 0 ? "GET" : "POST",
redirect: "error",
signal: d,
headers: {
authorization: `Bearer ${t}`,
accept: "application/vnd.github+json",
"content-type": "application/json",
"x-github-api-version": "2022-11-28"
},
...r === void 0 ? {} : { body: JSON.stringify(r) }
});
if (!i.ok) {
i.body?.cancel().catch(() => {});
throw failure();
}
const o = await readResponseWithLimit(i, 262144, { signal: d });
const s = JSON.parse(o.toString("utf8"));
if (r !== void 0) {
const e = object({ token: tokenSchema.shape.token }).safeParse(s);
if (e.success) {
l = e.data.token;
registerSecretValueForRedaction(l);
}
}
assertIssuanceCurrent();
const c = n.safeParse(s);
if (!c.success) throw failure();
return c.data;
};
try {
const o = jwt(t.app.appId, c);
registerSecretValueForRedaction(o);
const u = await request("/app", o, appSchema);
if (u.id !== t.app.appId || !permits(u.permissions, r)) throw failure();
const d = await request(`/app/installations/${t.app.installationId}`, o, installationSchema);
if (d.id !== t.app.installationId || d.app_id !== u.id || d.account.id !== t.app.accountId || d.suspended_at !== null || !permits(d.permissions, r)) throw failure();
const f = `${u.slug}[bot]`;
const p = await request(`/app/installations/${d.id}/access_tokens`, o, tokenSchema, {
repository_ids: n.map((e) => e.id),
permissions: r
});
l = p.token;
registerSecretValueForRedaction(l);
const m = Date.parse(p.expires_at);
if (m <= Date.now() || m > Date.now() + 39e5 || !isDeepStrictEqual(p.permissions, r)) throw failure();
const h = await request(`/users/${encodeURIComponent(f)}`, p.token, botSchema);
if (h.login !== f) throw failure();
const g = await request("/installation/repositories?per_page=100", p.token, repositoriesSchema);
if (g.total_count !== n.length || g.repositories.length !== g.total_count || !n.every((e) => g.repositories.some((t) => t.id === e.id && t.full_name.toLowerCase() === e.fullName.toLowerCase()))) throw failure();
assertIssuanceCurrent();
const _ = {
token: p.token,
expiresAtMs: m,
verifiedUntil: Math.min(s + 3e5, m),
account: {
accountId: h.id,
login: h.login,
avatarUrl: h.avatar_url
},
facts: {
appId: u.id,
installationId: d.id,
accountId: d.account.id,
repositories: e.app.repositories.filter((e) => n.some((t) => t.id === e.id)),
permissions: r,
suspended: false
}
};
installationMetadata.set(t, {
snapshot: e,
host: i,
apiBaseUrl: a,
value: {
account: _.account,
expiresAtMs: m,
verifiedUntil: _.verifiedUntil
}
});
return { value: _ };
} catch (e) {
if (l) await fetch(`${a}/installation/token`, {
method: "DELETE",
redirect: "error",
signal: AbortSignal.timeout(5e3),
headers: { authorization: `Bearer ${l}` }
}).then((e) => {
e.body?.cancel().catch(() => {});
}, () => {});
assertIssuanceCurrent();
throw e instanceof GitHubIdentityError ? e : failure();
}
};
const c = await issueInstallation();
const revoke = () => {
n = true;
r ??= fetch(`${a}/installation/token`, {
method: "DELETE",
redirect: "error",
signal: AbortSignal.timeout(5e3),
headers: { authorization: `Bearer ${c.value.token}` }
}).then(async (e) => {
await e.body?.cancel().catch(() => {});
if (!e.ok && e.status !== 401 && c.value.expiresAtMs > Date.now()) throw new Error("GitHub App token revocation failed");
});
return r;
};
const readToken = async () => {
assertInstallationCurrent();
if (c.value.expiresAtMs <= Date.now()) throw new GitHubIdentityError("changed");
return c.value.token;
};
try {
await readToken();
} catch (e) {
await revoke().catch(() => {});
throw e;
}
return {
...c.value,
readToken,
revoke
};
};
const d = await prepareInstallation();
try {
assertCurrent();
return {
prepared: Object.freeze({
source: n,
profileId: t.profileId,
host: i,
account: d.account,
accessExpiresAtMs: d.expiresAtMs,
revoke: d.revoke
}),
token: d.token,
readToken: d.readToken,
stale: void 0
};
} catch (e) {
await d.revoke().catch(() => {});
throw e;
}
}
function configuredAppGitHubIdentityFacts(e, t) {
const n = readGitHubAppInstallationMetadata(e, resolveGitHubHost(), resolveGitHubApiBaseUrl());
return {
source: t,
credentialKind: "app-installation",
credentialState: n ? "available" : "configured_unavailable",
account: n ? { login: n.account.login } : null,
gitAuthor: {
name: e.gitAuthor?.name ?? null,
email: e.gitAuthor?.email ?? null
},
evidence: n ? "github-api" : "none",
accessExpiresAtMs: n?.expiresAtMs ?? null,
refreshState: "not_applicable",
oauthScopes: [],
repositoryGrants: "unknown"
};
}
function configuredAppGitHubOptionsIdentity(e, t) {
const n = readGitHubAppInstallationMetadata(e, resolveGitHubHost(), resolveGitHubApiBaseUrl());
if (!n) throw new GitHubIdentityError("unavailable");
return {
source: t,
account: n.account,
stale: void 0
};
}
//#endregion
//#region src/agents/github-tool-account.ts
function managedGitHubHosts(e) {
return stringify({ [resolveConfiguredGitHubHost()]: {
user: e.login,
oauth_token: e.token,
users: { [e.login]: { oauth_token: e.token } }
} });
}
//#endregion
//#region src/agents/github-tool-identity-env.ts
function managedGitHubIdentityEnvironment(e) {
const t = e.gitAuthor;
const n = [...e.gitConfig ?? [], ...Object.entries({
...t?.name ? { "user.name": t.name } : {},
...t?.email ? { "user.email": t.email } : {}
})];
const r = Object.fromEntries(n.flatMap(([e, t], n) => [[`GIT_CONFIG_KEY_${n}`, e], [`GIT_CONFIG_VALUE_${n}`, t]]));
return {
GH_CONFIG_DIR: e.profileDir,
GH_HOST: e.host ?? "github.com",
...n.length > 0 ? {
GIT_CONFIG_COUNT: String(n.length),
...r
} : {},
...t?.name ? {
GIT_AUTHOR_NAME: t.name,
GIT_COMMITTER_NAME: t.name
} : {},
...t?.email ? {
GIT_AUTHOR_EMAIL: t.email,
GIT_COMMITTER_EMAIL: t.email
} : {}
};
}
/** Signing keys and preview credentials never enter agent child processes. */
function githubCredentialEnvironmentExclusions(e, t) {
const n = e.sourceConfig ?? e.config;
const r = [n.gateway?.controlUi?.github?.token ?? e.config.gateway?.controlUi?.github?.token];
for (const e of [n.tools?.github, ...Object.values(n.agents?.entries ?? {}).map((e) => e.tools?.github)]) if (e?.kind === "app-installation") r.push(e.app.privateKey);
const i = t ? { ...CLEARED_GITHUB_CREDENTIALS } : {};
const a = [];
for (const e of r) {
if (!isSecretRef(e)) continue;
if (e.source === "env" && isValidEnvSecretRefId(e.id)) i[e.id] = "";
else if (e.source === "store") {
i[e.id] = "";
a.push(e.id);
}
}
return {
credentialScrubEnv: i,
excludedStoreNames: a
};
}
//#endregion
//#region src/agents/github-tool-identity-lifecycle.ts
const profileListeners = /* @__PURE__ */ new Set();
/** Execution copies follow completed writes by the profile owner. */
function onManagedGitHubProfileChanged(e) {
return registerListener(profileListeners, e);
}
function notifyManagedGitHubProfileChanged(e) {
notifyListeners(profileListeners, e);
}
/** Never attach a replacement record's expiry to a token read before its rotation. */
function resolveGitHubPublicationAccessExpiry(e, t, n) {
return e?.state === "valid" && t?.state === "valid" && !e.record.pendingRefresh && !e.record.pendingInitial && !t.record.pendingRefresh && !t.record.pendingInitial && e.record.refreshToken === t.record.refreshToken && t.record.accountId === n ? t.record.accessExpiresAtMs : void 0;
}
//#endregion
//#region src/agents/github-tool-profile-files.ts
/** Write gh's external file contract without touching its OS keyring or verifying again. */
async function writeManagedGitHubProfileFiles(e, t, n) {
if (process.platform === "win32") {
const t = path.dirname(e);
await fs.mkdir(t, {
recursive: true,
mode: 448
});
await (await root(t)).mkdir(path.basename(e), {
private: true,
assertBeforeMutation: n?.assertCurrent
});
} else {
await fs.mkdir(e, {
recursive: true,
mode: 448
});
await fs.chmod(e, 448);
}
const r = await root(e, {
mode: 384,
mkdir: false,
durable: false
});
await r.write("config.yml", stringify({ version: "1" }));
await r.write("hosts.yml", managedGitHubHosts(t), { assertBeforeMutation: n?.assertCurrent });
notifyManagedGitHubProfileChanged({
profileDir: e,
kind: "updated"
});
}
//#endregion
//#region src/agents/github-tool-profile-path.ts
const MANAGED_GITHUB_ROOT_SEGMENTS = ["credentials", "github"];
function resolveManagedGitHubProfileDir(e) {
if (!isManagedGitHubProfileId(e.profileId)) throw new Error("Managed GitHub profile id is invalid.");
const t = resolveManagedGitHubProfileRoot(e);
return path.join(t, e.profileId);
}
function resolveManagedGitHubProfileRoot(e) {
const t = path.join(resolveStateDir(e.env), ...MANAGED_GITHUB_ROOT_SEGMENTS);
return e.scope === "agent" ? path.join(t, "agents", resolveManagedGitHubAgentKey(e.agentId)) : path.join(t, e.scope);
}
function resolveManagedGitHubAgentKey(e) {
return createHash("sha256").update(normalizeAgentId(e), "utf8").digest("hex");
}
//#endregion
//#region src/agents/github-tool-identity.ts
const GITHUB_HOST = "github.com";
var GitHubAccountMismatchError = class extends Error {};
function createManagedGitHubProfileId() {
return `ghp_${randomBytes(16).toString("hex")}`;
}
function resolveConfiguredGitHubToolIdentity(e) {
return e.scope === "agent" ? resolveAgentEntry(e.config, e.agentId)?.tools?.github : e.config.tools?.github;
}
function resolveSystemGitHubToolIdentity(e) {
return resolveScopedGitHubToolIdentity({
...e,
agentId: "",
scope: "system"
}) ?? { source: "system-detected" };
}
function resolveGitHubToolIdentity(e) {
return resolveScopedGitHubToolIdentity({
...e,
scope: "agent"
}) ?? resolveSystemGitHubToolIdentity(e);
}
function resolveScopedGitHubToolIdentity(e) {
const t = resolveConfiguredGitHubToolIdentity(e);
return t ? {
source: e.scope === "agent" ? "agent-override" : "system-configured",
config: t
} : void 0;
}
function resolveSelectedGitHubProfileDir(e, t) {
return resolveManagedGitHubProfileDir({
agentId: e.agentId,
env: e.env,
scope: t.source === "agent-override" ? "agent" : "system",
profileId: t.config.profileId
});
}
/** Prepares the non-secret child overlay and store exclusions once per agent run. */
function prepareGitHubToolEnvironment(e) {
const t = resolveGitHubToolIdentity(e);
if (t.source !== "system-detected" && t.config.kind === "app-installation") throw new Error("GitHub Apps support session reads only; select native or OAuth to run tools.");
return prepareGitHubToolEnvironmentForIdentity(e, t);
}
function prepareGitHubToolEnvironmentForIdentity(e, t) {
const n = t.source !== "system-detected";
const { credentialScrubEnv: r, excludedStoreNames: i } = githubCredentialEnvironmentExclusions(e, t.source === "system-detected" ? void 0 : t.config);
return Object.freeze({
credentialScrubEnv: Object.freeze(r),
localIdentityEnv: Object.freeze(n ? managedGitHubIdentityEnvironment({
profileDir: resolveSelectedGitHubProfileDir(e, t),
gitAuthor: t.config.gitAuthor
}) : {}),
localGitConfigParameters: AGENT_GIT_CONFIG_PARAMETERS,
excludedStoreNames: Object.freeze(i),
managedLocalIdentity: n,
...n ? { hostExecutionRequired: true } : {}
});
}
function githubIdentityProbeEnvironment(e, t) {
const n = prepareGitHubToolEnvironmentForIdentity(e, t);
return {
...e.env ?? process.env,
...Object.fromEntries(Object.keys(n.credentialScrubEnv).map((e) => [e, void 0])),
...n.localIdentityEnv
};
}
async function readManagedGitHubToken(e) {
if (!await isPrivateManagedGitHubProfile(e)) return;
try {
let t;
for (const n of ["hosts.yml", "config.yml"]) {
const r = path.join(e, n);
const i = await fs.lstat(r).catch((e) => {
if (n === "config.yml" && hasErrnoCode(e, "ENOENT")) return;
throw e;
});
if (!i) continue;
if (process.platform !== "win32" && (i.mode & 63) !== 0) return;
const a = await readSecretFile(r, "Managed GitHub profile", {
maxBytes: GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES,
rejectSymlink: true
});
const o = parseDocument(a, { prettyErrors: false });
if (o.errors.length || o.warnings.length) return;
const s = o.toJS({ maxAliasCount: 0 });
if (!isRecord(s)) return;
if (n === "hosts.yml") t = s;
}
const n = t?.[GITHUB_HOST];
return isRecord(n) && typeof n.oauth_token === "string" ? normalizeGitHubToken(n.oauth_token) : void 0;
} catch {
return;
}
}
async function isPrivateManagedGitHubProfile(e) {
try {
const [t, n] = await Promise.all([fs.lstat(e), fs.lstat(path.join(e, "hosts.yml"))]);
if (!t.isDirectory() || t.isSymbolicLink() || !n.isFile() || n.isSymbolicLink()) return false;
return process.platform === "win32" || (t.mode & 63) === 0 && (n.mode & 63) === 0;
} catch {
return false;
}
}
async function resolveGitHubToolIdentityStatus(e) {
const t = resolveGitHubToolIdentity(e);
const n = e.selectedScope === "system" ? resolveSystemGitHubToolIdentity(e) : resolveScopedGitHubToolIdentity({
...e,
scope: "agent"
});
const r = {
config: e.config,
sourceConfig: e.sourceConfig,
cwd: resolveAgentWorkspaceDir(e.config, e.agentId),
agentId: e.agentId,
env: e.env
};
const i = await resolveGitHubIdentityFacts({
...r,
identity: t
});
const a = n?.source === t.source && (n?.source === "system-detected" || t.source !== "system-detected" && n?.config.profileId === t.config.profileId);
const o = !n ? null : a ? i : await resolveGitHubIdentityFacts({
...r,
identity: n
});
return {
agentId: e.agentId,
selectedScope: e.selectedScope,
selected: {
scope: e.selectedScope,
configured: n?.source !== "system-detected" && n !== void 0,
identity: o
},
effective: i
};
}
async function resolveSystemGitHubIdentityStatus(e) {
return resolveGitHubIdentityFacts({
...e,
agentId: "",
identity: resolveSystemGitHubToolIdentity(e),
cwd: resolveStateDir(e.env)
});
}
async function resolveGitHubIdentityFacts(e) {
const t = e.identity;
const n = t.source !== "system-detected";
if (n && t.config.kind === "app-installation") return configuredAppGitHubIdentityFacts(t.config, t.source);
const r = githubIdentityProbeEnvironment(e, t);
const i = resolveGitHubHost();
const a = resolveGitHubApiBaseUrl();
const o = n ? await readManagedGitHubToken(resolveSelectedGitHubProfileDir(e, t)) : await readNativeGitHubToken(r, false, i);
const [s, c] = await Promise.all([o ? verifyGitHubCredential(o, {
...n ? {} : { apiBaseUrl: a },
allowStale: true
}) : void 0, readGitAuthor(r, e.cwd)]);
const l = s?.status === "available" ? s.account : null;
const u = s?.status === "unavailable" || !s ? n ? "configured_unavailable" : "unavailable" : s.status;
const d = n && t.config.kind === "oauth" ? await inspectGitHubOAuthRecord(t.config.profileId) : { state: "missing" };
const f = d.state === "valid" ? d.record : void 0;
const p = !n || t.config.kind !== "oauth" ? "not_applicable" : d.state !== "valid" ? "unavailable" : d.record.pendingRefresh ? "refreshing" : d.record.refreshFailure ?? (d.record.refreshExpiresAtMs <= Date.now() ? "expired" : "available");
return {
source: t.source,
...s?.status === "available" && s.stale ? { stale: true } : {},
credentialKind: !n ? "native" : t.config.kind === "oauth" ? "managed-oauth" : "managed-pat",
credentialState: u,
account: l ? { login: l.login } : null,
gitAuthor: c,
evidence: l ? "github-api" : s?.status === "rate_limited" ? "rate-limited" : s ? "unverified" : "none",
accessExpiresAtMs: f?.accessExpiresAtMs ?? null,
refreshState: p,
oauthScopes: [...f?.scopes ?? []],
repositoryGrants: "unknown"
};
}
/** Only publication needs a credential-bearing child environment; display verifies the account. */
async function preparePersonalGitHubPublicationIdentity(e) {
const { profileId: t, accountId: n, assertCurrent: r } = e;
r();
const i = resolveGitHubHost();
const a = resolveGitHubApiBaseUrl();
const assertSelected = () => {
r();
if (resolveGitHubHost() !== i || resolveGitHubApiBaseUrl() !== a) throw new GitHubIdentityError("changed");
};
const o = resolveManagedGitHubProfileDir({
agentId: "",
scope: "personal",
profileId: t
});
const s = await readManagedGitHubToken(o);
if (!s) throw new Error("My GitHub profile is unavailable; reconnect My GitHub.");
assertSelected();
const c = e.forDisplay ? void 0 : withGitHubToken(process.env, s);
if (c) Object.assign(c, {
GH_CONFIG_DIR: o,
GH_PROMPT_DISABLED: "1"
});
const l = await verifyGitHubCredential(s, { allowStale: e.forDisplay });
assertSelected();
if (l.status !== "available") throw new Error("My GitHub credential could not be verified; reconnect My GitHub.");
if (l.account.accountId !== n) throw new GitHubAccountMismatchError("My GitHub account changed; reconnect My GitHub.");
return Object.freeze({
source: "personal",
...l.stale ? { stale: true } : {},
profileId: t,
host: GITHUB_HOST,
account: l.account,
...c ? { env: Object.freeze(c) } : {}
});
}
/** Confirms the current config still selects the prepared publication profile. */
function matchesPreparedGitHubPublicationIdentity(e) {
const t = resolveGitHubToolIdentity(e);
return t.source === e.identity.source && (e.identity.host ?? resolveGitHubHost()) === resolveGitHubHost() && (t.source === "system-detected" || t.config.profileId === e.identity.profileId);
}
async function prepareSharedGitHubIdentity(e, t, n = readNativeGitHubToken, r = resolveGitHubHost(), i = resolveGitHubApiBaseUrl()) {
const a = t.source !== "system-detected";
if (a && t.config.kind === "app-installation") return await prepareAppGitHubIdentity(e, t.config, t.source, githubIdentityProbeEnvironment(e, t), r, i);
const currentEnvironment = () => ({
...githubIdentityProbeEnvironment(e, t),
GH_PROMPT_DISABLED: "1"
});
if (a && (r !== GITHUB_HOST || i !== resolveConfiguredGitHubApiBaseUrl())) {
const e = new GitHubIdentityError("unavailable");
e.message = "Use a credential issued by the repository's GitHub host; managed profiles are issued by github.com.";
throw e;
}
const o = a ? resolveSelectedGitHubProfileDir(e, t) : void 0;
const readToken = () => o !== void 0 ? readManagedGitHubToken(o) : e.readNativeCredential ? e.readNativeCredential(currentEnvironment()) : n(currentEnvironment(), e.allowAnonymous === true, r);
const s = await startGitHubIdentityOperation(readToken, e);
if (!s) return startGitHubIdentityOperation(() => {
if (!a && e.allowAnonymous) return {
prepared: void 0,
token: void 0,
readToken,
stale: void 0
};
throw new GitHubIdentityError("unavailable");
}, e);
const c = await startGitHubIdentityOperation(() => verifyGitHubCredential(s, {
apiBaseUrl: i,
allowStale: e.allowStale
}), e);
return startGitHubIdentityOperation(() => {
if (c.status !== "available") throw new GitHubIdentityError(c.status);
return {
prepared: {
source: t.source,
...a ? { profileId: t.config.profileId } : {},
host: r,
account: c.account
},
token: s,
readToken,
...c.stale ? { stale: true } : {}
};
}, e);
}
/** Publication owns a fixed credential snapshot for its already-admitted operation. */
async function prepareGitHubPublicationIdentity(e) {
const t = resolveGitHubToolIdentity(e);
const n = {
...githubIdentityProbeEnvironment(e, t),
GH_PROMPT_DISABLED: "1"
};
const readOAuth = () => t.source !== "system-detected" && t.config.kind === "oauth" ? inspectGitHubOAuthRecord(t.config.profileId) : void 0;
const r = resolveGitHubHost();
const i = resolveGitHubApiBaseUrl();
const a = await startGitHubIdentityOperation(readOAuth, e);
const { prepared: o, token: s } = await prepareSharedGitHubIdentity(e, t, void 0, r, i);
if (!o || s === void 0) throw new GitHubIdentityError("unavailable");
const c = await startGitHubIdentityOperation(readOAuth, e);
e.assertCurrent?.();
const l = resolveGitHubPublicationAccessExpiry(a, c, o.account.accountId);
return Object.freeze({
...o,
...l !== void 0 ? { accessExpiresAtMs: l } : {},
env: Object.freeze(withGitHubToken(n, s))
});
}
/** Options expose account facts only; publication obtains its own live credential. */
async function prepareGitHubPublicationOptionsIdentity(e) {
const t = resolveGitHubToolIdentity(e);
if (t.source !== "system-detected" && t.config.kind === "app-installation") {
e.assertCurrent?.();
return configuredAppGitHubOptionsIdentity(t.config, t.source);
}
let n = false;
const { prepared: r, stale: i } = await prepareSharedGitHubIdentity({
...e,
allowStale: true
}, t, (e, t, r) => readCachedNativeGitHubToken(e, t, r, { onStale: () => {
n = true;
} }));
if (!r) throw new GitHubIdentityError("unavailable");
return {
source: r.source,
account: r.account,
...i || n ? { stale: true } : {}
};
}
/** Read authority tracks current selection and token rotation, without exporting a child environment. */
async function prepareGitHubReadIdentity(e) {
const t = resolveGitHubToolIdentity(e);
const { profileId: n, kind: r } = t.source === "system-detected" ? {} : t.config;
const i = composeSessionSourceAssertion([captureExternalSessionCommitGuard(e.assertActive), () => {
const i = resolveGitHubToolIdentity({
config: e.getCurrentConfig(),
agentId: e.agentId
});
if (i.source !== t.source || i.source !== "system-detected" && (i.config.profileId !== n || i.config.kind !== r || r === "app-installation" && t.source !== "system-detected" && !isDeepStrictEqual(i.config, t.config))) throw new GitHubIdentityError("changed");
}]);
const a = {
assertCurrent: i,
startCurrent: e.startActive
};
await startGitHubIdentityOperation(e.refresh, a);
i();
const { token: o, readToken: s, prepared: c, stale: l } = await prepareSharedGitHubIdentity({
...e,
...a
}, t, readCachedNativeGitHubToken, e.issuer, e.issuer ? resolveConfiguredGitHubApiBaseUrl() : void 0);
try {
i();
} catch (e) {
await c?.revoke?.();
throw e;
}
return {
...createGitHubReadIdentity({
assertSelected: i,
startActive: e.startActive,
readToken: s,
...l ? { stale: l } : {},
...!c || o === void 0 ? {
token: void 0,
selection: { source: "anonymous" }
} : {
token: o,
selection: {
source: t.source,
...n ? { profileId: n } : {},
accountId: c.account.accountId
}
}
}),
...c?.revoke ? { revoke: c.revoke } : {}
};
}
async function removeManagedGitHubProfile(e) {
await fs.rm(e, {
recursive: true,
force: true
});
clearNativeGitHubTokenCache();
notifyManagedGitHubProfileChanged({
profileDir: e,
kind: "removed"
});
}
async function verifyManagedGitHubCredential(e) {
const t = normalizeGitHubToken(e);
const n = await verifyGitHubCredential(t);
if (n.status !== "available") throw new Error("GitHub could not verify the managed credential.");
const r = n.scopes;
if (r.length && (!r.includes("repo") || ![
"read:org",
"write:org",
"admin:org"
].some((e) => r.includes(e)))) throw new Error("GitHub credential is missing required repo or read:org scopes.");
return {
account: n.account,
credential: t
};
}
/** Verifies a rotated token, then atomically replaces credentials in one stable profile. */
async function refreshManagedGitHubProfile(e) {
if (!await isPrivateManagedGitHubProfile(e.profileDir)) throw new Error("The configured GitHub identity profile is unavailable.");
const { account: t, credential: n } = await verifyManagedGitHubCredential(e.token);
e.assertCurrent?.();
if (t.accountId !== e.expectedAccountId) throw new GitHubAccountMismatchError("GitHub OAuth refresh returned a different account.");
const r = path.join(e.profileDir, "hosts.yml");
const i = await fs.lstat(r);
if (!i.isFile() || i.isSymbolicLink()) throw new Error("The configured GitHub identity profile is unavailable.");
const a = await root(e.profileDir);
await e.prepareEffect?.();
e.assertCurrent?.();
await a.write("hosts.yml", managedGitHubHosts({
login: t.login,
token: n
}), {
mode: 384,
mkdir: false,
durable: false,
mutationSymlinks: "reject",
assertBeforeMutation: e.assertCurrent
});
clearNativeGitHubTokenCache();
e.assertCurrent?.();
notifyManagedGitHubProfileChanged({
profileDir: e.profileDir,
kind: "updated"
});
return t;
}
/** Publishes a new inactive profile and switches config without retiring in-use generations. */
async function installManagedGitHubProfile(e) {
const t = path.dirname(e.profileDir);
await fs.mkdir(t, {
recursive: true,
mode: 448
});
await fs.chmod(t, 448);
const n = await fs.mkdtemp(path.join(t, ".github-profile.staging-"));
const r = path.join(n, "profile");
let i = false;
let a = false;
try {
const { account: t, credential: n } = await verifyManagedGitHubCredential(e.token);
await writeManagedGitHubProfileFiles(r, {
login: t.login,
token: n
});
await e.prepareEffect?.();
e.assertCurrent?.();
await fs.rename(r, e.profileDir);
i = true;
await e.prepareEffect?.();
e.assertCurrent?.();
await e.commitConfig(t);
clearNativeGitHubTokenCache();
a = true;
return t;
} finally {
if (i && !a && !e.retainProfileOnCommitFailure) await fs.rm(e.profileDir, {
recursive: true,
force: true
});
await fs.rm(n, {
recursive: true,
force: true
});
}
}
//#endregion
export { parseGitHubDeviceAuthorizationRecord as A, deleteGitHubOAuthRecord as C, listGitHubAuthorizationRecords as D, inspectGitHubOAuthRecord as E, clearGitHubCredentialVerificationCache as F, pollGitHubOAuthDeviceToken as I, refreshGitHubOAuthToken as L, readGitHubDeviceAuthorizationRecord as M, writeGitHubDeviceAuthorizationRecord as N, listGitHubDeviceAuthorizationRecords as O, writeGitHubOAuthRecord as P, requestGitHubOAuthDeviceCode as R, deleteGitHubDeviceAuthorizationRecord as S, githubOAuthRecordName as T, resolveManagedGitHubProfileRoot as _, prepareGitHubPublicationIdentity as a, managedGitHubIdentityEnvironment as b, prepareGitHubToolEnvironment as c, removeManagedGitHubProfile as d, resolveConfiguredGitHubToolIdentity as f, resolveManagedGitHubProfileDir as g, resolveManagedGitHubAgentKey as h, matchesPreparedGitHubPublicationIdentity as i, parseGitHubOAuthRecord as j, listGitHubOAuthRecords as k, preparePersonalGitHubPublicationIdentity as l, resolveSystemGitHubIdentityStatus as m, createManagedGitHubProfileId as n, prepareGitHubPublicationOptionsIdentity as o, resolveGitHubToolIdentityStatus as p, installManagedGitHubProfile as r, prepareGitHubReadIdentity as s, GitHubAccountMismatchError as t, refreshManagedGitHubProfile as u, writeManagedGitHubProfileFiles as v, githubDeviceRecordName as w, createGitHubOAuthRecord as x, onManagedGitHubProfileChanged as y };