UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 5.29 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{d as shortenHomeInString,t as CONFIG_DIR}from"./utils-Dlk0IYAa.mjs";import{l as pathExists,r as canonicalPathFromExistingAncestor}from"./fs-safe-Bxzu1j4h.mjs";import{s as readFileDescriptorBounded}from"./boundary-file-read-bB9An35K.mjs";import{n as ok,t as err}from"./result-CkiK_t2O.mjs";import{t as resolveSystemBin}from"./resolve-system-bin-BxjtTRjs.mjs";import{n as runExec}from"./exec-c5tqm8tb.mjs";import{r as normalizeTlsFingerprint}from"./client-address-utils-CIkL4kpz.mjs";import path from"node:path";import{X509Certificate}from"node:crypto";import fs from"node:fs/promises";import{ensureDurableDirectory,publishFileExclusive}from"@openclaw/fs-safe/durability";import tls from"node:tls"; //!src/infra/tls/gateway.ts const GATEWAY_TLS_CERT_GENERATION_TIMEOUT_MS=3e4;const MAX_TLS_LEAF_FILE_BYTES=65536;async function readTlsLeafFile(e){const t=await fs.open(e,`r`);try{return(await readFileDescriptorBounded(t.fd,MAX_TLS_LEAF_FILE_BYTES)).toString(`utf8`)}finally{await t.close()}}async function publishGeneratedTlsOutput(e,t){const n=[];const r=await fs.open(e,`r+`);let i;try{await r.sync();i=await r.stat({bigint:true})}finally{await r.close()}const a=await publishFileExclusive({sourcePath:e,targetPath:t,expectedSourceIdentity:i,strategy:`link-or-copy`});if(a.method===`exclusive-copy`)n.push(`atomic hard-link publication unavailable`);if(a.directorySync.status===`unsupported`)n.push(`directory durability unavailable`);return n}async function generateSelfSignedCert(e){const t=await canonicalPathFromExistingAncestor(path.dirname(e.certPath));const n=await canonicalPathFromExistingAncestor(path.dirname(e.keyPath));const r=await ensureDurableDirectory({directoryPath:t});const i=n===t?r:await ensureDurableDirectory({directoryPath:n});const a=resolveSystemBin(`openssl`);if(!a)throw new Error(`openssl not found in trusted system directories. Install it in an OS-managed location.`);const o=await fs.mkdtemp(path.join(t,`.openclaw-gateway-tls-cert-`));const s=path.join(o,`cert.pem`);let c;try{c=await fs.mkdtemp(path.join(n,`.openclaw-gateway-tls-key-`));const t=path.join(c,`key.pem`);await Promise.all([fs.chmod(o,448),fs.chmod(c,448)]);await runExec(a,[`req`,`-x509`,`-newkey`,`rsa:2048`,`-sha256`,`-days`,`3650`,`-nodes`,`-keyout`,t,`-out`,s,`-subj`,`/CN=openclaw-gateway`],{logOutput:false,timeoutMs:GATEWAY_TLS_CERT_GENERATION_TIMEOUT_MS});await Promise.all([fs.chmod(t,384),fs.chmod(s,384)]);const[l,u]=await Promise.all([fs.readFile(s,`utf8`),fs.readFile(t,`utf8`)]);tls.createSecureContext({cert:l,key:u,minVersion:`TLSv1.3`});const d=/* @__PURE__ */ new Set;if(r.parentSync.status===`unsupported`||i.parentSync.status===`unsupported`)d.add(`directory durability unavailable`);(await publishGeneratedTlsOutput(s,path.join(r.path,path.basename(e.certPath)))).forEach(e=>d.add(e));(await publishGeneratedTlsOutput(t,path.join(i.path,path.basename(e.keyPath)))).forEach(e=>d.add(e));for(const t of d){const n={event:`gateway.tls.degraded`,ownerKind:`gateway`,ownerId:`tls`,reason:t,state:`best-effort`};e.log?.warn?.(`[GATEWAY_TLS_DEGRADED] best-effort gateway:tls: ${n.reason}.`,n)}e.log?.info?.(`gateway tls: generated self-signed cert at ${shortenHomeInString(e.certPath)}`)}finally{await Promise.allSettled([o,c].filter(e=>Boolean(e)).map(e=>fs.rm(e,{force:true,recursive:true})))}}function resolveGatewayTlsCertPath(e){return resolveUserPath(typeof e===`string`&&e.trim()?e:path.join(CONFIG_DIR,`gateway`,`tls`,`gateway-cert.pem`))}async function inspectGatewayTlsCertificate(e){if(e?.enabled!==true)return err(`gateway tls is disabled`);try{const t=await readTlsLeafFile(resolveGatewayTlsCertPath(e.certPath));const n=normalizeTlsFingerprint(new X509Certificate(t).fingerprint256);return n?ok({cert:t,fingerprintSha256:n}):err(`gateway tls: unable to compute certificate fingerprint`)}catch(e){return err(`gateway tls: failed to load cert (${String(e)})`)}}async function loadGatewayTlsServerRuntime(e,t){if(!e||e.enabled!==true)return{enabled:false};const n=e.autoGenerate!==false;const r=path.join(CONFIG_DIR,`gateway`,`tls`);const i=resolveGatewayTlsCertPath(e.certPath);const a=resolveUserPath(typeof e.keyPath===`string`&&e.keyPath.trim()?e.keyPath:path.join(r,`gateway-key.pem`));const o=e.caPath?resolveUserPath(e.caPath):void 0;const s={enabled:false,certPath:i,keyPath:a};const c=await pathExists(i);const l=await pathExists(a);if(!c&&!l&&n)try{await generateSelfSignedCert({certPath:i,keyPath:a,log:t})}catch(e){return{...s,error:`gateway tls: failed to generate cert (${String(e)})`}}if(!await pathExists(i)||!await pathExists(a))return{...s,error:`gateway tls: cert/key missing`};try{const e=await readTlsLeafFile(i);const t=await readTlsLeafFile(a);const n=o?await fs.readFile(o,`utf8`):void 0;const r=new X509Certificate(e);const c=normalizeTlsFingerprint(r.fingerprint256??``);if(!c)return{...s,caPath:o,error:`gateway tls: unable to compute certificate fingerprint`};const l={cert:e,key:t,ca:n,minVersion:`TLSv1.3`};tls.createSecureContext(l);return{...s,enabled:true,caPath:o,fingerprintSha256:c,tlsOptions:l}}catch(e){return{...s,caPath:o,error:`gateway tls: failed to load cert (${String(e)})`}}}export{loadGatewayTlsServerRuntime as n,inspectGatewayTlsCertificate as t};