openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 7.46 kB
JavaScript
import{m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{o as registerSecretValueForRedaction}from"./secret-redaction-registry-DospXE4m.mjs";import{i as resolveEnvironmentValue,n as mergeProcessEnv}from"./process-env-BMQKxoSL.mjs";import{l as resolveExecutablePathAsync}from"./executable-path-BYWCW0PG.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{a as withGitProcessOperation}from"./spawn-diagnostics-C-LTFiNq.mjs";import{t as runCommandBuffered}from"./exec-c5tqm8tb.mjs";import{t as createStaleWhileRevalidateCache}from"./stale-while-revalidate-cache-CaAugAC4.mjs";import{n as resolveGitHubHost}from"./github-host-runtime-BU0Fqlvz.mjs";import path from"node:path";import fs from"node:fs/promises";
//!src/agents/github-read-identity.ts
const GITHUB_IDENTITY_COMMAND_TIMEOUT_MS=15e3;const GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES=32768;const nativeTokens=createStaleWhileRevalidateCache({maxEntries:32,ttlMs:6e4,cacheable:e=>e!==void 0});let nativeConfiguration;function readNativeGitHubConfiguration(e){return nativeConfiguration?.host===e?nativeConfiguration.state:`unknown`}async function refreshNativeGitHubConfiguration(){const e=resolveGitHubHost();const t={host:e,state:readNativeGitHubConfiguration(e)};nativeConfiguration=t;let n=`unknown`;try{n=await readNativeGitHubToken({},true,e)?`configured`:`unconfigured`}catch{}if(nativeConfiguration===t)t.state=n}const githubIdentityChanges={};function clearNativeGitHubTokenCache(){nativeTokens.clear();nativeConfiguration=void 0;try{githubIdentityChanges.onChange?.()}catch{}}function ambientGitHubCredential(e,t=resolveGitHubHost()){const n=t===`github.com`?[`GH_TOKEN`,`GITHUB_TOKEN`]:[`GH_ENTERPRISE_TOKEN`,`GITHUB_ENTERPRISE_TOKEN`];const r=resolveEnvironmentValue(e,n[0])||resolveEnvironmentValue(e,n[1]);if(r&&t!==`github.com`&&resolveEnvironmentValue(e,`GH_HOST`)?.trim().toLowerCase()!==t)throw new GitHubIdentityError(`unverified`);return{host:t,token:r}}async function readCachedNativeGitHubToken(e,t=false,n=resolveGitHubHost(),r){const i=mergeProcessEnv([process.env,e]);const{host:a,token:o}=ambientGitHubCredential(i,n);if(o)return normalizeGitHubToken(o);const s=sha256Hex(JSON.stringify([a,process.cwd(),Object.entries(i).toSorted(([e],[t])=>e.localeCompare(t)),t]));const{value:c,stale:l}=await nativeTokens.read(s,()=>readNativeGitHubToken(e,t,a),{allowStale:r!==void 0});if(l)r?.onStale();return c}async function runGitHubIdentityCommand(e,t,n,r=GITHUB_IDENTITY_COMMAND_TIMEOUT_MS){return await withGitProcessOperation(`github.identity`,()=>runCommandBuffered(e,{env:t?{...t}:{},cwd:n,timeoutMs:r,maxOutputBytes:GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES}),`default`)}function normalizeGitHubToken(e){const t=e.trim();if(!t||t.length>2048||/\s/u.test(t))throw new Error(`Managed GitHub credential must be one non-empty line.`);registerSecretValueForRedaction(t);return t}async function assertNoNativeGitHubConfiguration(e,t){const value=t=>resolveEnvironmentValue(e,t);const n=process.platform===`win32`;const r=n?path.win32:path.posix;const i=value(n?`USERPROFILE`:`HOME`);const a=value(`XDG_CONFIG_HOME`);const o=value(`APPDATA`);const s=value(`GH_CONFIG_DIR`)||(a?r.join(a,`gh`):void 0)||(n&&o?r.join(o,`GitHub CLI`):void 0)||(i?r.join(i,`.config`,`gh`):void 0);if(!s)throw new GitHubIdentityError(`unverified`);const c=r.resolve(t,s);for(const e of[c,r.join(c,`config.yml`),r.join(c,`hosts.yml`)])try{const t=await fs.lstat(e);if(e!==c||!t.isDirectory()||t.isSymbolicLink())throw new GitHubIdentityError(`unavailable`)}catch(e){if(e instanceof GitHubIdentityError)throw e;if(!hasErrnoCode(e,`ENOENT`))throw new GitHubIdentityError(`unverified`)}}async function readNativeGitHubToken(e,t=false,n=resolveGitHubHost()){const r=mergeProcessEnv([process.env,e]);const{token:i}=ambientGitHubCredential(r,n);if(i)return normalizeGitHubToken(i);const a={...e,GH_HOST:n,GH_TOKEN:void 0,GITHUB_TOKEN:void 0,GH_ENTERPRISE_TOKEN:void 0,GITHUB_ENTERPRISE_TOKEN:void 0};const o=performance.now();const s=await runGitHubIdentityCommand([`gh`,`auth`,`token`,`--hostname`,n],a);try{if(s.code===0)return normalizeGitHubToken(s.stdout.toString(`utf8`))}finally{s.stdout.fill(0);s.stderr.fill(0)}if(!t)return;if(s.termination===`error`)try{const e=process.cwd();if(!hasErrnoCode(s.error,`ENOENT`)||!(await fs.stat(e)).isDirectory()||await resolveExecutablePathAsync(`gh`,{env:r,cwd:e,useCache:false}))throw new GitHubIdentityError(`unverified`);await assertNoNativeGitHubConfiguration(r,e);return}catch(e){throw e instanceof GitHubIdentityError?e:new GitHubIdentityError(`unverified`)}if(s.termination!==`exit`)throw new GitHubIdentityError(`unverified`);const c=GITHUB_IDENTITY_COMMAND_TIMEOUT_MS-Math.ceil(performance.now()-o);if(c<=0)throw new GitHubIdentityError(`unverified`);const l=await runGitHubIdentityCommand([`gh`,`auth`,`status`,`--active`,`--hostname`,n,`--json`,`hosts`],a,void 0,c);try{if(l.code!==0)throw new GitHubIdentityError(`unverified`);let e;try{e=JSON.parse(l.stdout.toString(`utf8`))}catch{throw new GitHubIdentityError(`unverified`)}if(!isRecord(e)||!isRecord(e.hosts)||Object.keys(e).length!==1)throw new GitHubIdentityError(`unverified`);if(Object.keys(e.hosts).length!==0)throw new GitHubIdentityError(`unavailable`);return}finally{l.stdout.fill(0);l.stderr.fill(0)}}function startGitHubIdentityOperation(e,t){t.assertCurrent?.();return t.startCurrent?t.startCurrent(()=>{t.assertCurrent?.();return e()}):e()}var GitHubIdentityError=class extends Error{constructor(e){super(e===`changed`?`GitHub identity changed; reload the dashboard and retry.`:e===`rate_limited`?`GitHub identity verification is rate limited; wait and retry.`:e===`unverified`?`The effective GitHub identity could not be verified; retry or reconnect the agent's GitHub identity.`:`The selected GitHub credential is unavailable; reconnect the agent's GitHub identity in Settings.`);this.reason=e}};function createGitHubReadIdentity(e){const{token:t,selection:n,assertSelected:r,startActive:i,readToken:a}=e;const o={assertCurrent:r,startCurrent:i};const start=async e=>{const n=await startGitHubIdentityOperation(a,o);return await startGitHubIdentityOperation(()=>{if(n!==t)throw new GitHubIdentityError(`changed`);return e()},o)};const s={...e.stale?{stale:true}:{},cacheScope:n.source===`anonymous`?`anonymous`:sha256Hex(JSON.stringify([n.source,n.profileId,n.accountId,t])),assertSelected:r,revalidate:()=>start(()=>void 0),start};return e.token===void 0?{...s,token:void 0,selection:Object.freeze(e.selection)}:{...s,token:e.token,selection:Object.freeze(e.selection)}}async function readGitAuthor(e,t){const n=await runGitHubIdentityCommand([`git`,`config`,`--null`,`--get-regexp`,`^user\\.(name|email)$`],{...e,GIT_NO_LAZY_FETCH:`1`},t);const r={name:null,email:null};if(n.code!==0)return r;for(const e of n.stdout.toString(`utf8`).split(`\0`)){const t=e.indexOf(`
`);if(t<0)continue;const n=e.slice(0,t);const i=readNonBlankString(e.slice(t+1))?.trim()??null;if(n===`user.name`)r.name=i;else if(n===`user.email`)r.email=i}return r}export{normalizeGitHubToken as a,readNativeGitHubConfiguration as c,startGitHubIdentityOperation as d,githubIdentityChanges as i,readNativeGitHubToken as l,clearNativeGitHubTokenCache as n,readCachedNativeGitHubToken as o,createGitHubReadIdentity as r,readGitAuthor as s,GitHubIdentityError as t,refreshNativeGitHubConfiguration as u};