@squidcloud/backend 1.0.504 → 1.0.505
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";const t={d:(e,r)=>{if(Array.isArray(r))for(var o=0;o<r.length;){var n=r[o++],i=r[o++];t.o(e,n)?0===i&&o++:0===i?Object.defineProperty(e,n,{enumerable:!0,value:r[o++]}):Object.defineProperty(e,n,{enumerable:!0,get:i})}else for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}};let e={};t.r(e),t.d(e,{BitbucketCloudClient:()=>a,GitHubAppClient:()=>O,SourceGitCommand:()=>Y,SourceGitCommandError:()=>j,SourceGitCredentialHelper:()=>at,SourceProviderError:()=>n,buildSourceGitEnvironment:()=>tt,buildSourceGitInvocation:()=>et,buildSourceGitNsjailArguments:()=>Q,isTrustedBoundaryExecutable:()=>G});let r=t=>new Error(t);function o(t,e,...o){t||function(t,...e){const o=function(t){return void 0===t?"":"string"==typeof t?t:t()}(t);if("object"==typeof o)throw o;throw r(o||"Assertion error",...e)}(e,...o)}class n extends Error{constructor(t,e){super(e),this.classification=t,this.name="SourceProviderError"}}const i="https://api.bitbucket.org",s="bitbucket.org";class a{constructor(t,e=fetch){this.fetchFn=e,o(t.email.trim()===t.email&&t.email.length>0,"BITBUCKET_EMAIL_INVALID"),o(t.apiToken.trim()===t.apiToken&&t.apiToken.length>0,"BITBUCKET_API_TOKEN_INVALID"),this.authorization=`Basic ${Buffer.from(`${t.email}:${t.apiToken}`).toString("base64")}`}async listRepositories(t,e){E(e),l(t,"BITBUCKET_WORKSPACE_INVALID");const r=[],n=new Set,s=new Set,a=new Set,_=`/2.0/repositories/${t}`;let u=`${i}${_}?pagelen=100`,T=0;for(;u;){o(T<100,"BITBUCKET_PAGINATION_LIMIT_EXCEEDED"),T+=1,o(!a.has(u),"BITBUCKET_PAGINATION_CYCLE"),a.add(u);const i=await this.request(u,e);E(e),o(Array.isArray(i.values),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");for(const e of i.values){const i=I(e,t),a=i.providerRepositoryId.toLowerCase(),c=i.fullName.toLowerCase();o(!n.has(a)&&!s.has(c),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),n.add(a),s.add(c),r.push(i)}u=c(i.next,_)}return E(e),r}async getRepository(t,e,r){E(r),l(t,"BITBUCKET_WORKSPACE_INVALID"),l(e,"BITBUCKET_REPOSITORY_SLUG_INVALID");const n=await this.request(`${i}/2.0/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}`,r);E(r);const s=I(n,t);return o(s.fullName.toLowerCase()===`${t}/${e}`.toLowerCase(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),s}async request(t,e){let r;try{r=await this.fetchFn(t,{headers:{Accept:"application/json",Authorization:this.authorization},redirect:"manual",signal:e})}catch(t){if(e?.aborted||T(t))throw new n("aborted","BITBUCKET_REQUEST_ABORTED");throw new n("transient","BITBUCKET_PROVIDER_UNAVAILABLE")}if(r.redirected||r.status>=300&&r.status<400)throw new Error("BITBUCKET_REDIRECT_REJECTED");if(!r.ok)throw 401===(i=r.status)?new n("authentication","BITBUCKET_AUTHENTICATION_FAILED"):403===i?new n("authentication","BITBUCKET_PERMISSION_DENIED"):429===i?new n("transient","BITBUCKET_RATE_LIMITED"):i>=500?new n("transient","BITBUCKET_PROVIDER_UNAVAILABLE"):new n("repository-unavailable",404===i?"BITBUCKET_NOT_FOUND":"BITBUCKET_REQUEST_FAILED");var i;try{const t=await r.json();return E(e),o(!!t&&"object"==typeof t&&!Array.isArray(t),"BITBUCKET_RESPONSE_INVALID"),t}catch(t){if(e?.aborted||T(t))throw new n("aborted","BITBUCKET_REQUEST_ABORTED");if(t instanceof Error&&t.message.startsWith("BITBUCKET_"))throw t;throw new Error("BITBUCKET_RESPONSE_INVALID")}}}function I(t,e){o(!!t&&"object"==typeof t&&!Array.isArray(t),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const r=t;o("string"==typeof r.uuid&&r.uuid.trim()===r.uuid&&r.uuid.length>0,"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof r.full_name&&/^[^/\s]+\/[^/\s]+$/.test(r.full_name)&&r.full_name.split("/")[0]?.toLowerCase()===e.toLowerCase(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const n=u(r.links,"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),i=n.clone;o(Array.isArray(i),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const s=i.filter(t=>"https"===function(t){return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}(t)?.name);o(1===s.length,"BITBUCKET_REPOSITORY_URL_INVALID");const a=_(u(s[0],"BITBUCKET_REPOSITORY_URL_INVALID").href,r.full_name,!0),I=_(u(n.html,"BITBUCKET_REPOSITORY_URL_INVALID").href,r.full_name,!1),c=r.mainbranch,l=null===c?"":function(t){return o("string"==typeof t&&t.trim(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),t}(u(c,"BITBUCKET_REPOSITORY_RESPONSE_INVALID").name);return{cloneUrl:a,defaultBranch:l,fullName:r.full_name,provider:"bitbucket",providerRepositoryId:r.uuid,webUrl:I}}function c(t,e){if(null==t)return;let r;o("string"==typeof t&&t,"BITBUCKET_PAGINATION_URL_INVALID");try{r=new URL(t)}catch{throw new Error("BITBUCKET_PAGINATION_URL_INVALID")}const n=/^https:\/\/(?:[^/@]+@)?api\.bitbucket\.org:\d+(?:\/|$)/i.test(t);return o(!("https:"!==r.protocol||"api.bitbucket.org"!==r.hostname||n||r.username||r.password||r.hash||r.pathname!==e),"BITBUCKET_PAGINATION_URL_INVALID"),r.toString()}function _(t,e,r){if("string"!=typeof t)throw new Error("BITBUCKET_REPOSITORY_URL_INVALID");let n;try{n=new URL(t)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const i=`/${e}${r?".git":""}`,a=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(t);return o("https:"===n.protocol&&n.hostname===s&&!a&&(r||!n.username)&&!n.password&&!n.search&&!n.hash&&n.pathname===i,"BITBUCKET_REPOSITORY_URL_INVALID"),`https://${s}${i}`}function u(t,e){return o(!!t&&"object"==typeof t&&!Array.isArray(t),e),t}function l(t,e){o("string"==typeof t&&t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),e)}function E(t){if(t?.aborted)throw new n("aborted","BITBUCKET_REQUEST_ABORTED")}function T(t){return t instanceof Error&&"AbortError"===t.name}const d=require("node:crypto"),p="https://api.github.com",S=3e5,A="2022-11-28";class O{constructor(t,e=fetch){this.fetchFn=e,this.tokenCache=new Map,N(t.appId),N(t.installationId),this.appId=t.appId,this.installationId=t.installationId,this.privateKey=function(t){o("string"==typeof t&&t.trim(),"GITHUB_PRIVATE_KEY_INVALID");const e=t.replace(/\\r\\n/g,"\n").replace(/\\n/g,"\n").replace(/\r\n/g,"\n").trim(),r=e.includes("\n")?e:function(t){const e=/^-----BEGIN (RSA )?PRIVATE KEY-----(.*?)-----END (RSA )?PRIVATE KEY-----$/s.exec(t);if(!e)return t;const r=e[1]?"RSA PRIVATE KEY":"PRIVATE KEY";return`-----BEGIN ${r}-----\n${(e[2].replace(/\s/g,"").match(/.{1,64}/g)??[]).join("\n")}\n-----END ${r}-----`}(e);try{(0,d.createPrivateKey)(r)}catch{throw new Error("GITHUB_PRIVATE_KEY_INVALID")}return r}(t.privateKey)}async createInstallationToken(t,e){m(e);const r=function(t){const e=t.repositoryIds?[...t.repositoryIds].sort((t,e)=>t-e):void 0;o(!e||e.every(t=>Number.isSafeInteger(t)&&t>0),"GITHUB_REPOSITORY_IDS_INVALID");const r=t.permissions?Object.fromEntries(Object.entries(t.permissions).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>(o("read"===e||"write"===e,"GITHUB_PERMISSIONS_INVALID"),[t,e]))):void 0;return{...e?{repository_ids:e}:{},...r?{permissions:r}:{}}}(t),n=JSON.stringify(r),i=this.tokenCache.get(n);if(i&&Date.parse(i.expiresAt)-Date.now()>S)return i;const s=await R(this.fetchFn,`${p}/app/installations/${this.installationId}/access_tokens`,{body:JSON.stringify(r),headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.createAppJwt()}`,"Content-Type":"application/json","X-GitHub-Api-Version":A},method:"POST",redirect:"manual",signal:e}),a=await f(s,e);m(e);const I=w(a,"token"),c=w(a,"expires_at");o(Number.isFinite(Date.parse(c)),"GITHUB_TOKEN_RESPONSE_INVALID");const _=function(t){const e=t.permissions;o(null!==e&&"object"==typeof e&&!Array.isArray(e),"GITHUB_TOKEN_RESPONSE_INVALID");const r={};for(const[t,n]of Object.entries(e))o(/^[a-z][a-z0-9_]{0,127}$/.test(t)&&("read"===n||"write"===n),"GITHUB_TOKEN_RESPONSE_INVALID"),r[t]=n;return Object.fromEntries(Object.entries(r).sort(([t],[e])=>t.localeCompare(e)))}(a),u=function(t){const e=t.repository_selection;return o("all"===e||"selected"===e,"GITHUB_TOKEN_RESPONSE_INVALID"),e}(a),l=function(t){const e=t.repositories;if(void 0===e)return[];o(Array.isArray(e),"GITHUB_TOKEN_RESPONSE_INVALID");const r=e.map(t=>(o(null!==t&&"object"==typeof t&&!Array.isArray(t)&&"id"in t&&Number.isSafeInteger(t.id)&&t.id>0,"GITHUB_TOKEN_RESPONSE_INVALID"),t.id));return o(new Set(r).size===r.length,"GITHUB_TOKEN_RESPONSE_INVALID"),r.sort((t,e)=>t-e)}(a),E={expiresAt:c,permissions:_,repositoryIds:l,repositorySelection:u,token:I};return function(t,e){e.permissions&&o(JSON.stringify(t.permissions)===JSON.stringify(e.permissions),"GITHUB_TOKEN_SCOPE_INVALID"),e.repository_ids&&o("selected"===t.repositorySelection&&t.repositoryIds.length===e.repository_ids.length&&t.repositoryIds.every((t,r)=>t===e.repository_ids?.[r]),"GITHUB_TOKEN_SCOPE_INVALID")}(E,r),Date.parse(c)-Date.now()>S&&this.tokenCache.set(n,E),E}async listInstallationRepositories(t){m(t);const{token:e}=await this.createInstallationToken({},t),r=[],n=new Set,i=new Set,s=new Set;let a=`${p}/installation/repositories?per_page=100`,I=0;for(;a;){o(I<100,"GITHUB_PAGINATION_LIMIT_EXCEEDED"),I+=1,o(!s.has(a),"GITHUB_PAGINATION_CYCLE"),s.add(a);const c=await R(this.fetchFn,a,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":A},redirect:"manual",signal:t}),_=await f(c,t);m(t);const u=_.repositories;o(Array.isArray(u),"GITHUB_REPOSITORY_RESPONSE_INVALID");for(const t of u.map(U)){o(!n.has(t.providerRepositoryId),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),n.add(t.providerRepositoryId);const e=t.fullName.toLowerCase();o(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),r.push(t)}a=B(c.headers.get("link"))}return m(t),r}createAppJwt(){const t=Math.floor(Date.now()/1e3),e=`${C({alg:"RS256",typ:"JWT"})}.${C({exp:t+600,iat:t-60,iss:this.appId})}`;return`${e}.${(0,d.sign)("RSA-SHA256",Buffer.from(e),this.privateKey).toString("base64url")}`}}function N(t){o("string"==typeof t&&/^\d+$/.test(t),"GITHUB_IDENTIFIER_INVALID")}async function f(t,e){if(t.redirected||t.status>=300&&t.status<400)throw new Error("GITHUB_REDIRECT_REJECTED");if(!t.ok)throw function(t){const{status:e}=t;return 401===e?new n("authentication","GITHUB_AUTHENTICATION_FAILED"):403===e?t.headers.has("retry-after")||"0"===t.headers.get("x-ratelimit-remaining")?new n("transient","GITHUB_RATE_LIMITED"):new n("authentication","GITHUB_PERMISSION_DENIED"):429===e?new n("transient","GITHUB_RATE_LIMITED"):e>=500?new n("transient","GITHUB_PROVIDER_UNAVAILABLE"):new n("repository-unavailable","GITHUB_REQUEST_FAILED")}(t);try{const e=await t.json();return o(!!e&&"object"==typeof e&&!Array.isArray(e),"GITHUB_RESPONSE_INVALID"),e}catch(t){if(e?.aborted||h(t))throw new n("aborted","GITHUB_REQUEST_ABORTED");if(t instanceof Error&&t.message.startsWith("GITHUB_"))throw t;throw new Error("GITHUB_RESPONSE_INVALID")}}async function R(t,e,r){try{return await t(e,r)}catch(t){if(r.signal?.aborted||h(t))throw new n("aborted","GITHUB_REQUEST_ABORTED");throw new n("transient","GITHUB_PROVIDER_UNAVAILABLE")}}function m(t){if(t?.aborted)throw new n("aborted","GITHUB_REQUEST_ABORTED")}function h(t){return t instanceof Error&&"AbortError"===t.name}function U(t){o(!!t&&"object"==typeof t&&!Array.isArray(t),"GITHUB_REPOSITORY_RESPONSE_INVALID");const e=t,r=e.id,n=e.full_name,i=e.clone_url,s=e.html_url,a=e.default_branch;return o(Number.isSafeInteger(r)&&r>0,"GITHUB_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof n&&/^[^/\s]+\/[^/\s]+$/.test(n),"GITHUB_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof a&&a.trim(),"GITHUB_REPOSITORY_RESPONSE_INVALID"),L(i,n,!0),L(s,n,!1),{cloneUrl:i,defaultBranch:a,fullName:n,provider:"github",providerRepositoryId:String(r),webUrl:s}}function L(t,e,r){if("string"!=typeof t)throw new Error("GITHUB_REPOSITORY_URL_INVALID");try{const n=new URL(t),i=`/${e}${r?".git":""}`;o(!("https:"!==n.protocol||"github.com"!==n.hostname||n.port||n.username||n.password||n.search||n.hash||n.pathname!==i),"GITHUB_REPOSITORY_URL_INVALID")}catch(t){if(t instanceof Error&&"GITHUB_REPOSITORY_URL_INVALID"===t.message)throw t;throw new Error("GITHUB_REPOSITORY_URL_INVALID")}}function B(t){if(!t)return;const e=t.split(",").map(t=>t.trim()).find(t=>/;\s*rel="?next"?/i.test(t));if(!e)return;const r=/^<([^>]+)>/.exec(e)?.[1];let n;o(r,"GITHUB_PAGINATION_URL_INVALID");try{n=new URL(r)}catch{throw new Error("GITHUB_PAGINATION_URL_INVALID")}return o(!("https:"!==n.protocol||"api.github.com"!==n.hostname||n.username||n.password||n.port||n.hash||"/installation/repositories"!==n.pathname),"GITHUB_PAGINATION_URL_INVALID"),n.toString()}function w(t,e){const r=t[e];return o("string"==typeof r&&r,"GITHUB_TOKEN_RESPONSE_INVALID"),r}function C(t){return Buffer.from(JSON.stringify(t)).toString("base64url")}const y=require("node:child_process"),D=require("node:fs/promises"),b=require("node:path");function G(t){return t.isFile()&&0===t.uid&&0===t.gid&&!!(73&t.mode)&&!(3584&t.mode)&&!(18&t.mode)}const P=16777216,g="/usr/local/bin/nsjail",V="/opt/source-agent-rootfs",v="/workspace",K="/usr/local/bin/squid-source-git-askpass",H="/proc",$="/etc/resolv.conf",x=65532,F=["COMSPEC","HOME","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","WINDIR"],M=["GIT_ASKPASS","GIT_SSL_CAINFO","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME"],k=new Set(["GIT_ASKPASS","GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_LFS_SKIP_SMUDGE","GIT_LITERAL_PATHSPECS","GIT_NO_REPLACE_OBJECTS","GIT_OPTIONAL_LOCKS","GIT_SSL_CAINFO","GIT_TERMINAL_PROMPT","HOME","LANG","LC_ALL","PATH","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME","SSL_CERT_DIR","SSL_CERT_FILE","TMPDIR"]);class j extends Error{constructor(t,e){super(`SOURCE_GIT_${t.toUpperCase().replaceAll("-","_")}`),this.kind=t,this.exitCode=e,this.name="SourceGitCommandError"}}class Y{constructor(t,e=function(){return"win32"===process.platform?"git.exe":"/usr/bin/git"}(),r=it()){this.runtimeRootDirectory=t,this.executable=e,this.fileLimitExecutable=r,o("win32"===process.platform||(0,b.isAbsolute)(e),"SOURCE_CONFIGURATION_INVALID"),o(void 0===r||(0,b.isAbsolute)(r),"SOURCE_CONFIGURATION_INVALID")}async run(t,e){if(o(t.length>0&&t.every(nt),"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(e.timeoutMs)&&e.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(void 0===e.maxFileBytes||Number.isSafeInteger(e.maxFileBytes)&&e.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),o(void 0===e.maxOutputBytes||Number.isSafeInteger(e.maxOutputBytes)&&e.maxOutputBytes>0,"SOURCE_CONFIGURATION_INVALID"),e.signal?.aborted)throw new j("aborted");let r;try{const n="linux"===process.platform?e.sandboxRootDirectory:void 0;n?(Z(n),await Promise.all([W(g),W(`${V}${this.executable}`),W(`${V}${K}`),...this.fileLimitExecutable?[W(`${V}${this.fileLimitExecutable}`)]:[]]),r=await(0,D.mkdtemp)((0,b.join)(n,".squid-trusted-git-"))):(await(0,D.mkdir)(this.runtimeRootDirectory,{mode:448,recursive:!0}),r=await(0,D.mkdtemp)((0,b.join)(this.runtimeRootDirectory,"disabled-git-hooks-"))),o(r,"SOURCE_CONFIGURATION_INVALID");const i=n?(0,b.join)(r,"hooks"):r;if(n&&await(0,D.mkdir)(i,{mode:448}),await(0,D.chmod)(i,448),e.signal?.aborted)throw new j("aborted");const s=tt(e.environment);if(n){const i=(0,b.relative)(n,r);o(i.length>0&&!i.includes(b.sep)&&".."!==i,"SOURCE_CONFIGURATION_INVALID");const a=b.posix.join(v,i);s.GIT_ASKPASS=K,s.HOME="/home/source-agent",s.PATH="/usr/local/bin:/usr/bin:/bin",s.SSL_CERT_DIR="/etc/ssl/certs",s.SSL_CERT_FILE="/etc/ssl/certs/ca-certificates.crt",s.TMPDIR="/tmp",delete s.COMSPEC,delete s.SystemRoot,delete s.WINDIR,s.GIT_SSL_CAINFO&&(s.GIT_SSL_CAINFO=await async function(t,e,r){o((0,b.isAbsolute)(t)&&!t.includes("\0"),"SOURCE_CONFIGURATION_INVALID");const n=await(0,D.lstat)(t);o(n.isFile()&&n.size>0&&n.size<=16777216,"SOURCE_CONFIGURATION_INVALID");const i="ca.pem",s=(0,b.join)(e,i);return await(0,D.copyFile)(t,s),await(0,D.chmod)(s,256),b.posix.join(r,i)}(s.GIT_SSL_CAINFO,r,a));const I=t.map(t=>z(t,n)),c=e.cwd?function(t,e){o((0,b.isAbsolute)(t),"SOURCE_CONFIGURATION_INVALID");const r=z(t,e);return o(q(r),"SOURCE_CONFIGURATION_INVALID"),r}(e.cwd,n):v,_=Q({environment:s,invocation:et(this.executable,[...this.fixedArguments(e.mode,b.posix.join(a,"hooks")),...I],e.maxFileBytes,process.platform,this.fileLimitExecutable),maxFileBytes:e.maxFileBytes??10737418240,mode:e.mode,tenantGid:J(process.getgid?.()),tenantUid:J(process.getuid?.()),timeoutMs:e.timeoutMs,workingDirectory:c,workspaceSource:n}),u=(0,y.spawn)(g,_,{detached:!0,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await rt(u,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}const a=et(this.executable,[...this.fixedArguments(e.mode,i),...t],e.maxFileBytes,process.platform,this.fileLimitExecutable),I=(0,y.spawn)(a.executable,a.arguments,{cwd:e.cwd,detached:"win32"!==process.platform,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await rt(I,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}finally{r&&await(0,D.rm)(r,{force:!0,recursive:!0})}}fixedArguments(t,e){return["--no-optional-locks","-c","advice.detachedHead=false","-c","core.longpaths=true","-c",`core.hooksPath=${e}`,"-c","credential.helper=","-c","gc.autoDetach=false","-c","maintenance.autoDetach=false","-c","http.followRedirects=false","-c","core.sshCommand=false","-c","protocol.ext.allow=never","-c","protocol.file.allow="+("local"===t?"always":"never"),"-c","protocol.ssh.allow=never","-c","protocol.git.allow=never","-c","protocol.http.allow=never","-c","protocol.https.allow=always"]}}function Q(t){o(Number.isSafeInteger(t.timeoutMs)&&t.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(t.maxFileBytes)&&t.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),Z(t.workspaceSource),X(t.tenantUid),X(t.tenantGid);const e=Math.max(1,Math.ceil(t.timeoutMs/1e3)),r=Math.max(1,Math.ceil(t.maxFileBytes/1048576)),n=t.workingDirectory??v;o(q(n),"SOURCE_CONFIGURATION_INVALID");const i=["--mode","o",..."remote"===t.mode?["--disable_clone_newnet"]:[],"--chroot",V,"--cwd",n,"--user",`${x}:${t.tenantUid}:1`,"--group",`${x}:${t.tenantGid}:1`,"--hostname","squid-trusted-git","--time_limit",String(e),"--rlimit_as","4096","--rlimit_cpu",String(e),"--rlimit_fsize",String(r),"--rlimit_nofile","256","--rlimit_nproc","128","--max_cpus","2","--bindmount",`${t.workspaceSource}:${v}`,"--mount",`none:/home/source-agent:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${x},gid=${x}`,"--mount",`none:/tmp:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${x},gid=${x}`,"--bindmount","/dev/null:/dev/null","--bindmount_ro","/dev/urandom:/dev/urandom","--disable_proc","--bindmount_ro",`${H}:${H}`,..."remote"===t.mode?["--bindmount_ro",`${$}:${$}`]:[]];for(const e of Object.keys(t.environment).sort())o(k.has(e),"SOURCE_CONFIGURATION_INVALID"),i.push("--env",e);return i.push("--",t.invocation.executable,...t.invocation.arguments),i}function z(t,e){const r=(0,b.relative)(e,t);return""===r?v:function(t){return".."!==t&&!t.startsWith(`..${b.sep}`)&&!(0,b.isAbsolute)(t)}(r)?b.posix.join(v,...r.split(b.sep)):t}function q(t){return t===b.posix.normalize(t)&&(t===v||t.startsWith(`${v}/`))}async function W(t){o(G(await(0,D.lstat)(t)),"SOURCE_SANDBOX_UNAVAILABLE")}function J(t){return o(void 0!==t,"SOURCE_SANDBOX_UNAVAILABLE"),X(t),t}function X(t){o(Number.isSafeInteger(t)&&t>=0,"SOURCE_SANDBOX_UNAVAILABLE")}function Z(t){o((0,b.isAbsolute)(t)&&!t.includes("\0")&&!t.includes(":")&&!/[\r\n]/.test(t),"SOURCE_CONFIGURATION_INVALID")}function tt(t,e=process.env,r=process.platform){const o={GIT_CONFIG_GLOBAL:"win32"===r?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_LFS_SKIP_SMUDGE:"1",GIT_LITERAL_PATHSPECS:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",LANG:"C",LC_ALL:"C",PATH:e.PATH};for(const r of F){const n=t?.[r]??e[r];void 0!==n&&(o[r]=n)}for(const e of M){const r=t?.[e];void 0!==r&&(o[e]=r)}return o}function et(t,e,r,n=process.platform,i=it(n)){return"linux"!==n||void 0===r?{arguments:e,executable:t}:(o(Number.isSafeInteger(r)&&r>0&&void 0!==i&&(0,b.isAbsolute)(i),"SOURCE_CONFIGURATION_INVALID"),{arguments:[`--fsize=${r}`,"--",t,...e],executable:i})}async function rt(t,e,r,n,i){o(Number.isSafeInteger(r)&&r>0,"SOURCE_CONFIGURATION_INVALID");const s=[],a=[];let I=0,c=!1,_=!1,u=!1;const l=(e,o)=>{if(I+=o.length,I>r)return _=!0,void ot(t);e.push(o)};t.stdout?.on("data",t=>l(s,t)),t.stderr?.on("data",t=>l(a,t));const E=()=>{c=!0,ot(t)};n?.addEventListener("abort",E,{once:!0}),n?.aborted&&E();const T=setTimeout(()=>{u=!0,ot(t)},i);T.unref?.(),e?t.stdin?.end(e):t.stdin?.end();try{const{code:e,error:r,signal:o}=await function(t){return new Promise(e=>{let r;t.once("error",t=>{r=t}),t.once("close",(t,o)=>{e({code:t,...r?{error:r}:{},signal:o})})})}(t);if(_)throw new j("resource-limit");if(c)throw new j("aborted");if(u)throw new j("transient");if(r)throw new j("transient");if(0===e)return{stdout:Buffer.concat(s)};if("SIGXFSZ"===o)throw new j("resource-limit");if("SIGKILL"===o)throw new j("transient");throw new j(function(t){const e=t.toLowerCase();return e.includes("file too large")||e.includes("disk quota exceeded")||e.includes("no space left")||e.includes("resource limit")?"resource-limit":/\b429\b/.test(e)||/\b5\d\d\b/.test(e)||e.includes("could not resolve host")||e.includes("connection reset")||e.includes("rate limit")||e.includes("timed out")||e.includes("timeout")?"transient":/\b(?:401|403)\b/.test(e)||e.includes("authentication failed")||e.includes("access denied")?"authentication":/\b404\b/.test(e)||e.includes("repository not found")||e.includes("does not appear to be a git repository")?"repository-unavailable":"transient"}(Buffer.concat(a).toString("utf8")),e??void 0)}finally{clearTimeout(T),n?.removeEventListener("abort",E)}}function ot(t){if(null===t.exitCode&&null===t.signalCode){if("win32"!==process.platform&&t.pid)try{return void process.kill(-t.pid,"SIGKILL")}catch{}t.kill("SIGKILL")}}function nt(t){return t.length<=32768&&!t.includes("\0")&&!/[\r\n]/.test(t)}function it(t=process.platform){return"linux"===t?"/usr/bin/prlimit":void 0}const st=require("node:os");class at{async withEnvironment(t,e,r){const o=await(0,D.mkdtemp)((0,b.join)((0,st.tmpdir)(),`squid-source-git-${(0,d.randomBytes)(6).toString("hex")}-`));await(0,D.chmod)(o,448);const n=(0,b.join)(o,"askpass.sh");try{return await(0,D.writeFile)(n,'#!/bin/sh\ncase "$1" in\n *Username*) printf \'%s\\n\' "$SQUID_GIT_USERNAME" ;;\n *Password*) printf \'%s\\n\' "$SQUID_GIT_PASSWORD" ;;\n *) exit 1 ;;\nesac\n',{mode:448}),await r({GIT_ASKPASS:n,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",HOME:o,PATH:process.env.PATH,SQUID_GIT_PASSWORD:e,SQUID_GIT_USERNAME:t})}finally{await(0,D.rm)(o,{force:!0,maxRetries:5,recursive:!0,retryDelay:100})}}}const It=exports;for(var ct in e)It[ct]=e[ct];e.__esModule&&Object.defineProperty(It,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";const t={d:(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}};let e={};t.r(e),t.d(e,{BitbucketCloudClient:()=>a,GitHubAppClient:()=>O,SourceGitCommand:()=>Y,SourceGitCommandError:()=>j,SourceGitCredentialHelper:()=>at,SourceProviderError:()=>n,buildSourceGitEnvironment:()=>tt,buildSourceGitInvocation:()=>et,buildSourceGitNsjailArguments:()=>Q,isTrustedBoundaryExecutable:()=>G});let r=t=>new Error(t);function o(t,e,...o){t||function(t,...e){const o=function(t){return void 0===t?"":"string"==typeof t?t:t()}(t);if("object"==typeof o)throw o;throw r(o||"Assertion error",...e)}(e,...o)}class n extends Error{constructor(t,e){super(e),this.classification=t,this.name="SourceProviderError"}}const i="https://api.bitbucket.org",s="bitbucket.org";class a{constructor(t,e=fetch){this.fetchFn=e,o(t.email.trim()===t.email&&t.email.length>0,"BITBUCKET_EMAIL_INVALID"),o(t.apiToken.trim()===t.apiToken&&t.apiToken.length>0,"BITBUCKET_API_TOKEN_INVALID"),this.authorization=`Basic ${Buffer.from(`${t.email}:${t.apiToken}`).toString("base64")}`}async listRepositories(t,e){E(e),l(t,"BITBUCKET_WORKSPACE_INVALID");const r=[],n=new Set,s=new Set,a=new Set,_=`/2.0/repositories/${t}`;let u=`${i}${_}?pagelen=100`,T=0;for(;u;){o(T<100,"BITBUCKET_PAGINATION_LIMIT_EXCEEDED"),T+=1,o(!a.has(u),"BITBUCKET_PAGINATION_CYCLE"),a.add(u);const i=await this.request(u,e);E(e),o(Array.isArray(i.values),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");for(const e of i.values){const i=I(e,t),a=i.providerRepositoryId.toLowerCase(),c=i.fullName.toLowerCase();o(!n.has(a)&&!s.has(c),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),n.add(a),s.add(c),r.push(i)}u=c(i.next,_)}return E(e),r}async getRepository(t,e,r){E(r),l(t,"BITBUCKET_WORKSPACE_INVALID"),l(e,"BITBUCKET_REPOSITORY_SLUG_INVALID");const n=await this.request(`${i}/2.0/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}`,r);E(r);const s=I(n,t);return o(s.fullName.toLowerCase()===`${t}/${e}`.toLowerCase(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),s}async request(t,e){let r;try{r=await this.fetchFn(t,{headers:{Accept:"application/json",Authorization:this.authorization},redirect:"manual",signal:e})}catch(t){if(e?.aborted||T(t))throw new n("aborted","BITBUCKET_REQUEST_ABORTED");throw new n("transient","BITBUCKET_PROVIDER_UNAVAILABLE")}if(r.redirected||r.status>=300&&r.status<400)throw new Error("BITBUCKET_REDIRECT_REJECTED");if(!r.ok)throw 401===(i=r.status)?new n("authentication","BITBUCKET_AUTHENTICATION_FAILED"):403===i?new n("authentication","BITBUCKET_PERMISSION_DENIED"):429===i?new n("transient","BITBUCKET_RATE_LIMITED"):i>=500?new n("transient","BITBUCKET_PROVIDER_UNAVAILABLE"):new n("repository-unavailable",404===i?"BITBUCKET_NOT_FOUND":"BITBUCKET_REQUEST_FAILED");var i;try{const t=await r.json();return E(e),o(!!t&&"object"==typeof t&&!Array.isArray(t),"BITBUCKET_RESPONSE_INVALID"),t}catch(t){if(e?.aborted||T(t))throw new n("aborted","BITBUCKET_REQUEST_ABORTED");if(t instanceof Error&&t.message.startsWith("BITBUCKET_"))throw t;throw new Error("BITBUCKET_RESPONSE_INVALID")}}}function I(t,e){o(!!t&&"object"==typeof t&&!Array.isArray(t),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const r=t;o("string"==typeof r.uuid&&r.uuid.trim()===r.uuid&&r.uuid.length>0,"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof r.full_name&&/^[^/\s]+\/[^/\s]+$/.test(r.full_name)&&r.full_name.split("/")[0]?.toLowerCase()===e.toLowerCase(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const n=u(r.links,"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),i=n.clone;o(Array.isArray(i),"BITBUCKET_REPOSITORY_RESPONSE_INVALID");const s=i.filter(t=>"https"===function(t){return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}(t)?.name);o(1===s.length,"BITBUCKET_REPOSITORY_URL_INVALID");const a=_(u(s[0],"BITBUCKET_REPOSITORY_URL_INVALID").href,r.full_name,!0),I=_(u(n.html,"BITBUCKET_REPOSITORY_URL_INVALID").href,r.full_name,!1),c=r.mainbranch,l=null===c?"":function(t){return o("string"==typeof t&&t.trim(),"BITBUCKET_REPOSITORY_RESPONSE_INVALID"),t}(u(c,"BITBUCKET_REPOSITORY_RESPONSE_INVALID").name);return{cloneUrl:a,defaultBranch:l,fullName:r.full_name,provider:"bitbucket",providerRepositoryId:r.uuid,webUrl:I}}function c(t,e){if(null==t)return;let r;o("string"==typeof t&&t,"BITBUCKET_PAGINATION_URL_INVALID");try{r=new URL(t)}catch{throw new Error("BITBUCKET_PAGINATION_URL_INVALID")}const n=/^https:\/\/(?:[^/@]+@)?api\.bitbucket\.org:\d+(?:\/|$)/i.test(t);return o(!("https:"!==r.protocol||"api.bitbucket.org"!==r.hostname||n||r.username||r.password||r.hash||r.pathname!==e),"BITBUCKET_PAGINATION_URL_INVALID"),r.toString()}function _(t,e,r){if("string"!=typeof t)throw new Error("BITBUCKET_REPOSITORY_URL_INVALID");let n;try{n=new URL(t)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const i=`/${e}${r?".git":""}`,a=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(t);return o("https:"===n.protocol&&n.hostname===s&&!a&&(r||!n.username)&&!n.password&&!n.search&&!n.hash&&n.pathname===i,"BITBUCKET_REPOSITORY_URL_INVALID"),`https://${s}${i}`}function u(t,e){return o(!!t&&"object"==typeof t&&!Array.isArray(t),e),t}function l(t,e){o("string"==typeof t&&t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),e)}function E(t){if(t?.aborted)throw new n("aborted","BITBUCKET_REQUEST_ABORTED")}function T(t){return t instanceof Error&&"AbortError"===t.name}const d=require("node:crypto"),p="https://api.github.com",S=3e5,A="2022-11-28";class O{constructor(t,e=fetch){this.fetchFn=e,this.tokenCache=new Map,N(t.appId),N(t.installationId),this.appId=t.appId,this.installationId=t.installationId,this.privateKey=function(t){o("string"==typeof t&&t.trim(),"GITHUB_PRIVATE_KEY_INVALID");const e=t.replace(/\\r\\n/g,"\n").replace(/\\n/g,"\n").replace(/\r\n/g,"\n").trim(),r=e.includes("\n")?e:function(t){const e=/^-----BEGIN (RSA )?PRIVATE KEY-----(.*?)-----END (RSA )?PRIVATE KEY-----$/s.exec(t);if(!e)return t;const r=e[1]?"RSA PRIVATE KEY":"PRIVATE KEY";return`-----BEGIN ${r}-----\n${(e[2].replace(/\s/g,"").match(/.{1,64}/g)??[]).join("\n")}\n-----END ${r}-----`}(e);try{(0,d.createPrivateKey)(r)}catch{throw new Error("GITHUB_PRIVATE_KEY_INVALID")}return r}(t.privateKey)}async createInstallationToken(t,e){m(e);const r=function(t){const e=t.repositoryIds?[...t.repositoryIds].sort((t,e)=>t-e):void 0;o(!e||e.every(t=>Number.isSafeInteger(t)&&t>0),"GITHUB_REPOSITORY_IDS_INVALID");const r=t.permissions?Object.fromEntries(Object.entries(t.permissions).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>(o("read"===e||"write"===e,"GITHUB_PERMISSIONS_INVALID"),[t,e]))):void 0;return{...e?{repository_ids:e}:{},...r?{permissions:r}:{}}}(t),n=JSON.stringify(r),i=this.tokenCache.get(n);if(i&&Date.parse(i.expiresAt)-Date.now()>S)return i;const s=await f(this.fetchFn,`${p}/app/installations/${this.installationId}/access_tokens`,{body:JSON.stringify(r),headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.createAppJwt()}`,"Content-Type":"application/json","X-GitHub-Api-Version":A},method:"POST",redirect:"manual",signal:e}),a=await R(s,e);m(e);const I=w(a,"token"),c=w(a,"expires_at");o(Number.isFinite(Date.parse(c)),"GITHUB_TOKEN_RESPONSE_INVALID");const _=function(t){const e=t.permissions;o(null!==e&&"object"==typeof e&&!Array.isArray(e),"GITHUB_TOKEN_RESPONSE_INVALID");const r={};for(const[t,n]of Object.entries(e))o(/^[a-z][a-z0-9_]{0,127}$/.test(t)&&("read"===n||"write"===n),"GITHUB_TOKEN_RESPONSE_INVALID"),r[t]=n;return Object.fromEntries(Object.entries(r).sort(([t],[e])=>t.localeCompare(e)))}(a),u=function(t){const e=t.repository_selection;return o("all"===e||"selected"===e,"GITHUB_TOKEN_RESPONSE_INVALID"),e}(a),l=function(t){const e=t.repositories;if(void 0===e)return[];o(Array.isArray(e),"GITHUB_TOKEN_RESPONSE_INVALID");const r=e.map(t=>(o(null!==t&&"object"==typeof t&&!Array.isArray(t)&&"id"in t&&Number.isSafeInteger(t.id)&&t.id>0,"GITHUB_TOKEN_RESPONSE_INVALID"),t.id));return o(new Set(r).size===r.length,"GITHUB_TOKEN_RESPONSE_INVALID"),r.sort((t,e)=>t-e)}(a),E={expiresAt:c,permissions:_,repositoryIds:l,repositorySelection:u,token:I};return function(t,e){e.permissions&&o(JSON.stringify(t.permissions)===JSON.stringify(e.permissions),"GITHUB_TOKEN_SCOPE_INVALID"),e.repository_ids&&o("selected"===t.repositorySelection&&t.repositoryIds.length===e.repository_ids.length&&t.repositoryIds.every((t,r)=>t===e.repository_ids?.[r]),"GITHUB_TOKEN_SCOPE_INVALID")}(E,r),Date.parse(c)-Date.now()>S&&this.tokenCache.set(n,E),E}async listInstallationRepositories(t){m(t);const{token:e}=await this.createInstallationToken({},t),r=[],n=new Set,i=new Set,s=new Set;let a=`${p}/installation/repositories?per_page=100`,I=0;for(;a;){o(I<100,"GITHUB_PAGINATION_LIMIT_EXCEEDED"),I+=1,o(!s.has(a),"GITHUB_PAGINATION_CYCLE"),s.add(a);const c=await f(this.fetchFn,a,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":A},redirect:"manual",signal:t}),_=await R(c,t);m(t);const u=_.repositories;o(Array.isArray(u),"GITHUB_REPOSITORY_RESPONSE_INVALID");for(const t of u.map(U)){o(!n.has(t.providerRepositoryId),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),n.add(t.providerRepositoryId);const e=t.fullName.toLowerCase();o(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),r.push(t)}a=B(c.headers.get("link"))}return m(t),r}createAppJwt(){const t=Math.floor(Date.now()/1e3),e=`${C({alg:"RS256",typ:"JWT"})}.${C({exp:t+600,iat:t-60,iss:this.appId})}`;return`${e}.${(0,d.sign)("RSA-SHA256",Buffer.from(e),this.privateKey).toString("base64url")}`}}function N(t){o("string"==typeof t&&/^\d+$/.test(t),"GITHUB_IDENTIFIER_INVALID")}async function R(t,e){if(t.redirected||t.status>=300&&t.status<400)throw new Error("GITHUB_REDIRECT_REJECTED");if(!t.ok)throw function(t){const{status:e}=t;return 401===e?new n("authentication","GITHUB_AUTHENTICATION_FAILED"):403===e?t.headers.has("retry-after")||"0"===t.headers.get("x-ratelimit-remaining")?new n("transient","GITHUB_RATE_LIMITED"):new n("authentication","GITHUB_PERMISSION_DENIED"):429===e?new n("transient","GITHUB_RATE_LIMITED"):e>=500?new n("transient","GITHUB_PROVIDER_UNAVAILABLE"):new n("repository-unavailable","GITHUB_REQUEST_FAILED")}(t);try{const e=await t.json();return o(!!e&&"object"==typeof e&&!Array.isArray(e),"GITHUB_RESPONSE_INVALID"),e}catch(t){if(e?.aborted||h(t))throw new n("aborted","GITHUB_REQUEST_ABORTED");if(t instanceof Error&&t.message.startsWith("GITHUB_"))throw t;throw new Error("GITHUB_RESPONSE_INVALID")}}async function f(t,e,r){try{return await t(e,r)}catch(t){if(r.signal?.aborted||h(t))throw new n("aborted","GITHUB_REQUEST_ABORTED");throw new n("transient","GITHUB_PROVIDER_UNAVAILABLE")}}function m(t){if(t?.aborted)throw new n("aborted","GITHUB_REQUEST_ABORTED")}function h(t){return t instanceof Error&&"AbortError"===t.name}function U(t){o(!!t&&"object"==typeof t&&!Array.isArray(t),"GITHUB_REPOSITORY_RESPONSE_INVALID");const e=t,r=e.id,n=e.full_name,i=e.clone_url,s=e.html_url,a=e.default_branch;return o(Number.isSafeInteger(r)&&r>0,"GITHUB_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof n&&/^[^/\s]+\/[^/\s]+$/.test(n),"GITHUB_REPOSITORY_RESPONSE_INVALID"),o("string"==typeof a&&a.trim(),"GITHUB_REPOSITORY_RESPONSE_INVALID"),L(i,n,!0),L(s,n,!1),{cloneUrl:i,defaultBranch:a,fullName:n,provider:"github",providerRepositoryId:String(r),webUrl:s}}function L(t,e,r){if("string"!=typeof t)throw new Error("GITHUB_REPOSITORY_URL_INVALID");try{const n=new URL(t),i=`/${e}${r?".git":""}`;o(!("https:"!==n.protocol||"github.com"!==n.hostname||n.port||n.username||n.password||n.search||n.hash||n.pathname!==i),"GITHUB_REPOSITORY_URL_INVALID")}catch(t){if(t instanceof Error&&"GITHUB_REPOSITORY_URL_INVALID"===t.message)throw t;throw new Error("GITHUB_REPOSITORY_URL_INVALID")}}function B(t){if(!t)return;const e=t.split(",").map(t=>t.trim()).find(t=>/;\s*rel="?next"?/i.test(t));if(!e)return;const r=/^<([^>]+)>/.exec(e)?.[1];let n;o(r,"GITHUB_PAGINATION_URL_INVALID");try{n=new URL(r)}catch{throw new Error("GITHUB_PAGINATION_URL_INVALID")}return o(!("https:"!==n.protocol||"api.github.com"!==n.hostname||n.username||n.password||n.port||n.hash||"/installation/repositories"!==n.pathname),"GITHUB_PAGINATION_URL_INVALID"),n.toString()}function w(t,e){const r=t[e];return o("string"==typeof r&&r,"GITHUB_TOKEN_RESPONSE_INVALID"),r}function C(t){return Buffer.from(JSON.stringify(t)).toString("base64url")}const y=require("node:child_process"),D=require("node:fs/promises"),b=require("node:path");function G(t){return t.isFile()&&0===t.uid&&0===t.gid&&!!(73&t.mode)&&!(3584&t.mode)&&!(18&t.mode)}const P=16777216,g="/usr/local/bin/nsjail",V="/opt/source-agent-rootfs",v="/workspace",K="/usr/local/bin/squid-source-git-askpass",H="/proc",$="/etc/resolv.conf",x=65532,F=["COMSPEC","HOME","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","WINDIR"],M=["GIT_ASKPASS","GIT_SSL_CAINFO","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME"],k=new Set(["GIT_ASKPASS","GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_LFS_SKIP_SMUDGE","GIT_LITERAL_PATHSPECS","GIT_NO_REPLACE_OBJECTS","GIT_OPTIONAL_LOCKS","GIT_SSL_CAINFO","GIT_TERMINAL_PROMPT","HOME","LANG","LC_ALL","PATH","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME","SSL_CERT_DIR","SSL_CERT_FILE","TMPDIR"]);class j extends Error{constructor(t,e){super(`SOURCE_GIT_${t.toUpperCase().replaceAll("-","_")}`),this.kind=t,this.exitCode=e,this.name="SourceGitCommandError"}}class Y{constructor(t,e=function(){return"win32"===process.platform?"git.exe":"/usr/bin/git"}(),r=it()){this.runtimeRootDirectory=t,this.executable=e,this.fileLimitExecutable=r,o("win32"===process.platform||(0,b.isAbsolute)(e),"SOURCE_CONFIGURATION_INVALID"),o(void 0===r||(0,b.isAbsolute)(r),"SOURCE_CONFIGURATION_INVALID")}async run(t,e){if(o(t.length>0&&t.every(nt),"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(e.timeoutMs)&&e.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(void 0===e.maxFileBytes||Number.isSafeInteger(e.maxFileBytes)&&e.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),o(void 0===e.maxOutputBytes||Number.isSafeInteger(e.maxOutputBytes)&&e.maxOutputBytes>0,"SOURCE_CONFIGURATION_INVALID"),e.signal?.aborted)throw new j("aborted");let r;try{const n="linux"===process.platform?e.sandboxRootDirectory:void 0;n?(Z(n),await Promise.all([W(g),W(`${V}${this.executable}`),W(`${V}${K}`),...this.fileLimitExecutable?[W(`${V}${this.fileLimitExecutable}`)]:[]]),r=await(0,D.mkdtemp)((0,b.join)(n,".squid-trusted-git-"))):(await(0,D.mkdir)(this.runtimeRootDirectory,{mode:448,recursive:!0}),r=await(0,D.mkdtemp)((0,b.join)(this.runtimeRootDirectory,"disabled-git-hooks-"))),o(r,"SOURCE_CONFIGURATION_INVALID");const i=n?(0,b.join)(r,"hooks"):r;if(n&&await(0,D.mkdir)(i,{mode:448}),await(0,D.chmod)(i,448),e.signal?.aborted)throw new j("aborted");const s=tt(e.environment);if(n){const i=(0,b.relative)(n,r);o(i.length>0&&!i.includes(b.sep)&&".."!==i,"SOURCE_CONFIGURATION_INVALID");const a=b.posix.join(v,i);s.GIT_ASKPASS=K,s.HOME="/home/source-agent",s.PATH="/usr/local/bin:/usr/bin:/bin",s.SSL_CERT_DIR="/etc/ssl/certs",s.SSL_CERT_FILE="/etc/ssl/certs/ca-certificates.crt",s.TMPDIR="/tmp",delete s.COMSPEC,delete s.SystemRoot,delete s.WINDIR,s.GIT_SSL_CAINFO&&(s.GIT_SSL_CAINFO=await async function(t,e,r){o((0,b.isAbsolute)(t)&&!t.includes("\0"),"SOURCE_CONFIGURATION_INVALID");const n=await(0,D.lstat)(t);o(n.isFile()&&n.size>0&&n.size<=16777216,"SOURCE_CONFIGURATION_INVALID");const i="ca.pem",s=(0,b.join)(e,i);return await(0,D.copyFile)(t,s),await(0,D.chmod)(s,256),b.posix.join(r,i)}(s.GIT_SSL_CAINFO,r,a));const I=t.map(t=>z(t,n)),c=e.cwd?function(t,e){o((0,b.isAbsolute)(t),"SOURCE_CONFIGURATION_INVALID");const r=z(t,e);return o(q(r),"SOURCE_CONFIGURATION_INVALID"),r}(e.cwd,n):v,_=Q({environment:s,invocation:et(this.executable,[...this.fixedArguments(e.mode,b.posix.join(a,"hooks")),...I],e.maxFileBytes,process.platform,this.fileLimitExecutable),maxFileBytes:e.maxFileBytes??10737418240,mode:e.mode,tenantGid:J(process.getgid?.()),tenantUid:J(process.getuid?.()),timeoutMs:e.timeoutMs,workingDirectory:c,workspaceSource:n}),u=(0,y.spawn)(g,_,{detached:!0,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await rt(u,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}const a=et(this.executable,[...this.fixedArguments(e.mode,i),...t],e.maxFileBytes,process.platform,this.fileLimitExecutable),I=(0,y.spawn)(a.executable,a.arguments,{cwd:e.cwd,detached:"win32"!==process.platform,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await rt(I,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}finally{r&&await(0,D.rm)(r,{force:!0,recursive:!0})}}fixedArguments(t,e){return["--no-optional-locks","-c","advice.detachedHead=false","-c","core.longpaths=true","-c",`core.hooksPath=${e}`,"-c","credential.helper=","-c","gc.autoDetach=false","-c","maintenance.autoDetach=false","-c","http.followRedirects=false","-c","core.sshCommand=false","-c","protocol.ext.allow=never","-c","protocol.file.allow="+("local"===t?"always":"never"),"-c","protocol.ssh.allow=never","-c","protocol.git.allow=never","-c","protocol.http.allow=never","-c","protocol.https.allow=always"]}}function Q(t){o(Number.isSafeInteger(t.timeoutMs)&&t.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(t.maxFileBytes)&&t.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),Z(t.workspaceSource),X(t.tenantUid),X(t.tenantGid);const e=Math.max(1,Math.ceil(t.timeoutMs/1e3)),r=Math.max(1,Math.ceil(t.maxFileBytes/1048576)),n=t.workingDirectory??v;o(q(n),"SOURCE_CONFIGURATION_INVALID");const i=["--mode","o",..."remote"===t.mode?["--disable_clone_newnet"]:[],"--chroot",V,"--cwd",n,"--user",`${x}:${t.tenantUid}:1`,"--group",`${x}:${t.tenantGid}:1`,"--hostname","squid-trusted-git","--time_limit",String(e),"--rlimit_as","4096","--rlimit_cpu",String(e),"--rlimit_fsize",String(r),"--rlimit_nofile","256","--rlimit_nproc","128","--max_cpus","2","--bindmount",`${t.workspaceSource}:${v}`,"--mount",`none:/home/source-agent:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${x},gid=${x}`,"--mount",`none:/tmp:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${x},gid=${x}`,"--bindmount","/dev/null:/dev/null","--bindmount_ro","/dev/urandom:/dev/urandom","--disable_proc","--bindmount_ro",`${H}:${H}`,..."remote"===t.mode?["--bindmount_ro",`${$}:${$}`]:[]];for(const e of Object.keys(t.environment).sort())o(k.has(e),"SOURCE_CONFIGURATION_INVALID"),i.push("--env",e);return i.push("--",t.invocation.executable,...t.invocation.arguments),i}function z(t,e){const r=(0,b.relative)(e,t);return""===r?v:function(t){return".."!==t&&!t.startsWith(`..${b.sep}`)&&!(0,b.isAbsolute)(t)}(r)?b.posix.join(v,...r.split(b.sep)):t}function q(t){return t===b.posix.normalize(t)&&(t===v||t.startsWith(`${v}/`))}async function W(t){o(G(await(0,D.lstat)(t)),"SOURCE_SANDBOX_UNAVAILABLE")}function J(t){return o(void 0!==t,"SOURCE_SANDBOX_UNAVAILABLE"),X(t),t}function X(t){o(Number.isSafeInteger(t)&&t>=0,"SOURCE_SANDBOX_UNAVAILABLE")}function Z(t){o((0,b.isAbsolute)(t)&&!t.includes("\0")&&!t.includes(":")&&!/[\r\n]/.test(t),"SOURCE_CONFIGURATION_INVALID")}function tt(t,e=process.env,r=process.platform){const o={GIT_CONFIG_GLOBAL:"win32"===r?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_LFS_SKIP_SMUDGE:"1",GIT_LITERAL_PATHSPECS:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",LANG:"C",LC_ALL:"C",PATH:e.PATH};for(const r of F){const n=t?.[r]??e[r];void 0!==n&&(o[r]=n)}for(const e of M){const r=t?.[e];void 0!==r&&(o[e]=r)}return o}function et(t,e,r,n=process.platform,i=it(n)){return"linux"!==n||void 0===r?{arguments:e,executable:t}:(o(Number.isSafeInteger(r)&&r>0&&void 0!==i&&(0,b.isAbsolute)(i),"SOURCE_CONFIGURATION_INVALID"),{arguments:[`--fsize=${r}`,"--",t,...e],executable:i})}async function rt(t,e,r,n,i){o(Number.isSafeInteger(r)&&r>0,"SOURCE_CONFIGURATION_INVALID");const s=[],a=[];let I=0,c=!1,_=!1,u=!1;const l=(e,o)=>{if(I+=o.length,I>r)return _=!0,void ot(t);e.push(o)};t.stdout?.on("data",t=>l(s,t)),t.stderr?.on("data",t=>l(a,t));const E=()=>{c=!0,ot(t)};n?.addEventListener("abort",E,{once:!0}),n?.aborted&&E();const T=setTimeout(()=>{u=!0,ot(t)},i);T.unref?.(),e?t.stdin?.end(e):t.stdin?.end();try{const{code:e,error:r,signal:o}=await function(t){return new Promise(e=>{let r;t.once("error",t=>{r=t}),t.once("close",(t,o)=>{e({code:t,...r?{error:r}:{},signal:o})})})}(t);if(_)throw new j("resource-limit");if(c)throw new j("aborted");if(u)throw new j("transient");if(r)throw new j("transient");if(0===e)return{stdout:Buffer.concat(s)};if("SIGXFSZ"===o)throw new j("resource-limit");if("SIGKILL"===o)throw new j("transient");throw new j(function(t){const e=t.toLowerCase();return e.includes("file too large")||e.includes("disk quota exceeded")||e.includes("no space left")||e.includes("resource limit")?"resource-limit":/\b429\b/.test(e)||/\b5\d\d\b/.test(e)||e.includes("could not resolve host")||e.includes("connection reset")||e.includes("rate limit")||e.includes("timed out")||e.includes("timeout")?"transient":/\b(?:401|403)\b/.test(e)||e.includes("authentication failed")||e.includes("access denied")?"authentication":/\b404\b/.test(e)||e.includes("repository not found")||e.includes("does not appear to be a git repository")?"repository-unavailable":"transient"}(Buffer.concat(a).toString("utf8")),e??void 0)}finally{clearTimeout(T),n?.removeEventListener("abort",E)}}function ot(t){if(null===t.exitCode&&null===t.signalCode){if("win32"!==process.platform&&t.pid)try{return void process.kill(-t.pid,"SIGKILL")}catch{}t.kill("SIGKILL")}}function nt(t){return t.length<=32768&&!t.includes("\0")&&!/[\r\n]/.test(t)}function it(t=process.platform){return"linux"===t?"/usr/bin/prlimit":void 0}const st=require("node:os");class at{async withEnvironment(t,e,r){const o=await(0,D.mkdtemp)((0,b.join)((0,st.tmpdir)(),`squid-source-git-${(0,d.randomBytes)(6).toString("hex")}-`));await(0,D.chmod)(o,448);const n=(0,b.join)(o,"askpass.sh");try{return await(0,D.writeFile)(n,'#!/bin/sh\ncase "$1" in\n *Username*) printf \'%s\\n\' "$SQUID_GIT_USERNAME" ;;\n *Password*) printf \'%s\\n\' "$SQUID_GIT_PASSWORD" ;;\n *) exit 1 ;;\nesac\n',{mode:448}),await r({GIT_ASKPASS:n,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",HOME:o,PATH:process.env.PATH,SQUID_GIT_PASSWORD:e,SQUID_GIT_USERNAME:t})}finally{await(0,D.rm)(o,{force:!0,maxRetries:5,recursive:!0,retryDelay:100})}}}const It=exports;for(var ct in e)It[ct]=e[ct];e.__esModule&&Object.defineProperty(It,"__esModule",{value:!0})})();
|
package/dist/cjs/langgraph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";const t={d:(e,n)=>{
|
|
1
|
+
(()=>{"use strict";const t={d:(e,n)=>{for(var a in n)t.o(n,a)&&!t.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:n[a]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}};let e={};t.r(e),t.d(e,{SquidCheckpointer:()=>p,langGraph:()=>g,runLangGraphRequest:()=>u});const n=require("@squidcloud/backend");let a=t=>new Error(t);function o(t,e,...n){t||function(t,...e){const n=function(t){return void 0===t?"":"string"==typeof t?t:t()}(t);if("object"==typeof n)throw n;throw a(n||"Assertion error",...e)}(e,...n)}const r="__squidLangGraphRun__",i=require("@langchain/core/messages"),s=require("@langchain/langgraph");const c=36e5,d=require("@langchain/langgraph-checkpoint");class p extends d.BaseCheckpointSaver{constructor(t){super(),this.graphId=t}async getTuple(t){const{threadId:e,checkpointNs:n,checkpointId:a}=h(t),{graphId:o}=this,r=a?await this.postUnlessNotFound("getCheckpoint",{graphId:o,threadId:e,checkpointId:a}):await this.postUnlessNotFound("getLatestCheckpoint",{graphId:o,threadId:e,checkpointNs:n});return r&&await this.toTuple(r)}async*list(t,e={}){const{threadId:n,checkpointNs:a}=h(t),{limit:o,before:r,filter:i}=e,s={graphId:this.graphId,threadId:n,checkpointNs:a,limit:i?void 0:o,beforeCheckpointId:r&&(0,d.getCheckpointId)(r)||void 0},{checkpoints:c}=await this.post("listCheckpoints",s);let p=o??1/0;for(const t of c){if(p<=0)return;const e=await this.toTuple(t),n=e.metadata??{};i&&!Object.entries(i).every(([t,e])=>n[t]===e)||(p--,yield e)}}async put(t,e,n,a){const{threadId:o,checkpointNs:r,checkpointId:i}=h(t),s={graphId:this.graphId,threadId:o,checkpointNs:r,checkpointId:e.id,checkpoint:await this.dump((0,d.copyCheckpoint)(e)),parentCheckpointId:i??null,metadata:await this.dump(n)};return await this.post("saveCheckpoint",s),{configurable:{thread_id:o,checkpoint_ns:r,checkpoint_id:e.id}}}async putWrites(t,e,n){const{threadId:a,checkpointNs:r,checkpointId:i}=h(t);o(i,"Failed to put writes: the config has no checkpoint_id");const s=await Promise.all(e.map(async([t,e],a)=>({channel:t,taskId:n,idx:d.WRITES_IDX_MAP[t]??a,value:await this.dump(e)}))),c={graphId:this.graphId,threadId:a,checkpointNs:r,checkpointId:i,writes:s};await this.post("savePendingWrites",c)}async deleteThread(t){await this.post("deleteCheckpoints",{graphId:this.graphId,threadId:t})}async toTuple(t){const{threadId:e,checkpointNs:n,checkpointId:a,parentCheckpointId:o}=t,r=t=>({configurable:{thread_id:e,checkpoint_ns:n,checkpoint_id:t}}),i=await Promise.all(t.pendingWrites.map(async({taskId:t,channel:e,value:n})=>[t,e,await this.load(n)]));return{config:r(a),checkpoint:await this.load(t.checkpoint),metadata:t.metadata?await this.load(t.metadata):void 0,parentConfig:o?r(o):void 0,pendingWrites:i}}async dump(t){const[e,n]=await this.serde.dumpsTyped(t),a=[e,{__bytes__:Buffer.from(n).toString("base64")}];return JSON.stringify(a)}async load(t){const[e,{__bytes__:n}]=JSON.parse(t);return await this.serde.loadsTyped(e,Buffer.from(n,"base64"))}async post(t,e){return await(0,n.getPassiveSquid)().rpcManager.post(`langgraph/${t}`,e)}async postUnlessNotFound(t,e){try{return await this.post(t,e)}catch(t){if(404===t.statusCode)return;throw t}}}function h(t){const e=t.configurable?.thread_id;o("string"==typeof e&&e,"The LangGraph config has no thread_id");const n=t.configurable?.checkpoint_ns;return{threadId:e,checkpointNs:"string"==typeof n?n:"",checkpointId:(0,d.getCheckpointId)(t)||void 0}}async function u(t,e){const{graphId:n,operation:a,input:o,resumePayload:r,timeoutMs:i,graphContext:d}=e,h=new p(n),u=t.compile({checkpointer:h}),g=e.threadId??("function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),f={configurable:{thread_id:g}};if("getState"!==a){const t="resume"===a&&await h.getTuple(f)?new s.Command({resume:r}):o??{},n=AbortSignal.timeout(i??c);try{const a={...f,signal:n,context:d};e.onStreamEvent?await async function(t,e,n,a){const o=await t.stream(e,{...n,streamMode:["custom","messages"],subgraphs:!0});for await(const t of o){const e=l(t);e&&a(e)}}(u,t,a,e.onStreamEvent):await u.invoke(t,a)}catch(t){if(n.aborted)return{ok:!1,errorCode:"TIMEOUT",error:`The graph run did not finish within ${i??c} ms`};throw t}}const y=await u.getState(f),m=[...y.next],k=(I=y.values)&&"object"==typeof I?JSON.parse(JSON.stringify(I)):{};var I;return"getState"===a?{ok:!0,threadId:g,state:k,next:m}:{ok:!0,threadId:g,status:m.length?"interrupted":"completed",state:k,next:m}}function l([,t,e]){if("custom"===t)return{type:"custom",data:e};if("messages"!==t)return;const[n,a]=e;if(!(0,i.isBaseMessage)(n)||!(0,i.isAIMessage)(n)||!n.text)return;const{id:o,text:r}=n,s=String(a?.langgraph_node??"");if(!(0,i.isBaseMessageChunk)(n))return{type:"message",messageId:o,node:s,text:r};const c=a?.tags;return{type:"token",messageId:o,node:s,tags:Array.isArray(c)?c.filter(t=>"string"==typeof t):[],text:r}}function g(t,e={}){return function(a,i,s){n.metadata.langGraph(t,`${a.constructor.name}:${i}`,e.description);const c=function(t,e,...n){return o(t,e,...n),t}(s.value,()=>`@langGraph can only decorate a method: ${i}`);return s.value=function(...t){const[e]=t;return(n=e)&&"object"==typeof n&&!0===n[r]?async function(t,e,n){const a=await t;return o(function(t){return"function"==typeof t?.compile}(a),()=>`@langGraph function '${e}' must return an uncompiled StateGraph, got ${function(t){return null===t?"null":"object"==typeof t?t.constructor?.name??"object":typeof t}(a)}`),await u(a,n)}(c.apply(this,[]),i,e):c.apply(this,[]);var n},s}}const f=exports;for(var y in e)f[y]=e[y];e.__esModule&&Object.defineProperty(f,"__esModule",{value:!0})})();
|