@squidcloud/backend 1.0.492 → 1.0.494

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:()=>j,SourceGitCommandError:()=>k,SourceGitCredentialHelper:()=>st,SourceProviderError:()=>n,buildSourceGitEnvironment:()=>Z,buildSourceGitInvocation:()=>tt,buildSourceGitNsjailArguments:()=>Y,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=`${y({alg:"RS256",typ:"JWT"})}.${y({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 y(t){return Buffer.from(JSON.stringify(t)).toString("base64url")}const C=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",$=65532,x=["COMSPEC","HOME","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","WINDIR"],F=["GIT_ASKPASS","GIT_SSL_CAINFO","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME"],M=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 k extends Error{constructor(t){super(`SOURCE_GIT_${t.toUpperCase().replaceAll("-","_")}`),this.kind=t,this.name="SourceGitCommandError"}}class j{constructor(t,e=function(){return"win32"===process.platform?"git.exe":"/usr/bin/git"}(),r=nt()){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(ot),"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 k("aborted");let r;try{const n="linux"===process.platform?e.sandboxRootDirectory:void 0;n?(X(n),await Promise.all([q(g),q(`${V}${this.executable}`),q(`${V}${K}`),...this.fileLimitExecutable?[q(`${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 k("aborted");const s=Z(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=>Q(t,n)),c=e.cwd?function(t,e){o((0,b.isAbsolute)(t),"SOURCE_CONFIGURATION_INVALID");const r=Q(t,e);return o(z(r),"SOURCE_CONFIGURATION_INVALID"),r}(e.cwd,n):v,_=Y({environment:s,invocation:tt(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:W(process.getgid?.()),tenantUid:W(process.getuid?.()),timeoutMs:e.timeoutMs,workingDirectory:c,workspaceSource:n}),u=(0,C.spawn)(g,_,{detached:!0,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await et(u,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}const a=tt(this.executable,[...this.fixedArguments(e.mode,i),...t],e.maxFileBytes,process.platform,this.fileLimitExecutable),I=(0,C.spawn)(a.executable,a.arguments,{cwd:e.cwd,detached:"win32"!==process.platform,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await et(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","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 Y(t){o(Number.isSafeInteger(t.timeoutMs)&&t.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(t.maxFileBytes)&&t.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),X(t.workspaceSource),J(t.tenantUid),J(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(z(n),"SOURCE_CONFIGURATION_INVALID");const i=["--mode","o",..."remote"===t.mode?["--disable_clone_newnet"]:[],"--chroot",V,"--cwd",n,"--user",`${$}:${t.tenantUid}:1`,"--group",`${$}:${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=${$},gid=${$}`,"--mount",`none:/tmp:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${$},gid=${$}`,"--bindmount","/dev/null:/dev/null","--bindmount_ro","/dev/urandom:/dev/urandom","--disable_proc","--bindmount_ro",`${H}:${H}`];for(const e of Object.keys(t.environment).sort())o(M.has(e),"SOURCE_CONFIGURATION_INVALID"),i.push("--env",e);return i.push("--",t.invocation.executable,...t.invocation.arguments),i}function Q(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 z(t){return t===b.posix.normalize(t)&&(t===v||t.startsWith(`${v}/`))}async function q(t){o(G(await(0,D.lstat)(t)),"SOURCE_SANDBOX_UNAVAILABLE")}function W(t){return o(void 0!==t,"SOURCE_SANDBOX_UNAVAILABLE"),J(t),t}function J(t){o(Number.isSafeInteger(t)&&t>=0,"SOURCE_SANDBOX_UNAVAILABLE")}function X(t){o((0,b.isAbsolute)(t)&&!t.includes("\0")&&!t.includes(":")&&!/[\r\n]/.test(t),"SOURCE_CONFIGURATION_INVALID")}function Z(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 x){const n=t?.[r]??e[r];void 0!==n&&(o[r]=n)}for(const e of F){const r=t?.[e];void 0!==r&&(o[e]=r)}return o}function tt(t,e,r,n=process.platform,i=nt(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 et(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 rt(t);e.push(o)};t.stdout?.on("data",t=>l(s,t)),t.stderr?.on("data",t=>l(a,t));const E=()=>{c=!0,rt(t)};n?.addEventListener("abort",E,{once:!0}),n?.aborted&&E();const T=setTimeout(()=>{u=!0,rt(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 k("resource-limit");if(c)throw new k("aborted");if(u)throw new k("transient");if(r)throw new k("transient");if(0===e)return{stdout:Buffer.concat(s)};if("SIGXFSZ"===o)throw new k("resource-limit");if("SIGKILL"===o)throw new k("transient");throw new k(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")))}finally{clearTimeout(T),n?.removeEventListener("abort",E)}}function rt(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 ot(t){return t.length<=32768&&!t.includes("\0")&&!/[\r\n]/.test(t)}function nt(t=process.platform){return"linux"===t?"/usr/bin/prlimit":void 0}const it=require("node:os");class st{async withEnvironment(t,e,r){const o=await(0,D.mkdtemp)((0,b.join)((0,it.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 at=exports;for(var It in e)at[It]=e[It];e.__esModule&&Object.defineProperty(at,"__esModule",{value:!0})})();
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:()=>j,SourceGitCommandError:()=>k,SourceGitCredentialHelper:()=>st,SourceProviderError:()=>n,buildSourceGitEnvironment:()=>Z,buildSourceGitInvocation:()=>tt,buildSourceGitNsjailArguments:()=>Y,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=`${y({alg:"RS256",typ:"JWT"})}.${y({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 y(t){return Buffer.from(JSON.stringify(t)).toString("base64url")}const C=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",$=65532,x=["COMSPEC","HOME","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","WINDIR"],F=["GIT_ASKPASS","GIT_SSL_CAINFO","SQUID_GIT_PASSWORD","SQUID_GIT_USERNAME"],M=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 k extends Error{constructor(t){super(`SOURCE_GIT_${t.toUpperCase().replaceAll("-","_")}`),this.kind=t,this.name="SourceGitCommandError"}}class j{constructor(t,e=function(){return"win32"===process.platform?"git.exe":"/usr/bin/git"}(),r=nt()){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(ot),"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 k("aborted");let r;try{const n="linux"===process.platform?e.sandboxRootDirectory:void 0;n?(X(n),await Promise.all([q(g),q(`${V}${this.executable}`),q(`${V}${K}`),...this.fileLimitExecutable?[q(`${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 k("aborted");const s=Z(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=>Q(t,n)),c=e.cwd?function(t,e){o((0,b.isAbsolute)(t),"SOURCE_CONFIGURATION_INVALID");const r=Q(t,e);return o(z(r),"SOURCE_CONFIGURATION_INVALID"),r}(e.cwd,n):v,_=Y({environment:s,invocation:tt(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:W(process.getgid?.()),tenantUid:W(process.getuid?.()),timeoutMs:e.timeoutMs,workingDirectory:c,workspaceSource:n}),u=(0,C.spawn)(g,_,{detached:!0,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await et(u,e.input,e.maxOutputBytes??P,e.signal,e.timeoutMs)}const a=tt(this.executable,[...this.fixedArguments(e.mode,i),...t],e.maxFileBytes,process.platform,this.fileLimitExecutable),I=(0,C.spawn)(a.executable,a.arguments,{cwd:e.cwd,detached:"win32"!==process.platform,env:s,stdio:["pipe","pipe","pipe"],windowsHide:!0});return await et(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 Y(t){o(Number.isSafeInteger(t.timeoutMs)&&t.timeoutMs>0,"SOURCE_CONFIGURATION_INVALID"),o(Number.isSafeInteger(t.maxFileBytes)&&t.maxFileBytes>0,"SOURCE_CONFIGURATION_INVALID"),X(t.workspaceSource),J(t.tenantUid),J(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(z(n),"SOURCE_CONFIGURATION_INVALID");const i=["--mode","o",..."remote"===t.mode?["--disable_clone_newnet"]:[],"--chroot",V,"--cwd",n,"--user",`${$}:${t.tenantUid}:1`,"--group",`${$}:${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=${$},gid=${$}`,"--mount",`none:/tmp:tmpfs:size=67108864,nr_inodes=16384,mode=0700,uid=${$},gid=${$}`,"--bindmount","/dev/null:/dev/null","--bindmount_ro","/dev/urandom:/dev/urandom","--disable_proc","--bindmount_ro",`${H}:${H}`];for(const e of Object.keys(t.environment).sort())o(M.has(e),"SOURCE_CONFIGURATION_INVALID"),i.push("--env",e);return i.push("--",t.invocation.executable,...t.invocation.arguments),i}function Q(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 z(t){return t===b.posix.normalize(t)&&(t===v||t.startsWith(`${v}/`))}async function q(t){o(G(await(0,D.lstat)(t)),"SOURCE_SANDBOX_UNAVAILABLE")}function W(t){return o(void 0!==t,"SOURCE_SANDBOX_UNAVAILABLE"),J(t),t}function J(t){o(Number.isSafeInteger(t)&&t>=0,"SOURCE_SANDBOX_UNAVAILABLE")}function X(t){o((0,b.isAbsolute)(t)&&!t.includes("\0")&&!t.includes(":")&&!/[\r\n]/.test(t),"SOURCE_CONFIGURATION_INVALID")}function Z(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 x){const n=t?.[r]??e[r];void 0!==n&&(o[r]=n)}for(const e of F){const r=t?.[e];void 0!==r&&(o[e]=r)}return o}function tt(t,e,r,n=process.platform,i=nt(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 et(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 rt(t);e.push(o)};t.stdout?.on("data",t=>l(s,t)),t.stderr?.on("data",t=>l(a,t));const E=()=>{c=!0,rt(t)};n?.addEventListener("abort",E,{once:!0}),n?.aborted&&E();const T=setTimeout(()=>{u=!0,rt(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 k("resource-limit");if(c)throw new k("aborted");if(u)throw new k("transient");if(r)throw new k("transient");if(0===e)return{stdout:Buffer.concat(s)};if("SIGXFSZ"===o)throw new k("resource-limit");if("SIGKILL"===o)throw new k("transient");throw new k(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")))}finally{clearTimeout(T),n?.removeEventListener("abort",E)}}function rt(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 ot(t){return t.length<=32768&&!t.includes("\0")&&!/[\r\n]/.test(t)}function nt(t=process.platform){return"linux"===t?"/usr/bin/prlimit":void 0}const it=require("node:os");class st{async withEnvironment(t,e,r){const o=await(0,D.mkdtemp)((0,b.join)((0,it.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 at=exports;for(var It in e)at[It]=e[It];e.__esModule&&Object.defineProperty(at,"__esModule",{value:!0})})();