openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 18 kB
JavaScript
import{a as asOptionalRecord,r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{s as readPositiveIntegerParam}from"./common-DIgvX97L.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import{n as ArchiveLimitError,t as ARCHIVE_LIMIT_ERROR_CODE}from"./archive-BAuHVLxp.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./archive-CS1U7znq.mjs";import"./param-readers-BpVB3RWF.mjs";import{t as FILE_TRANSFER_NODE_INVOKE_COMMANDS}from"./node-invoke-policy-commands-BsXzYr4I.mjs";import{a as persistLiteralGrant,n as evaluateFilePolicy,r as evaluateFilePolicyConstraints}from"./policy-gDWG6qTv.mjs";import{a as DIR_FETCH_MAX_ENTRIES,i as DIR_FETCH_HARD_MAX_BYTES,n as inspectDirFetchArchive,r as DIR_FETCH_DEFAULT_MAX_BYTES}from"./dir-fetch-archive-Ddnnu07X.mjs";import{r as readPathBinding}from"./path-binding-DEwRklUS.mjs";import{n as readFileCreateMetadata}from"./file-create-protocol-BCmesQ8y.mjs";import{i as readFileFetchBinaryMaxBytes,n as FILE_FETCH_DEFAULT_MAX_BYTES,r as FILE_FETCH_HARD_MAX_BYTES}from"./file-fetch-protocol-DuskShAk.mjs";import{n as appendFileTransferAudit,t as bindFileTransferAudit}from"./audit-context-YrxeUP51.mjs";import crypto from"node:crypto";
//!extensions/file-transfer/src/shared/node-invoke-policy-approval.ts
function commandKind(e){return e===`file.write`||e===`file.create`?`write`:`read`}function promptVerb(e){return{"dir.fetch":`Fetch directory`,"dir.list":`List directory`,"file.create":`Create file`,"file.write":`Write file`,"file.fetch":`Read file`,"file.stat":`Read file metadata`}[e]}async function requestApproval(e){const t=e.ctx.node?.displayName;const n=bindFileTransferAudit({op:e.op,nodeId:e.ctx.nodeId,nodeDisplayName:t,requestedPath:e.path},e.startedAt);const r=evaluateFilePolicy({nodeId:e.ctx.nodeId,nodeDisplayName:t,kind:e.kind,command:e.op,path:e.path,pluginConfig:e.ctx.pluginConfig});if(r.ok&&r.reason===`matched-allow`)return{ok:true,source:`authored`,persist:false,followSymlinks:r.followSymlinks,maxBytes:r.maxBytes};if(r.ok&&r.reason===`matched-literal`)return{ok:true,source:`literal`,persist:false,expectedCanonicalPath:r.expectedCanonicalPath,followSymlinks:r.followSymlinks,maxBytes:r.maxBytes};if(!r.ok&&!r.askable){await n({decision:r.code===`NO_POLICY`?`denied:no_policy`:`denied:policy`,errorCode:r.code,reason:r.reason});return{ok:false,code:r.code,message:`${e.op} ${r.code}: ${r.reason}`}}const i=e.ctx.approvals;if(!i){await n({decision:`denied:approval`,reason:`plugin approvals unavailable`});return{ok:false,code:`APPROVAL_UNAVAILABLE`,message:`${e.op} APPROVAL_UNAVAILABLE: plugin approvals unavailable`}}const a=promptVerb(e.op);const o=t??e.ctx.nodeId;const s=(await i.request({title:`${a}: ${e.path}`,description:`${e.op===`dir.fetch`?`Allow ${a.toLowerCase()} on ${o}\nPath: ${e.path}\n\nThis fetch includes descendants of this directory; deny rules still apply.`:`Allow ${a.toLowerCase()} on ${o}\nPath: ${e.path}`}\nNode ID: ${e.ctx.nodeId}\n\n"allow-always" saves this exact command and path for this node.`,severity:e.kind===`write`?`warning`:`info`,toolName:e.op})).decision;if(s!==`allow-once`&&s!==`allow-always`){const t=s===null||s===void 0;const r=s===`deny`;await n({decision:`denied:approval`,reason:r?`operator denied`:t?`no operator available`:`invalid approval decision`});return{ok:false,code:t?`APPROVAL_UNAVAILABLE`:`APPROVAL_DENIED`,message:t?`${e.op} APPROVAL_UNAVAILABLE: no operator client connected to approve the request`:r?`${e.op} APPROVAL_DENIED: operator denied the prompt`:`${e.op} APPROVAL_DENIED: invalid approval decision`}}await n({decision:s===`allow-always`?`allowed:always`:`allowed:once`});return{ok:true,source:`approval`,persist:s===`allow-always`,followSymlinks:r.followSymlinks??false,maxBytes:r.maxBytes,pendingReapprovalSelector:r.ok?void 0:r.pendingReapprovalSelector}}
//!extensions/file-transfer/src/shared/node-invoke-policy-preflight.ts
function joinRemotePolicyPath(e,t){const n=t.replace(/\\/gu,`/`).replace(/^\.\//u,``);if(!n||n===`.`)return e;const r=e.includes(`\\`)&&!e.includes(`/`)?`\\`:`/`;const i=e.replace(/[\\/]$/u,``)||r;return`${i}${i.endsWith(r)?``:r}${n.split(`/`).join(r)}`}function validateDirFetchPreflightEntry(e){if(e.includes(`\0`))return{ok:false,reason:`entry contains NUL byte`};const t=e.replace(/\\/gu,`/`).replace(/^\.\//u,``);if(!t||t===`.`)return{ok:false,reason:`entry is empty`};if(t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t))return{ok:false,reason:`entry is absolute`};if(t===`..`||t.startsWith(`../`)||t.includes(`/../`))return{ok:false,reason:`entry contains '..' traversal`};return{ok:true}}function*dirFetchPolicyPaths(e){const t=/* @__PURE__ */ new Map;yield`.`;for(const n of e){let e=t;let r=``;for(const[t]of n.replace(/\\/gu,`/`).matchAll(/[^/]+/gu)){if(!t||t===`.`)continue;r=r?`${r}/${t}`:t;let n=e.get(t);if(!n){n=/* @__PURE__ */ new Map;e.set(t,n);yield r}e=n}}}async function validateDirFetchEntries(e){const t=e.ctx.node?.displayName;const n=bindFileTransferAudit({op:e.op,nodeId:e.ctx.nodeId,nodeDisplayName:t,requestedPath:e.requestedPath},e.startedAt);const r=e.phase===`preflight`?`PREFLIGHT_ENTRIES_MISSING`:`ARCHIVE_ENTRIES_MISSING`;const i=e.phase===`preflight`?`PREFLIGHT_ENTRY_INVALID`:`ARCHIVE_ENTRY_INVALID`;const a=e.phase===`preflight`?`PREFLIGHT_ENTRIES_TOO_MANY`:`ARCHIVE_ENTRIES_TOO_MANY`;if(!Array.isArray(e.entries)){await n({canonicalPath:e.canonicalPath,decision:`error`,errorCode:r,reason:`dir.fetch ${e.phase} did not return entries`});return policyDeniedResult({op:e.op,code:r,message:`dir.fetch ${e.phase} did not return entries; refusing archive transfer`,details:{path:e.canonicalPath}})}const rejectEntryLimit=async(t,r)=>{const i=`dir.fetch ${e.phase} contains ${t} ${r}; limit ${DIR_FETCH_MAX_ENTRIES}`;await n({canonicalPath:e.canonicalPath,decision:`denied:policy`,errorCode:a,reason:i});return policyDeniedResult({op:e.op,code:a,message:`${i}; refusing archive transfer`,details:{path:e.canonicalPath,reason:i}})};if(e.entries.length>5e3)return await rejectEntryLimit(e.entries.length,`entries`);const o=[];for(const t of e.entries){const r=typeof t===`string`&&t.length>0;const a=r?validateDirFetchPreflightEntry(t):{ok:false,reason:`entry is not a non-empty string`};if(!a.ok){const o=r?joinRemotePolicyPath(e.canonicalPath,t):e.canonicalPath;await n({canonicalPath:o,decision:`denied:policy`,errorCode:i,reason:a.reason});return policyDeniedResult({op:e.op,code:i,message:`directory ${e.phase} entry${r?` ${t}`:``} is invalid: ${a.reason}`,details:{path:o,reason:a.reason}})}o.push(t)}let s=0;for(const r of dirFetchPolicyPaths(o)){if(r!==`.`){s+=1;if(s>5e3)return await rejectEntryLimit(s,`descendant paths`)}const i=joinRemotePolicyPath(e.canonicalPath,r);const a={nodeId:e.ctx.nodeId,nodeDisplayName:t,kind:`read`,command:`dir.fetch`,path:i,pluginConfig:e.ctx.pluginConfig};const o=e.authorization.source===`authored`?evaluateFilePolicy(a):evaluateFilePolicyConstraints(a);if(o.ok)continue;await n({canonicalPath:i,decision:`denied:policy`,errorCode:o.code,reason:o.reason});return policyDeniedResult({op:e.op,code:`PATH_POLICY_DENIED`,message:`directory ${e.phase} entry ${i} is not allowed by policy: ${o.reason}`,details:{path:i,reason:o.reason}})}return null}function policyDeniedResult(e){return{ok:false,code:e.code,message:`${e.op} ${e.code}: ${e.message}`,...e.details?{details:e.details}:{}}}async function invokePreflight(e){const t=e.ctx.node?.displayName;const n=bindFileTransferAudit({op:e.op,nodeId:e.ctx.nodeId,nodeDisplayName:t,requestedPath:e.requestedPath},e.startedAt);const r=await e.ctx.invokeNode({params:{...e.params,preflightOnly:true,...e.expectedCanonicalPath?{expectedCanonicalPath:e.expectedCanonicalPath}:{}}});if(!r.ok){await n({decision:`error`,errorCode:r.code,errorMessage:r.message});return{ok:false,result:{ok:false,code:r.code,message:`${e.op} preflight failed: ${r.message}`,details:r.details,unavailable:true}}}const i=asNullableRecord(r.payload);if(i?.ok===false){const e=typeof i.code===`string`?i.code:`PREFLIGHT_FAILED`;const t=typeof i.canonicalPath===`string`?i.canonicalPath:void 0;await n({canonicalPath:t,decision:`error`,errorCode:e,errorMessage:typeof i.message===`string`?i.message:void 0});if(e===`CANONICAL_PATH_CHANGED`&&t)return{ok:false,result:r,canonicalChanged:true,canonicalPath:t};return{ok:false,result:r}}if(e.op===`file.write`&&e.params.rejectHardlinks===true&&i?.rejectHardlinks!==true)return{ok:false,result:policyDeniedResult({op:e.op,code:`HARDLINK_REJECTION_UNSUPPORTED`,message:`node does not support hardlink-safe workspace writes; update the node and retry`})};const a=i&&typeof i.path===`string`?i.path:``;if(!a)return{ok:false,result:policyDeniedResult({op:e.op,code:`PREFLIGHT_PATH_MISSING`,message:`node preflight did not return a resolved path`})};const o=readPathBinding(i?.binding);const s=e.op===`file.write`||e.op===`file.create`?`write`:`existing`;if(!o||o.kind!==s)return{ok:false,result:policyDeniedResult({op:e.op,code:`FILESYSTEM_IDENTITY_MISSING`,message:`node preflight did not return a filesystem identity; update the node and retry`})};return{ok:true,payload:i,canonicalPath:a,binding:o}}async function validateCanonicalAuthorization(e){const t=e.ctx.node?.displayName;const n=bindFileTransferAudit({op:e.op,nodeId:e.ctx.nodeId,nodeDisplayName:t,requestedPath:e.requestedPath},e.startedAt);if(e.authorization.source===`literal`&&e.authorization.expectedCanonicalPath!==e.canonicalPath){const t=await e.ctx.approvals?.request({title:`${promptVerb(e.op)} target changed: ${e.requestedPath}`,description:`The node now resolves this path to:\n${e.canonicalPath}\n\nApprove this exact resolved target for ${e.ctx.nodeId}.`,severity:e.kind===`write`?`warning`:`info`,toolName:e.op});if(t?.decision!==`allow-once`&&t?.decision!==`allow-always`){await n({canonicalPath:e.canonicalPath,decision:`denied:symlink_escape`,errorCode:`CANONICAL_PATH_CHANGED`,reason:`resolved path differs from the standing approval`});return policyDeniedResult({op:e.op,code:`CANONICAL_PATH_CHANGED`,message:`the resolved path differs from the standing approval and was not reapproved`,details:{path:e.canonicalPath}})}e.authorization.source=`approval`;e.authorization.persist=t.decision===`allow-always`;e.authorization.expectedCanonicalPath=e.canonicalPath}const r={nodeId:e.ctx.nodeId,nodeDisplayName:t,kind:e.kind,command:e.op,path:e.canonicalPath,pluginConfig:e.ctx.pluginConfig};const i=e.authorization.source===`authored`?evaluateFilePolicy(r):evaluateFilePolicyConstraints(r);if(i.ok)return null;await n({canonicalPath:e.canonicalPath,decision:`denied:symlink_escape`,errorCode:i.code,reason:i.reason});return policyDeniedResult({op:e.op,code:`SYMLINK_TARGET_DENIED`,message:`requested path resolved to ${e.canonicalPath} which is not allowed by policy`})}async function runPathPreflight(e){const t=e.authorization.source===`literal`?e.authorization.expectedCanonicalPath:void 0;let n=await invokePreflight({...e,expectedCanonicalPath:t});if(!n.ok&&n.canonicalChanged===true){const t=await validateCanonicalAuthorization({...e,canonicalPath:n.canonicalPath});if(t)return{ok:false,result:t};n=await invokePreflight({...e,expectedCanonicalPath:e.authorization.expectedCanonicalPath});if(!n.ok&&n.canonicalChanged===true){await appendFileTransferAudit({op:e.op,nodeId:e.ctx.nodeId,nodeDisplayName:e.ctx.node?.displayName,requestedPath:e.requestedPath,canonicalPath:n.canonicalPath,decision:`denied:symlink_escape`,errorCode:`CANONICAL_PATH_CHANGED`,reason:`resolved path changed again after reapproval`,durationMs:Date.now()-e.startedAt});return{ok:false,result:policyDeniedResult({op:e.op,code:`CANONICAL_PATH_CHANGED`,message:`the resolved path changed again after reapproval; retry the operation`,details:{path:n.canonicalPath}})}}}if(!n.ok)return{ok:false,result:n.result};const r=await validateCanonicalAuthorization({...e,canonicalPath:n.canonicalPath});if(r)return{ok:false,result:r};if(e.op===`dir.fetch`){const t=await validateDirFetchEntries({...e,canonicalPath:n.canonicalPath,entries:n.payload?.entries,phase:`preflight`});if(t)return{ok:false,result:t}}return{ok:true,canonicalPath:n.canonicalPath,binding:n.binding}}
//!extensions/file-transfer/src/shared/node-invoke-policy.ts
const DIR_FETCH_ARCHIVE_INSPECTION_TIMEOUT_MS=3e4;function readMaxBytes(e){const t=(e.value===void 0?e.defaultValue:readPositiveIntegerParam({maxBytes:e.value},`maxBytes`))??e.defaultValue;const n=Math.max(1,Math.min(t,e.hardMax));return e.policyMax?Math.min(n,e.policyMax):n}function validateFetchMaxBytesParam(e,t){if(e!==`file.fetch`&&e!==`dir.fetch`)return;if(t.maxBytes!==void 0)readPositiveIntegerParam(t,`maxBytes`);if(e===`file.fetch`)readFileFetchBinaryMaxBytes(t)}function readAuditSizeBytes(e,t,n){if(e===`dir.fetch`)return n;if(e===`dir.list`)return;return typeof t?.size===`number`?t.size:void 0}async function verifyDirFetchArchive(e){const t=typeof e?.tarBase64===`string`?e.tarBase64:``;if(!t)return{ok:false,code:`ARCHIVE_ENTRIES_MISSING`,reason:`dir.fetch archive did not return tarBase64`};const n=Buffer.from(t,`base64`);const r=n.byteLength;if(typeof e?.tarBytes===`number`&&e.tarBytes!==r)return{ok:false,code:`ARCHIVE_SIZE_MISMATCH`,reason:`dir.fetch archive size mismatch: payload says ${e.tarBytes} bytes, decoded ${r}`};const i=crypto.createHash(`sha256`).update(n).digest(`hex`);if(typeof e?.sha256===`string`&&e.sha256.toLowerCase()!==i)return{ok:false,code:`ARCHIVE_INTEGRITY_FAILURE`,reason:`dir.fetch archive sha256 mismatch: payload says ${e.sha256.toLowerCase()}, decoded ${i}`};try{return{ok:true,entries:await inspectDirFetchArchive(n,DIR_FETCH_ARCHIVE_INSPECTION_TIMEOUT_MS),sizeBytes:r,sha256:i}}catch(e){const t=e instanceof ArchiveLimitError&&e.code===ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT;return{ok:false,code:t?`ARCHIVE_ENTRIES_TOO_MANY`:`ARCHIVE_ENTRIES_UNREADABLE`,reason:t?`dir.fetch archive contains more than ${DIR_FETCH_MAX_ENTRIES} entries`:`dir.fetch archive inspection failed: ${formatErrorMessage(e)}`}}}async function handleFileTransferInvoke(e){if(!FILE_TRANSFER_NODE_INVOKE_COMMANDS.includes(e.command))return{ok:false,code:`UNSUPPORTED_COMMAND`,message:`unsupported file-transfer command`};const t=e.command;const n=t;const r=asOptionalRecord(e.params)??{};const i=typeof r.path===`string`?r.path:``;const a=e.node?.displayName;const o=Date.now();const s=bindFileTransferAudit({op:n,nodeId:e.nodeId,nodeDisplayName:a,requestedPath:i},o);if(!i)return{ok:false,code:`INVALID_PARAMS`,message:`${n} path required`};try{validateFetchMaxBytesParam(t,r)}catch(e){return{ok:false,code:`INVALID_PARAMS`,message:e instanceof Error?e.message:String(e)}}const c=await requestApproval({ctx:e,op:n,kind:commandKind(t),path:i,startedAt:o});if(!c.ok)return{ok:false,code:c.code,message:c.message};let l;try{const{followSymlinks:e,maxBytes:n}=c;l={...r,followSymlinks:e&&r.followSymlinks!==false};delete l.preflightOnly;delete l.expectedCanonicalPath;delete l.expectedBinding;if(t===`file.create`)Object.assign(l,readFileCreateMetadata(r,n));else if(t===`file.fetch`){const e=readFileFetchBinaryMaxBytes(r);l.maxBytes=readMaxBytes({value:r.maxBytes,defaultValue:FILE_FETCH_DEFAULT_MAX_BYTES,hardMax:e??16777216,policyMax:n})}else if(t===`dir.fetch`)l.maxBytes=readMaxBytes({value:r.maxBytes,defaultValue:DIR_FETCH_DEFAULT_MAX_BYTES,hardMax:DIR_FETCH_HARD_MAX_BYTES,policyMax:n})}catch(e){return{ok:false,code:`INVALID_PARAMS`,message:e instanceof Error?e.message:String(e)}}const u=await runPathPreflight({ctx:e,op:n,kind:commandKind(t),authorization:c,params:l,requestedPath:i,startedAt:o});if(!u.ok)return u.result;l.expectedCanonicalPath=u.canonicalPath;l.expectedBinding=u.binding;const d=await e.invokeNode({params:l});if(!d.ok){await s({decision:`error`,errorCode:d.code,errorMessage:d.message});return{ok:false,code:d.code,message:`${n} failed: ${d.message}`,details:d.details,unavailable:true}}const f=asNullableRecord(d.payload);if(f?.ok===false){await s({canonicalPath:typeof f.canonicalPath===`string`?f.canonicalPath:void 0,decision:`error`,errorCode:typeof f.code===`string`?f.code:void 0,errorMessage:typeof f.message===`string`?f.message:void 0});return d}const p=f&&typeof f.path===`string`?f.path:``;if(!p)return policyDeniedResult({op:n,code:`CANONICAL_PATH_MISSING`,message:`node result did not return a resolved path`});if(u.canonicalPath!==p)return policyDeniedResult({op:n,code:`CANONICAL_PATH_CHANGED`,message:`the resolved path changed after preflight; refusing the result`,details:{path:p}});const m=await validateCanonicalAuthorization({ctx:e,op:n,kind:commandKind(t),authorization:c,requestedPath:i,canonicalPath:p,startedAt:o});if(m)return m;let h;if(t===`dir.fetch`){const t=await verifyDirFetchArchive(f);if(!t.ok){await s({canonicalPath:p,decision:`error`,errorCode:t.code,reason:t.reason});return policyDeniedResult({op:n,code:t.code,message:`${t.reason}; refusing archive transfer`,details:{path:p,reason:t.reason}})}const r=await validateDirFetchEntries({ctx:e,op:n,authorization:c,requestedPath:i,canonicalPath:p,entries:t.entries,startedAt:o,phase:`archive`});if(r)return r;h={sizeBytes:t.sizeBytes,sha256:t.sha256}}let g;if(c.persist)try{await persistLiteralGrant({nodeId:e.nodeId,command:t,requestedPath:i,canonicalPath:p,pendingReapprovalSelector:c.pendingReapprovalSelector})}catch(e){g=`The transfer succeeded, but the standing approval was not saved. Run the command again and choose allow-always, or use allow-once.`;await s({canonicalPath:p,decision:`error`,errorCode:`APPROVAL_PERSIST_FAILED`,reason:`standing approval persistence failed: ${String(e)}`})}await s({canonicalPath:p,decision:`allowed`,sizeBytes:readAuditSizeBytes(t,f,h?.sizeBytes),sha256:t===`dir.fetch`?h?.sha256:typeof f?.sha256===`string`?f.sha256:void 0});return g&&f?{ok:true,payload:{...f,standingApprovalWarning:g}}:d}function createFileTransferNodeInvokePolicy(){return{commands:[...FILE_TRANSFER_NODE_INVOKE_COMMANDS],handle:handleFileTransferInvoke}}export{createFileTransferNodeInvokePolicy};