openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
15 lines • 20.7 kB
JavaScript
import{g as parseSecretRef}from"./types.secrets-UWdyCdE6.mjs";import{i as pinDirectory,o as publishFileNoClobber,s as requireDirectorySync,t as ensureDurableDirectory}from"./directory-durability-o_aQCRBZ.mjs";import{i as isMissingPathError,t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{Fn as object,Jn as string,Pn as number,or as union,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{t as resolveStorageProvider}from"./storage-provider-registry-tzvkcH4r.mjs";import path from"node:path";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,scrypt,timingSafeEqual}from"node:crypto";import fs from"node:fs/promises";import{root}from"@openclaw/fs-safe/root";
//!src/storage/encryption.ts
const MAGIC=Buffer.from(`OCSTOR1
`);const STORAGE_SEGMENT_BYTES=1048576;const TAG_BYTES=16;const MAX_HEADER_BYTES=1024;var StreamReader=class{constructor(e){this.chunk=/* @__PURE__ */ new Uint8Array;this.offset=0;this.iterator=e[Symbol.asyncIterator]()}async read(e){const t=Buffer.allocUnsafe(e);let n=0;while(n<e){if(this.offset===this.chunk.length){const e=await this.iterator.next();if(e.done)break;this.chunk=e.value;this.offset=0;if(this.chunk.length===0)continue}const r=Math.min(e-n,this.chunk.length-this.offset);t.set(this.chunk.subarray(this.offset,this.offset+r),n);n+=r;this.offset+=r}return t.subarray(0,n)}async close(){await this.iterator.return?.()}};function headerBytes(e,t){const n=Buffer.from(JSON.stringify({v:1,objSalt:e.toString(`base64`),noncePrefix:t.toString(`base64`),segmentBytes:STORAGE_SEGMENT_BYTES}));const r=Buffer.alloc(4);r.writeUInt32BE(n.length);return Buffer.concat([MAGIC,r,n])}const HEADER_BYTES=headerBytes(Buffer.alloc(32),Buffer.alloc(7)).length;function encryptedStorageSize(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Storage size must be a nonnegative safe integer.`);const t=Math.floor(e/STORAGE_SEGMENT_BYTES)+1;if(t>4294967296)throw new Error(`Storage object exceeds the encryption segment limit.`);return HEADER_BYTES+e+t*TAG_BYTES}function nonce(e,t,n){if(t>4294967295)throw new Error(`Storage object exceeds the encryption segment limit.`);const r=Buffer.alloc(12);e.copy(r);r.writeUInt32BE(t,7);r[11]=n?1:0;return r}async function*encryptStorageObject(e,t){const n=randomBytes(32);const r=randomBytes(7);const i=headerBytes(n,r);const a=Buffer.from(hkdfSync(`sha256`,t,n,`openclaw-storage v1 object`,32));const o=new StreamReader(e);try{yield i;for(let e=0;;e++){const t=await o.read(STORAGE_SEGMENT_BYTES);const n=t.length<STORAGE_SEGMENT_BYTES;const s=createCipheriv(`aes-256-gcm`,a,nonce(r,e,n));s.setAAD(i);yield Buffer.concat([s.update(t),s.final(),s.getAuthTag()]);if(n)break}}finally{a.fill(0);await o.close()}}function decodeBase64(e,t){if(typeof e!==`string`)throw new Error(`Invalid storage encryption header.`);const n=Buffer.from(e,`base64`);if(n.length!==t||n.toString(`base64`)!==e)throw new Error(`Invalid storage encryption header.`);return n}async function readHeader(e){const t=await e.read(MAGIC.length+4);if(t.length!==MAGIC.length+4||!t.subarray(0,MAGIC.length).equals(MAGIC))throw new Error(`Invalid storage encryption magic.`);const n=t.readUInt32BE(MAGIC.length);if(n===0||n>MAX_HEADER_BYTES)throw new Error(`Invalid storage encryption header length.`);const r=await e.read(n);if(r.length!==n)throw new Error(`Truncated storage encryption header.`);const i=JSON.parse(r.toString(`utf8`));if(!i||typeof i!==`object`||!(`v`in i)||i.v!==1||!(`segmentBytes`in i)||i.segmentBytes!==STORAGE_SEGMENT_BYTES||!(`objSalt`in i)||!(`noncePrefix`in i))throw new Error(`Unsupported storage encryption header.`);return{header:Buffer.concat([t,r]),salt:decodeBase64(i.objSalt,32),prefix:decodeBase64(i.noncePrefix,7)}}async function*decryptStorageObject(e,t){const n=new StreamReader(e);let r;try{const{header:e,salt:i,prefix:a}=await readHeader(n);r=Buffer.from(hkdfSync(`sha256`,t,i,`openclaw-storage v1 object`,32));for(let t=0;;t++){const i=await n.read(1048592);if(i.length<TAG_BYTES)throw new Error(`Truncated storage object: missing final segment.`);const o=i.length<1048592;const s=createDecipheriv(`aes-256-gcm`,r,nonce(a,t,o));s.setAAD(e);s.setAuthTag(i.subarray(-16));const c=Buffer.concat([s.update(i.subarray(0,-16)),s.final()]);if(c.length>0)yield c;if(o)return}}finally{r?.fill(0);await n.close()}}function plaintextStorageSize(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Storage size must be a nonnegative safe integer.`);const t=e-HEADER_BYTES;const n=Math.floor(t/1048592);const r=t%1048592;if(t<TAG_BYTES||r<TAG_BYTES)throw new Error(`Truncated storage object: missing final segment.`);if(n+1>4294967296)throw new Error(`Storage object exceeds the encryption segment limit.`);return t-(n+1)*TAG_BYTES}
//!src/storage/keys.ts
function validateStorageKey(e){if(Buffer.byteLength(e)>512||!e.split(`/`).every(e=>/^[A-Za-z0-9._-]+$/.test(e)&&e!==`.`&&e!==`..`))throw new Error(`Storage keys must contain nonempty /-separated letters, digits, dots, underscores or hyphens, without . or .. segments, and be at most 512 bytes.`)}function validateStoragePrefix(e){if(e!==``){validateStorageKey(e.endsWith(`/`)?e.slice(0,-1):e);if(Buffer.byteLength(e)>512)throw new Error(`Storage prefixes must be at most 512 bytes.`)}}
//!src/storage/filesystem.ts
function validateSettings(e){if(typeof e.path!==`string`||!path.isAbsolute(e.path))return`Filesystem storage settings.path must be an absolute directory path.`;if(Object.keys(e).some(e=>e!==`path`))return`Filesystem storage only accepts the path setting.`}function ignoreMissingPath(e){if(!isMissingPathError(e))throw e}const filesystemStorageProvider={id:`filesystem`,label:`Filesystem`,validateSettings,describeTarget:e=>typeof e.path===`string`?e.path:void 0,async open({settings:e,signal:t}){const n=validateSettings(e);if(n||typeof e.path!==`string`)throw new Error(n??`Filesystem storage requires a path.`);t?.throwIfAborted();const r=await pinDirectory(e.path,{label:`Storage root directory`});try{const t=await root(r.receipt.realPath,{symlinks:`reject`,mutationSymlinks:`reject`,hardlinks:`reject`,mkdir:false});await r.assertCurrent();const n=/* @__PURE__ */ new Set;async function assertCurrent(e){e?.throwIfAborted();await r.assertCurrent()}const i={displayTarget:e.path,async probe(e){await assertCurrent(e?.signal);const t=await fs.statfs(r.receipt.realPath);await assertCurrent(e?.signal);return{freeBytes:t.bavail*t.bsize,totalBytes:t.blocks*t.bsize}},async putObject(e,n,i){await assertCurrent(i.signal);const a=path.posix.dirname(e);const o=path.join(t.rootReal,a);if(a!==`.`){const e=await ensureDurableDirectory({directoryPath:o,label:`Storage object directory`,create:async()=>{await assertCurrent(i.signal);await t.mkdir(a)}});requireDirectorySync(e.parentSync,`Storage object directory`)}await assertCurrent(i.signal);const s=await pinDirectory(o,{label:`Storage object directory`});const c=path.posix.join(a,`.openclaw-put-${randomUUID()}.tmp~`);let l=false;let u=0;async function*measuredBody(){for await(const t of n){i.signal?.throwIfAborted();u+=t.byteLength;if(i.sizeBytes!==void 0&&u>i.sizeBytes)throw new Error(`Storage object ${e} exceeds its declared size.`);yield t}if(i.sizeBytes!==void 0&&u!==i.sizeBytes)throw new Error(`Storage object ${e} does not match its declared size.`)}try{await t.create(c,measuredBody(),{durable:`file`,mkdir:false,mode:384,maxBytes:i.sizeBytes??Number.MAX_SAFE_INTEGER,signal:i.signal});l=true;await s.assertCurrent();await assertCurrent(i.signal);await publishFileNoClobber(path.join(t.rootReal,c),path.join(t.rootReal,e),{strategy:`link-required`,moveSource:true,durability:`fail-closed`});l=false;requireDirectorySync(await s.sync(),`Storage object directory`);await assertCurrent(i.signal);return{sizeBytes:u}}finally{try{if(l){await r.assertCurrent();await s.assertCurrent();await t.remove(c,{force:true});requireDirectorySync(await s.sync(),`Storage object directory`)}}finally{await s.close()}}},async getObject(e,r){await assertCurrent(r?.signal);const i=await t.open(e).catch(ignoreMissingPath);if(!i)return;const a=i.handle;n.add(a);return(async function*(){try{await assertCurrent(r?.signal);while(true){r?.signal?.throwIfAborted();const e=Buffer.allocUnsafe(65536);const{bytesRead:t}=await a.read(e,0,e.length,null);if(t===0)break;yield e.subarray(0,t)}}finally{n.delete(a);await a.close()}})()},async statObject(e,n){await assertCurrent(n?.signal);const r=await t.stat(e).catch(ignoreMissingPath);await assertCurrent(n?.signal);return r?.isFile?{key:e,sizeBytes:r.size,modifiedAt:r.mtimeMs}:void 0},async*listObjects(e,n){await assertCurrent(n?.signal);const r=e.slice(0,e.lastIndexOf(`/`)+1).replace(/\/$/u,``);if(!(await t.stat(r||`.`).catch(ignoreMissingPath))?.isDirectory)return;for await(const a of t.walk(r,{symlinkPolicy:`skip`,signal:n?.signal,order:`filesystem`,entryFilter(e){try{validateStorageKey(e.relativePath)}catch{return`skip-subtree`}return`include`}})){if(a.kind!==`file`||!a.relativePath.startsWith(e))continue;const t=await i.statObject(a.relativePath,n);if(t)yield t}},async deleteObject(e,n){if(!await i.statObject(e,n))return;const r=await pinDirectory(path.dirname(path.join(t.rootReal,e)));try{await assertCurrent(n?.signal);await t.remove(e,{force:true,signal:n?.signal});requireDirectorySync(await r.sync(),`Storage object directory`)}finally{await r.close()}},async close(){try{await Promise.all([...n].map(e=>e.close()))}finally{n.clear();await r.close()}}};return i}catch(e){await r.close();throw e}}};
//!src/storage/marker.ts
const STORAGE_MARKER_KEY=`openclaw-storage.json`;const KEY_CHECK=`openclaw-storage key check v1`;const base64=e=>string().refine(t=>{const n=Buffer.from(t,`base64`);return n.length===e&&n.toString(`base64`)===t});const markerSchema=object({version:literal(1),locationId:string().uuid(),createdAt:number().int().nonnegative(),encryption:union([literal(`none`),object({kdf:literal(`scrypt`),salt:base64(16),N:literal(32768),r:literal(8),p:literal(1),keyCheck:base64(32)}).strict()])}).strict();var StorageLocationError=class extends Error{constructor(e,t){super(t);this.name=`StorageLocationError`;this.state=e}};const cacheFingerprintKey=randomBytes(32);const masterKeys=/* @__PURE__ */ new Map;function deriveMasterKey(e,t,n){const r=createHmac(`sha256`,cacheFingerprintKey).update(n).update(`\0`).update(t).digest(`hex`);const i=masterKeys.get(e);if(i?.fingerprint===r)return i.key;const a=new Promise((e,r)=>{scrypt(t,Buffer.from(n,`base64`),32,{N:32768,r:8,p:1,maxmem:67108864},(t,n)=>{if(t)r(t);else e(n)})});masterKeys.set(e,{fingerprint:r,key:a});a.catch(()=>{if(masterKeys.get(e)?.key===a)masterKeys.delete(e)});return a}async function readStorageMarker(e,t){const n=await e.getObject(STORAGE_MARKER_KEY,{signal:t});if(!n)return;const r=[];let i=0;for await(const e of n){i+=e.byteLength;if(i>4096)throw new StorageLocationError(`error`,`Storage marker exceeds 4096 bytes.`);r.push(Buffer.from(e))}try{return markerSchema.parse(JSON.parse(Buffer.concat(r).toString(`utf8`)))}catch{throw new StorageLocationError(`error`,`Invalid storage location marker.`)}}async function verifyStorageMarker(e,t,n){if(t.encryption===`none`){if(n!==void 0)throw new StorageLocationError(`wrong-key`,`Storage location "${e}" was initialized without encryption; restore its original encryption configuration.`);return}if(n===void 0)throw new StorageLocationError(`wrong-key`,`Storage location "${e}" requires its original encryption passphrase.`);const r=await deriveMasterKey(e,n,t.encryption.salt);const i=Buffer.from(t.encryption.keyCheck,`base64`);const a=createHmac(`sha256`,r).update(KEY_CHECK).digest();if(!timingSafeEqual(i,a))throw new StorageLocationError(`wrong-key`,`Wrong encryption passphrase for storage location "${e}".`);return r}async function createStorageMarker(e,t){const n={version:1,locationId:randomUUID(),createdAt:Date.now(),encryption:`none`};if(t!==void 0){const r=randomBytes(16).toString(`base64`);const i=await deriveMasterKey(e,t,r);n.encryption={kdf:`scrypt`,salt:r,N:32768,r:8,p:1,keyCheck:createHmac(`sha256`,i).update(KEY_CHECK).digest(`base64`)}}return n}
//!src/storage/provider.ts
async function acquireStorageProvider(e){if(e.providerId===`filesystem`)return{provider:filesystemStorageProvider,release:async()=>{}};if(e.registry){const t=resolveStorageProvider(e.registry,e.providerId);if(!t)throw new Error(`Storage provider "${e.providerId}" is not loaded; check its plugin configuration.`);return{provider:t,registry:e.registry,release:async()=>{}}}const{applyPluginAutoEnable:t}=await import(`./plugin-auto-enable-vCVcote7.mjs`);const n=t({config:e.config,env:e.env??process.env});const{resolveManifestContractRuntimePluginResolution:r}=await import(`./manifest-contract-runtime-CnKay3HW.mjs`);const i=r({cfg:n.config,contract:`storageProviders`,value:e.providerId});if(i.pluginIds.length===0)throw new Error(`Storage provider "${e.providerId}" is unavailable; install and enable its plugin.`);const{acquirePluginRegistryForInspection:a}=await import(`./plugins/loader.js`);const o=await a({config:n.config,autoEnabledReasons:n.autoEnabledReasons,onlyPluginIds:i.pluginIds});try{const t=resolveStorageProvider(o.registry,e.providerId);if(!t)throw new Error(`Plugin did not register storage provider "${e.providerId}".`);return{provider:t,registry:o.registry,release:o.release}}catch(e){await o.release();throw e}}
//!src/storage/locations.ts
function configuredLocation(e){if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(e.name))throw new StorageLocationError(`error`,`Invalid storage location name.`);const t=e.config.storage?.locations?.[e.name];if(!t)throw new StorageLocationError(`error`,`Storage location "${e.name}" is not configured.`);return t}function unavailable(e,t){return new StorageLocationError(`unavailable`,`Storage location "${e}"${t?` (${t})`:``} has no initialization marker. If this is a new location, run \`openclaw storage init ${e}\`; otherwise reconnect the disk or check the bucket and prefix.`)}function storageLocationError(e){if(e instanceof StorageLocationError)return e;if(isMissingPathError(e)||hasErrnoCode(e,`path-mismatch`))return new StorageLocationError(`unavailable`,`Storage directory is unavailable. Reconnect the disk and check the configured path; storage init requires an existing directory.`);return new StorageLocationError(`error`,`Storage could not be accessed. Check its provider settings, credentials, and connection.`)}function probeFailure(e){const{state:t,message:n}=storageLocationError(e);return{state:t,message:n}}async function prepare(e){e.signal?.throwIfAborted();const t=configuredLocation(e);const n=await acquireStorageProvider({providerId:t.provider,config:e.config,registry:e.registry,env:e.env}).catch(e=>{throw storageLocationError(e)});try{const r=n.provider.validateSettings?.(t.settings);if(r)throw new StorageLocationError(`error`,r);const i=e.env??process.env;let a;if(t.encryption!==`none`){const{materializeSecretInput:n}=await import(`./resolve-secret-input-string-D2GSnFYD.mjs`);a=await n({config:e.config,value:t.encryption.passphrase,env:i,normalize:e=>typeof e===`string`&&e.length>0?e:void 0})}if(t.encryption!==`none`&&a===void 0)throw new StorageLocationError(`wrong-key`,`Storage location "${e.name}" requires a nonempty encryption passphrase.`);const o=await n.provider.open({locationName:e.name,settings:t.settings,signal:e.signal,resolveSecret:async t=>{const n=parseSecretRef(t,e.config.secrets?.defaults);if(!n)throw new Error(`Storage provider credentials must use SecretRefs.`);const{resolveSecretRefString:r}=await import(`./resolve-BoevD-iP.mjs`);return await r(n,{config:e.config,env:i})}});let s=false;const close=async()=>{if(s)return;s=true;try{try{await o.close?.()}finally{await n.release()}}catch(e){throw storageLocationError(e)}};return{backend:o,passphrase:a,provider:t.provider,close}}catch(e){await n.release().catch(e=>{throw storageLocationError(e)});throw storageLocationError(e)}}async function makeLocation(e,t,n){const{backend:r,passphrase:i}=t;const a=await verifyStorageMarker(e.name,n,i);let o=false;const s=JSON.stringify(n);const assertOpen=e=>{e?.throwIfAborted();if(o)throw new StorageLocationError(`unavailable`,`Storage location is closed.`)};const check=async t=>{assertOpen(t);const n=await readStorageMarker(r,t).catch(e=>{throw storageLocationError(e)});if(!n)throw unavailable(e.name,r.displayTarget);if(JSON.stringify(n)!==s)throw new StorageLocationError(`unavailable`,`Storage location "${e.name}" identity changed; reopen the location before using it.`);assertOpen(t)};const info=e=>({...e,storedBytes:e.sizeBytes,sizeBytes:a?plaintextStorageSize(e.sizeBytes):e.sizeBytes});const scoped=i=>{const keyFor=e=>{validateStorageKey(e);const t=i+e;validateStorageKey(t);if(t===`openclaw-storage.json`)throw new Error(`The storage marker is reserved for the storage owner.`);return t};const options=t=>({signal:t?.signal??e.signal});return{describe:()=>({name:e.name,provider:t.provider,displayTarget:r.displayTarget,locationId:n.locationId,encrypted:a!==void 0}),probe:async e=>{try{const t=options(e);await check(t.signal);return{state:`ok`,...await r.probe(t)}}catch(e){return probeFailure(e)}},putObject:async(e,t,n)=>{const i=keyFor(e);const o=options(n);if(n.sizeBytes!==void 0)encryptedStorageSize(n.sizeBytes);await check(o.signal);let s=0;let c;async function*counted(){for await(const e of t){o.signal?.throwIfAborted();s+=e.byteLength;if(n.sizeBytes!==void 0&&s>n.sizeBytes)throw new Error(`Storage object is larger than its declared size.`);yield e}if(n.sizeBytes!==void 0&&s!==n.sizeBytes)throw new Error(`Storage object does not match its declared size.`);await check(o.signal);try{await n.precondition?.(o.signal);assertOpen(o.signal)}catch(e){c={error:e};throw e}}const l=await r.putObject(i,a?encryptStorageObject(counted(),a):counted(),{...o,sizeBytes:n.sizeBytes===void 0?void 0:a?encryptedStorageSize(n.sizeBytes):n.sizeBytes}).catch(e=>{if(!c||e===c.error)throw e;throw new Error(`${formatErrorMessage(c.error)}\n${formatErrorMessage(e)}`,{cause:e})});return{sizeBytes:s,storedBytes:l.sizeBytes}},getObject:async(e,t)=>{const n=keyFor(e);const i=options(t);await check(i.signal);const o=await r.getObject(n,i);return o&&a?decryptStorageObject(o,a):o},stat:async(e,t)=>{const n=keyFor(e);const i=options(t);assertOpen(i.signal);const a=await r.statObject(n,i);assertOpen(i.signal);return a?{...info(a),key:e}:void 0},async*list(e,t){const n=e??``;validateStoragePrefix(n);const a=i+n;validateStoragePrefix(a);const o=options(t);assertOpen(o.signal);for await(const e of r.listObjects(a,o)){assertOpen(o.signal);if(!e.key.startsWith(a))throw new Error(`Storage provider returned an object outside the requested prefix.`);try{validateStorageKey(e.key)}catch{continue}const n=e.key.slice(i.length);if(e.key!==`openclaw-storage.json`&&(!t?.acceptKey||t.acceptKey(n)))yield{...info(e),key:n}}},delete:async(e,t)=>{const n=keyFor(e);const i=options(t);await check(i.signal);await t?.precondition?.(i.signal);assertOpen(i.signal);await r.deleteObject(n,i)},scope:e=>{const t=keyFor(e)+`/`;validateStoragePrefix(t);return scoped(t)},close:async()=>{o=true;await t.close()}}};return scoped(``)}async function openStorageLocation(e){const t=await prepare(e);try{const n=await readStorageMarker(t.backend,e.signal);if(!n)throw unavailable(e.name,t.backend.displayTarget);return await makeLocation(e,t,n)}catch(e){await t.close();throw storageLocationError(e)}}async function initStorageLocation(e){const t=await prepare(e);try{let n=await readStorageMarker(t.backend,e.signal);if(!n){const r=await createStorageMarker(e.name,t.passphrase);const i=Buffer.from(JSON.stringify(r)+`
`);try{await t.backend.putObject(STORAGE_MARKER_KEY,(async function*(){yield i})(),{sizeBytes:i.length,signal:e.signal});n=r}catch(i){n=await readStorageMarker(t.backend,e.signal);if(!n||n.locationId===r.locationId)throw i}}return await makeLocation(e,t,n)}catch(e){await t.close();throw storageLocationError(e)}}async function probeStorageLocation(e){try{const t=await openStorageLocation(e);try{return await t.probe()}finally{await t.close()}}catch(e){return probeFailure(e)}}function listStorageLocations(e,t){return Object.entries(e.storage?.locations??{}).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,n])=>{const r=(n.provider===`filesystem`?filesystemStorageProvider:t?resolveStorageProvider(t,n.provider):void 0)?.describeTarget?.(n.settings);const i={name:e,provider:n.provider,encrypted:n.encryption!==`none`};return r===void 0?i:Object.assign(i,{displayTarget:r})})}export{storageLocationError as a,probeStorageLocation as i,listStorageLocations as n,acquireStorageProvider as o,openStorageLocation as r,initStorageLocation as t};