openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 5.09 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{c as redactSensitiveText}from"./redact-BT59pdZ_.mjs";import{p as AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER}from"./auth-rate-limit-CJ17nIGS.mjs";import{n as withSerializedRateLimitAttempt}from"./rate-limit-attempt-serialization-CLMEob1y.mjs";import{t as sendJson}from"./http-json-g_k96dZ_.mjs";import{v as watchClientDisconnect}from"./http-common-kI7-c_LU.mjs";import{t as ArtifactTransferBusyError}from"./artifact-transfer-service-Dq84sJgK.mjs";import{Transform}from"node:stream";import{pipeline as pipeline$1}from"node:stream/promises";
//!src/gateway/worker-environments/artifact-transfer-http.ts
const SHA256_PATTERN=/^[a-f0-9]{64}$/u;function sendOpaqueNotFound(e){sendJson(e,404,{error:`not_found`})}function streamInterruptionReason(e,t,n){const r=(e instanceof Error?e.message:String(e)).replaceAll(t,`[redacted]`).replaceAll(n,`[artifact]`).replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/giu,`[url]`).replace(/(["'])[^"'<>]*[\\/][^"'<>]*\1/gu,`[path]`).replace(/[^\s"'<>(),;=]*[\\/][^\s"'<>(),;]*/gu,`[path]`);const i=redactSensitiveText(r,{mode:`tools`}).replace(/\s+/gu,` `).trim();return`stream error (${truncateUtf16Safe(i||`unknown error`,240)})`}async function handleArtifactTransferHttpRequest(e){const t=URL.parse(e.req.url??`/`,`http://localhost`);if(!t||e.classifyPath(t.pathname)===`outside`)return false;e.res.setHeader(`Cache-Control`,`no-store`);const n=e.routePrefix;const r=t.pathname.startsWith(n)?t.pathname.slice(n.length):``;if(e.req.method!==`GET`||!SHA256_PATTERN.test(r)||t.search||t.hash){sendOpaqueNotFound(e.res);return true}return handleWorkerTransferHttpRequest(e,t=>e.callback?.({req:e.req,res:e.res,artifactKey:r,bearer:t}))}async function handleWorkerTransferHttpRequest(e,t){const n=normalizeOptionalString(e.req.headers.authorization);const r=n?.toLowerCase().startsWith(`bearer `)?normalizeOptionalString(n.slice(7)):void 0;const i=await withSerializedRateLimitAttempt({ip:e.clientIp,scope:AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER,run:async()=>{const n=e.rateLimiter?.check(e.clientIp,AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER);if(n&&!n.allowed)return{kind:`rate-limited`,retryAfterMs:n.retryAfterMs};const i=r?t(r):void 0;const a=i?await i:{kind:`unauthorized`};if(a.kind===`unauthorized`)e.rateLimiter?.recordFailure(e.clientIp,AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER);else e.rateLimiter?.reset(e.clientIp,AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER);return a}});if(i.kind===`rate-limited`){if(i.retryAfterMs>0)e.res.setHeader(`Retry-After`,String(Math.ceil(i.retryAfterMs/1e3)));sendJson(e.res,429,{error:`rate_limited`});return true}if(i.kind===`unauthorized`){sendOpaqueNotFound(e.res);return true}await i.handle();return true}function createArtifactTransferHttpCallback(e){return async({req:t,res:n,artifactKey:r,bearer:i})=>{let a;try{a=e.authorize({token:i,artifactKey:r})}catch(e){if(!(e instanceof ArtifactTransferBusyError))throw e;return{kind:`authorized`,handle:()=>sendJson(n,503,{error:`transfer_in_progress`})}}if(!a)return{kind:`unauthorized`};const{capability:o}=a;return{kind:`authorized`,handle:async()=>{let r=0;let i;const s=e.authorizationSignal(a);const recordAuthorityClosure=()=>{i??=`authority closed (${o.revocationReason??`authorization lost`})`};s.addEventListener(`abort`,recordAuthorityClosure,{once:true});if(s.aborted)recordAuthorityClosure();const c=new AbortController;const l=watchClientDisconnect(t,n,c,()=>{i??=`client disconnected`});const u=AbortSignal.any([s,c.signal]);let d;try{const s=await e.openFile(a);d=s?.handle;if(!s||u.aborted||!e.isAuthorizationCurrent(a)){sendOpaqueNotFound(n);return}const c=t.headers.range;const l=c===void 0?0:Number(/^bytes=(\d+)-$/u.exec(c)?.[1]);if(c!==void 0&&(!Number.isSafeInteger(l)||l>=s.bytes)){n.setHeader(`Content-Range`,`bytes */${s.bytes}`);sendJson(n,416,{error:`range_not_satisfiable`});return}r=l;const f=new Transform({transform(t,n,i){if(!e.isAuthorizationCurrent(a)){i(/* @__PURE__ */ new Error(`Worker artifact transfer authority closed`));return}r+=t.length;try{o.onProgress?.(r)}catch{}i(null,t)}});n.writeHead(c===void 0?200:206,{"content-type":`application/octet-stream`,"content-length":String(s.bytes-l),"accept-ranges":`bytes`,...c===void 0?{}:{"content-range":`bytes ${l}-${s.bytes-1}/${s.bytes}`},"x-openclaw-content-sha256":s.sha256});const p=s.handle.createReadStream({start:l,end:s.bytes-1,autoClose:false});p.once(`error`,e=>{i??=streamInterruptionReason(e,o.token,o.artifact.tarballPath)});await pipeline$1(p,f,n,{signal:u})}catch(e){i??=streamInterruptionReason(e,o.token,o.artifact.tarballPath);if(!n.headersSent&&!n.destroyed)sendOpaqueNotFound(n);else if(!n.destroyed)n.destroy()}finally{l();s.removeEventListener(`abort`,recordAuthorityClosure);if(r!==o.artifact.tarballBytes||!n.writableFinished)try{o.onInterrupted?.(r,i??`stream error`)}catch{}try{await d?.close()}finally{e.finish(a)}}}}}}export{handleArtifactTransferHttpRequest as n,handleWorkerTransferHttpRequest as r,createArtifactTransferHttpCallback as t};