UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 2.32 kB
import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import{t as KeyedAsyncQueue}from"./keyed-async-queue-qBcorzrt.mjs";import path from"node:path";import{createHash,createPrivateKey,createPublicKey,randomBytes}from"node:crypto";import fs from"node:fs/promises"; //!src/gateway/openclaw-id/tunnel-child/keyfile.ts const KEY_BYTES=32;const keyFiles=new KeyedAsyncQueue;const ED25519_PKCS8_PREFIX=Buffer.from(`302e020100300506032b657004220420`,`hex`);var KeyFileRefusedError=class extends Error{};function stagedKeyPath(e){return`${e}.next`}async function loadKeyFile(e){const t=await fs.stat(e).catch(ignoreMissingPath);if(!t)return;if(process.platform!==`win32`&&(t.mode&63)!==0)throw new KeyFileRefusedError(`${e} must not be group- or world-accessible`);const n=await fs.readFile(e);if(n.length!==KEY_BYTES)throw new KeyFileRefusedError(`${e} is not a ${KEY_BYTES}-byte key`);return n}async function createKeyFile(e){const t=randomBytes(KEY_BYTES);await fs.mkdir(path.dirname(e),{recursive:true,mode:448});const n=`${e}.${randomBytes(4).toString(`hex`)}.tmp`;await fs.writeFile(n,t,{mode:384,flag:`wx`});await fs.rename(n,e);return t}function loadOrCreateEndpointKey(e){return keyFiles.enqueue(path.resolve(path.dirname(e)),async()=>{const t=await loadKeyFile(e);return t?{key:t,created:false}:{key:await createKeyFile(e),created:true}})}function ed25519PublicKeyHex(e){const t=Buffer.concat([ED25519_PKCS8_PREFIX,e]);try{const e=createPublicKey(createPrivateKey({key:t,format:`der`,type:`pkcs8`})).export({format:`jwk`});return Buffer.from(e.x??``,`base64url`).toString(`hex`)}finally{t.fill(0)}}function loadBoundKey(e,t){return keyFiles.enqueue(path.resolve(path.dirname(e)),async()=>{const n=stagedKeyPath(e);const r=await loadKeyFile(e);if(r&&ed25519PublicKeyHex(r)===t)return{key:r,promoted:false};r?.fill(0);const i=await loadKeyFile(n);if(i&&ed25519PublicKeyHex(i)===t){await fs.rename(n,e);return{key:i,promoted:true}}i?.fill(0);return{refused:r?`key_mismatch`:`keys_missing`}})}function logFingerprint(e){const t=/^[0-9a-f]{64}$/.test(e)?Buffer.from(e,`hex`):Buffer.from(e);return`fp:${createHash(`sha256`).update(t).digest(`hex`).slice(0,8)}`}export{loadOrCreateEndpointKey as a,loadKeyFile as i,ed25519PublicKeyHex as n,logFingerprint as o,loadBoundKey as r,stagedKeyPath as s,KeyFileRefusedError as t};