@stacksjs/ts-cloud 0.9.4 → 0.10.0
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.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-08c0pzkb.js +1 -0
- package/dist/bin/chunk-12210qvj.js +1 -0
- package/dist/bin/chunk-1v6bt68w.js +6 -0
- package/dist/bin/chunk-35ttwn26.js +70 -0
- package/dist/bin/chunk-3r3be05z.js +1 -0
- package/dist/bin/chunk-41yqpdv7.js +2 -0
- package/dist/bin/chunk-5rv31chh.js +1 -0
- package/dist/bin/chunk-6eat8ezk.js +2 -0
- package/dist/bin/chunk-6gktf2m2.js +1 -0
- package/dist/bin/chunk-6zjy949y.js +141 -0
- package/dist/bin/chunk-7wzdaqh6.js +2 -0
- package/dist/bin/chunk-80ar3aty.js +1 -0
- package/dist/bin/chunk-8rwhsp5b.js +2 -0
- package/dist/bin/chunk-936vp7dx.js +44 -0
- package/dist/bin/chunk-9px3rg4a.js +4 -0
- package/dist/bin/{chunk-rxcvf10f.js → chunk-anm3ae6z.js} +129 -129
- package/dist/bin/{chunk-tx0tqq2k.js → chunk-axvr7dwa.js} +6 -6
- package/dist/bin/chunk-b0hj9m5e.js +2 -0
- package/dist/bin/{chunk-mh0kdzqp.js → chunk-b2ymh8k0.js} +1 -1
- package/dist/bin/chunk-b35989e3.js +50 -0
- package/dist/bin/chunk-c2b6nk0q.js +37 -0
- package/dist/bin/chunk-ckxpgwxw.js +3 -0
- package/dist/bin/chunk-d6zzgvtn.js +92 -0
- package/dist/bin/chunk-da8zpf82.js +1 -0
- package/dist/bin/chunk-ddmjjstg.js +1 -0
- package/dist/bin/chunk-dhhz4zyj.js +1 -0
- package/dist/bin/chunk-dj9a67c3.js +9 -0
- package/dist/bin/chunk-ds1z880f.js +1 -0
- package/dist/bin/chunk-dvkj4k6h.js +111 -0
- package/dist/bin/chunk-eh40fpvj.js +1 -0
- package/dist/bin/chunk-ey9fagrr.js +6 -0
- package/dist/bin/chunk-ezftw2q4.js +1 -0
- package/dist/bin/chunk-g6a4n3rh.js +1 -0
- package/dist/bin/chunk-g90nqfgv.js +585 -0
- package/dist/bin/chunk-gs40j75w.js +1 -0
- package/dist/bin/chunk-jjjts1vt.js +1 -0
- package/dist/bin/{chunk-etrb03mt.js → chunk-jnsbzqzz.js} +30 -30
- package/dist/bin/chunk-jnx4jgw8.js +1 -0
- package/dist/bin/chunk-jt1tndm2.js +3 -0
- package/dist/bin/chunk-kybdb0ws.js +2 -0
- package/dist/bin/chunk-m3nqw76h.js +3 -0
- package/dist/bin/chunk-mn6j22zn.js +6 -0
- package/dist/bin/chunk-nb0yjkv5.js +2 -0
- package/dist/bin/chunk-pjpa4x52.js +2 -0
- package/dist/bin/chunk-pkgkfe6s.js +2 -0
- package/dist/bin/chunk-pnz5hk8n.js +60 -0
- package/dist/bin/chunk-q46zr2tv.js +1 -0
- package/dist/bin/chunk-qtdngvs8.js +1 -0
- package/dist/bin/chunk-sbejksrh.js +2 -0
- package/dist/bin/chunk-svyd4v6c.js +34 -0
- package/dist/bin/chunk-tna7ay8d.js +1 -0
- package/dist/bin/chunk-tp4c2mv1.js +1 -0
- package/dist/bin/chunk-w5d6tr2x.js +1 -0
- package/dist/bin/chunk-wewcjam5.js +1 -0
- package/dist/bin/chunk-xv4bscrm.js +1 -0
- package/dist/bin/chunk-y9eyc5pw.js +1 -0
- package/dist/bin/chunk-y9f8649w.js +512 -0
- package/dist/bin/cli.js +428 -418
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-dskvqt67.js → chunk-06jk7ba9.js} +127 -127
- package/dist/chunk-0e16qt6k.js +5 -0
- package/dist/chunk-13hxhzaz.js +34 -0
- package/dist/chunk-2p89vt3b.js +2 -0
- package/dist/{chunk-xt3s24vr.js → chunk-77t2ctwn.js} +1 -1
- package/dist/chunk-88z37ey4.js +114 -0
- package/dist/chunk-8c4715hz.js +2 -0
- package/dist/chunk-9a22225r.js +60 -0
- package/dist/chunk-as6by62d.js +1 -0
- package/dist/chunk-cd0zpxhf.js +44 -0
- package/dist/chunk-cp54a0qn.js +6 -0
- package/dist/chunk-d67xbk4v.js +141 -0
- package/dist/chunk-dckz9xve.js +2 -0
- package/dist/chunk-e1666vjv.js +2 -0
- package/dist/chunk-hhdx5k96.js +442 -0
- package/dist/{chunk-gahsdmxf.js → chunk-kv2ztkp4.js} +52 -52
- package/dist/chunk-nrz6zypg.js +1 -0
- package/dist/chunk-q816js1y.js +1 -0
- package/dist/chunk-qh9ep11z.js +704 -0
- package/dist/chunk-rg720cqg.js +1 -0
- package/dist/chunk-snak8s7m.js +92 -0
- package/dist/chunk-vq737g82.js +1 -0
- package/dist/chunk-xd6w0c11.js +50 -0
- package/dist/chunk-xtwjt370.js +37 -0
- package/dist/chunk-y26yh5zp.js +1 -0
- package/dist/chunk-zmxffmmq.js +4 -0
- package/dist/deploy/attach-credentials.d.ts +4 -8
- package/dist/deploy/index.js +1 -1
- package/dist/dns/cloudflare.d.ts +27 -0
- package/dist/dns/godaddy.d.ts +18 -1
- package/dist/dns/index.d.ts +2 -0
- package/dist/dns/index.js +1 -1
- package/dist/dns/zone-migration.d.ts +92 -0
- package/dist/dns/zone-migration.test.d.ts +1 -0
- package/dist/drivers/hetzner/driver.d.ts +8 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/compute-provision.d.ts +14 -2
- package/dist/drivers/shared/db-provision.d.ts +3 -2
- package/dist/drivers/shared/mail-provision.d.ts +116 -0
- package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
- package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
- package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
- package/dist/drivers/shared/package-manager.d.ts +1 -0
- package/dist/drivers/shared/remote-failure.d.ts +21 -0
- package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
- package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
- package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +89 -89
- package/dist/operations/plan.d.ts +136 -0
- package/dist/operations/plan.test.d.ts +1 -0
- package/dist/operations/server-rename.d.ts +84 -0
- package/dist/operations/server-rename.test.d.ts +1 -0
- package/dist/operations/site-move.d.ts +263 -0
- package/dist/operations/site-move.test.d.ts +1 -0
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +1 -1
- package/dist/ui/applications/compose.html +5 -5
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +47 -47
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +76 -76
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +106 -106
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +33 -33
- package/dist/ui/server/logs.html +23 -23
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +27 -27
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +52 -52
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +26 -26
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +39 -39
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +54 -54
- package/dist/ui-src/src/charts.ts +17499 -12662
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +3 -3
- package/dist/bin/chunk-00kg80qg.js +0 -1
- package/dist/bin/chunk-09nwf2gy.js +0 -34
- package/dist/bin/chunk-1k5kszjp.js +0 -111
- package/dist/bin/chunk-21e0mavm.js +0 -1
- package/dist/bin/chunk-271gk1n2.js +0 -6
- package/dist/bin/chunk-2empps47.js +0 -2
- package/dist/bin/chunk-38pq971s.js +0 -2
- package/dist/bin/chunk-3gykfyq4.js +0 -37
- package/dist/bin/chunk-3vqfexc4.js +0 -70
- package/dist/bin/chunk-4vrqm9h0.js +0 -2
- package/dist/bin/chunk-598yf4bs.js +0 -1
- package/dist/bin/chunk-5ectjq0b.js +0 -1
- package/dist/bin/chunk-5erkxpt7.js +0 -512
- package/dist/bin/chunk-5mrtzemj.js +0 -1
- package/dist/bin/chunk-5n9fmabb.js +0 -1
- package/dist/bin/chunk-9knpg30y.js +0 -1
- package/dist/bin/chunk-9pvsff8g.js +0 -1
- package/dist/bin/chunk-ax9mr6wm.js +0 -44
- package/dist/bin/chunk-axhnkn5g.js +0 -2
- package/dist/bin/chunk-c1vcdgvr.js +0 -1
- package/dist/bin/chunk-ctd2vg9w.js +0 -2
- package/dist/bin/chunk-dbgffky8.js +0 -1
- package/dist/bin/chunk-ddk4rt4j.js +0 -6
- package/dist/bin/chunk-dwr30vbv.js +0 -1
- package/dist/bin/chunk-e0rkrq70.js +0 -1
- package/dist/bin/chunk-e3xrwh9z.js +0 -1
- package/dist/bin/chunk-fhc6ntvd.js +0 -2
- package/dist/bin/chunk-fpm59y25.js +0 -6
- package/dist/bin/chunk-fvbxvq6b.js +0 -1
- package/dist/bin/chunk-fy8j3y8p.js +0 -92
- package/dist/bin/chunk-fz21b57w.js +0 -1
- package/dist/bin/chunk-gavvf0pg.js +0 -141
- package/dist/bin/chunk-ggn7ax8p.js +0 -4
- package/dist/bin/chunk-gpe2prkm.js +0 -1
- package/dist/bin/chunk-h5pa5men.js +0 -2
- package/dist/bin/chunk-hm08xdxf.js +0 -2
- package/dist/bin/chunk-hzgz13nf.js +0 -1
- package/dist/bin/chunk-j703btc5.js +0 -50
- package/dist/bin/chunk-k9t9wvms.js +0 -1
- package/dist/bin/chunk-m669wtgr.js +0 -1
- package/dist/bin/chunk-m7dgskt1.js +0 -1
- package/dist/bin/chunk-mr0atd2s.js +0 -2
- package/dist/bin/chunk-mz0wbbsj.js +0 -3
- package/dist/bin/chunk-ngcyftm2.js +0 -1
- package/dist/bin/chunk-p66ptpmr.js +0 -2
- package/dist/bin/chunk-qk9qgepa.js +0 -1
- package/dist/bin/chunk-rytk89az.js +0 -60
- package/dist/bin/chunk-tga3hhwk.js +0 -6
- package/dist/bin/chunk-vek8a0w6.js +0 -1
- package/dist/bin/chunk-vm3q5gf2.js +0 -3
- package/dist/bin/chunk-y7s5r8y6.js +0 -3
- package/dist/bin/chunk-yv9sth30.js +0 -1
- package/dist/bin/chunk-zmegvjp8.js +0 -581
- package/dist/chunk-0ccta6z6.js +0 -6
- package/dist/chunk-0k1cs6pp.js +0 -1
- package/dist/chunk-1egjn203.js +0 -704
- package/dist/chunk-2wx29qga.js +0 -5
- package/dist/chunk-5m5rqmv7.js +0 -1
- package/dist/chunk-8ea5022g.js +0 -114
- package/dist/chunk-8xqn3c0w.js +0 -2
- package/dist/chunk-b4esxhmw.js +0 -2
- package/dist/chunk-b8e5wzwn.js +0 -44
- package/dist/chunk-bggt4n6e.js +0 -2
- package/dist/chunk-cwkg37rs.js +0 -37
- package/dist/chunk-gnv3r2jg.js +0 -1
- package/dist/chunk-hg3c48cp.js +0 -34
- package/dist/chunk-m5azeva3.js +0 -2
- package/dist/chunk-r3qf56b3.js +0 -92
- package/dist/chunk-sdqa9ghv.js +0 -141
- package/dist/chunk-svrvvcm7.js +0 -1
- package/dist/chunk-v0p3hpc3.js +0 -60
- package/dist/chunk-wdzjbecg.js +0 -50
- package/dist/chunk-ww8k3g7j.js +0 -1
- package/dist/chunk-xmqfc62w.js +0 -1
- package/dist/chunk-xrebj679.js +0 -435
- package/dist/chunk-y21zk0pn.js +0 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Id as a}from"./chunk-0e16qt6k.js";import"./chunk-dckz9xve.js";import"./chunk-cp54a0qn.js";import"./chunk-06jk7ba9.js";import"./chunk-77t2ctwn.js";export{a as buildAndPushServerlessImage};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import{Wh as U,Xh as L}from"./chunk-cp54a0qn.js";import{yt as K}from"./chunk-77t2ctwn.js";import*as c from"node:crypto";import{readFileSync as D}from"node:fs";import{readdir as z}from"node:fs/promises";import{join as M}from"node:path";function R(e){if(e){let r=O(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return O(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function O(e){let{existsSync:t,readFileSync:s}=K("node:fs"),{homedir:r}=K("node:os"),{join:n}=K("node:path"),i=process.env.AWS_SHARED_CREDENTIALS_FILE||n(r(),".aws","credentials");if(!t(i))return null;let o=s(i,"utf-8"),a=null,g,l,u;for(let d of o.split(`
|
|
2
|
+
`)){let y=d.trim();if(!y||y.startsWith("#")||y.startsWith(";"))continue;let h=y.match(/^\[([^\]]+)\]$/);if(h){if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:u};a=h[1],g=void 0,l=void 0,u=void 0;continue}if(a===e){let[S,...m]=y.split("="),p=m.join("=").trim();switch(S.trim().toLowerCase()){case"aws_access_key_id":g=p;break;case"aws_secret_access_key":l=p;break;case"aws_session_token":u=p;break}}}if(a===e&&g&&l)return{accessKeyId:g,secretAccessKey:l,sessionToken:u};return null}function B(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let n=new ArrayBuffer(r);return new Uint8Array(n).set(new Uint8Array(e)),n}class V{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",i=typeof e==="string"?t:e.profile,o=r?.endpoint?U({region:n,path:"/",endpoint:r.endpoint}):void 0;this.region=n,this.explicitProfile=i,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new L(r?.credentials,{profile:i,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=R(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let n=Array.isArray(r)?r:[r];for(let i of n)t.push({Name:i.Name,CreationDate:i.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
+
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
|
+
<LocationConstraint>${this.region}</LocationConstraint>
|
|
5
|
+
</CreateBucketConfiguration>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:r})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let r=s.map((n)=>n.Key);for(let n=0;n<r.length;n+=1000){let i=r.slice(n,n+1000);await this.deleteObjects(e,i)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let r={"list-type":"2","max-keys":"1000"};if(e.prefix)r.prefix=e.prefix;if(s)r["continuation-token"]=s;let n=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:r}),i=n?.ListBucketResult??n,o=i?.Contents;if(o){let g=Array.isArray(o)?o:[o];for(let l of g)t.push({Key:l.Key,LastModified:l.LastModified||"",Size:Number.parseInt(l.Size||"0"),ETag:l.ETag})}let a=i?.IsTruncated;s=a==="true"||a===!0?i?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],n=(t?.ListBucketResult??t)?.Contents;if(n){let i=Array.isArray(n)?n:[n];for(let o of i){if(e.prefix&&!o.Key?.startsWith(e.prefix))continue;if(s.push({Key:o.Key||"",LastModified:o.LastModified||"",Size:Number.parseInt(o.Size||"0"),ETag:o.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[n,i]of Object.entries(e.metadata))t[`x-amz-meta-${n}`]=i;let s=e.key.split("/").map((n)=>encodeURIComponent(n)).join("/"),r=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(r)||r instanceof Uint8Array){let n=Buffer.isBuffer(r)?r:Buffer.from(r),{accessKeyId:i,secretAccessKey:o,sessionToken:a}=this.getCredentials(),g=this.s3VirtualHost(e.bucket),l=this.objectPath(e.bucket,s),u=this.objectUrl(e.bucket,s),d=new Date,y=d.toISOString().replace(/[:-]|\.\d{3}/g,""),h=d.toISOString().slice(0,10).replace(/-/g,""),S=c.createHash("sha256").update(n).digest("hex"),m={host:g,"x-amz-date":y,"x-amz-content-sha256":S,...t};if(a)m["x-amz-security-token"]=a;let p=Object.keys(m).sort().map((f)=>`${f.toLowerCase()}:${m[f].trim()}
|
|
6
|
+
`).join(""),C=Object.keys(m).sort().map((f)=>f.toLowerCase()).join(";"),P=["PUT",l,"",p,C,S].join(`
|
|
7
|
+
`),k="AWS4-HMAC-SHA256",b=`${h}/${this.region}/s3/aws4_request`,v=[k,y,b,c.createHash("sha256").update(P).digest("hex")].join(`
|
|
8
|
+
`),q=c.createHmac("sha256",`AWS4${o}`).update(h).digest(),H=c.createHmac("sha256",q).update(this.region).digest(),E=c.createHmac("sha256",H).update("s3").digest(),w=c.createHmac("sha256",E).update("aws4_request").digest(),x=c.createHmac("sha256",w).update(v).digest("hex"),T=`${k} Credential=${i}/${b}, SignedHeaders=${C}, Signature=${x}`,A=await fetch(u,{method:"PUT",headers:{...m,Authorization:T},body:B(n)});if(!A.ok){let f=await A.text();throw Error(`S3 PUT failed: ${A.status} ${f}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${s}`,bucket:e.bucket,headers:t,body:e.body})}async getObject(e,t){let s=t.split("/").map((n)=>encodeURIComponent(n)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${s}`,bucket:e,rawResponse:!0})}async getObjectBytes(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:n}=this.getCredentials(),i=this.s3VirtualHost(e),o=t.split("/").map((f)=>encodeURIComponent(f)).join("/"),a=this.objectPath(e,o),g=this.objectUrl(e,o),l=new Date,u=l.toISOString().replace(/[:-]|\.\d{3}/g,""),d=l.toISOString().slice(0,10).replace(/-/g,""),y=c.createHash("sha256").update("").digest("hex"),h={host:i,"x-amz-date":u,"x-amz-content-sha256":y};if(n)h["x-amz-security-token"]=n;let S=Object.keys(h).sort().map((f)=>`${f.toLowerCase()}:${h[f].trim()}
|
|
9
|
+
`).join(""),m=Object.keys(h).sort().map((f)=>f.toLowerCase()).join(";"),p=["GET",a,"",S,m,y].join(`
|
|
10
|
+
`),C="AWS4-HMAC-SHA256",P=`${d}/${this.region}/s3/aws4_request`,k=[C,u,P,c.createHash("sha256").update(p).digest("hex")].join(`
|
|
11
|
+
`),b=c.createHmac("sha256",`AWS4${r}`).update(d).digest(),v=c.createHmac("sha256",b).update(this.region).digest(),q=c.createHmac("sha256",v).update("s3").digest(),H=c.createHmac("sha256",q).update("aws4_request").digest(),E=c.createHmac("sha256",H).update(k).digest("hex"),w=`${C} Credential=${s}/${P}, SignedHeaders=${m}, Signature=${E}`,x=await fetch(g,{method:"GET",headers:{...h,Authorization:w}});if(!x.ok){let f=await x.text();throw Error(`S3 GET failed: ${x.status} ${f}`)}let T=await x.arrayBuffer(),A=x.headers.get("content-length");return{body:new Uint8Array(T),contentType:x.headers.get("content-type")??void 0,contentLength:A?Number.parseInt(A,10):void 0}}async copyObject(e){let t={"x-amz-copy-source":`/${e.sourceBucket}/${e.sourceKey}`};if(e.metadataDirective)t["x-amz-metadata-directive"]=e.metadataDirective;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[s,r]of Object.entries(e.metadata))t[`x-amz-meta-${s}`]=r;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e.destinationBucket}/${e.destinationKey}`,headers:t})}async deleteObject(e,t){let s=t.split("/").map((r)=>encodeURIComponent(r)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${s}`,bucket:e})}async deleteObjects(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
12
|
+
<Delete>
|
|
13
|
+
${t.map((n)=>`<Object><Key>${n}</Key></Object>`).join(`
|
|
14
|
+
`)}
|
|
15
|
+
</Delete>`,r=c.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}async bucketExists(e){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`}),!0}catch{return!1}}async copy(e){let t=D(e.source);await this.putObject({bucket:e.bucket,key:e.key,body:t,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}async sync(e){let t=await this.listFilesRecursive(e.source);for(let s of t){if(e.exclude&&e.exclude.some((i)=>s.includes(i)))continue;if(e.include&&!e.include.some((i)=>s.includes(i)))continue;let r=s.substring(e.source.length+1),n=e.prefix?`${e.prefix}/${r}`:r;if(!e.dryRun){let i=D(s);await this.putObject({bucket:e.bucket,key:n,body:i,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}}}async delete(e,t){await this.deleteObject(e,t)}async deletePrefix(e,t){let r=(await this.list({bucket:e,prefix:t})).map((n)=>n.Key);if(r.length>0)await this.deleteObjects(e,r)}async getBucketSize(e,t){return(await this.list({bucket:e,prefix:t})).reduce((r,n)=>r+n.Size,0)}async listFilesRecursive(e){let t=[],s=await z(e,{withFileTypes:!0});for(let r of s){let n=M(e,r.name);if(r.isDirectory()){let i=await this.listFilesRecursive(n);t.push(...i)}else t.push(n)}return t}async putBucketPolicy(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:n}=this.getCredentials(),i=this.s3BaseHost(),o=typeof t==="string"?t:JSON.stringify(t),a=new Date,g=a.toISOString().replace(/[:-]|\.\d{3}/g,""),l=a.toISOString().slice(0,10).replace(/-/g,""),u=c.createHash("sha256").update(o).digest("hex"),d="/"+e,y="policy=",h={host:i,"x-amz-date":g,"x-amz-content-sha256":u,"content-type":"application/json"};if(n)h["x-amz-security-token"]=n;let S=Object.keys(h).sort().map((A)=>`${A.toLowerCase()}:${h[A].trim()}
|
|
16
|
+
`).join(""),m=Object.keys(h).sort().map((A)=>A.toLowerCase()).join(";"),p=["PUT",d,"policy=",S,m,u].join(`
|
|
17
|
+
`),C="AWS4-HMAC-SHA256",P=`${l}/${this.region}/s3/aws4_request`,k=[C,g,P,c.createHash("sha256").update(p).digest("hex")].join(`
|
|
18
|
+
`),b=c.createHmac("sha256","AWS4"+r).update(l).digest(),v=c.createHmac("sha256",b).update(this.region).digest(),q=c.createHmac("sha256",v).update("s3").digest(),H=c.createHmac("sha256",q).update("aws4_request").digest(),E=c.createHmac("sha256",H).update(k).digest("hex"),w=`${C} Credential=${s}/${P}, SignedHeaders=${m}, Signature=${E}`,x=`${this.endpointProtocol}://${i}${d}?policy=`,T=await fetch(x,{method:"PUT",headers:{...h,Authorization:w},body:o});if(!T.ok){let A=await T.text();throw Error(`Failed to put bucket policy: ${T.status} ${A}`)}}async getBucketPolicy(e){let{accessKeyId:t,secretAccessKey:s,sessionToken:r}=this.getCredentials(),n=this.s3BaseHost(),i=new Date,o=i.toISOString().replace(/[:-]|\.\d{3}/g,""),a=i.toISOString().slice(0,10).replace(/-/g,""),g=c.createHash("sha256").update("").digest("hex"),l="/"+e,u="policy=",d={host:n,"x-amz-date":o,"x-amz-content-sha256":g};if(r)d["x-amz-security-token"]=r;let y=Object.keys(d).sort().map((T)=>`${T.toLowerCase()}:${d[T].trim()}
|
|
19
|
+
`).join(""),h=Object.keys(d).sort().map((T)=>T.toLowerCase()).join(";"),S=["GET",l,"policy=",y,h,g].join(`
|
|
20
|
+
`),m="AWS4-HMAC-SHA256",p=`${a}/${this.region}/s3/aws4_request`,C=[m,o,p,c.createHash("sha256").update(S).digest("hex")].join(`
|
|
21
|
+
`),P=c.createHmac("sha256","AWS4"+s).update(a).digest(),k=c.createHmac("sha256",P).update(this.region).digest(),b=c.createHmac("sha256",k).update("s3").digest(),v=c.createHmac("sha256",b).update("aws4_request").digest(),q=c.createHmac("sha256",v).update(C).digest("hex"),H=`${m} Credential=${t}/${p}, SignedHeaders=${h}, Signature=${q}`,E=`${this.endpointProtocol}://${n}${l}?policy=`,w=await fetch(E,{method:"GET",headers:{...d,Authorization:H}});if(w.status===404)return null;if(!w.ok){let T=await w.text();throw Error(`Failed to get bucket policy: ${w.status} ${T}`)}let x=await w.text();return JSON.parse(x)}async deleteBucketPolicy(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{policy:""}})}async headBucket(e){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(t){if(t.statusCode===404)return{exists:!1};throw t}}async headObject(e,t){try{let s=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}/${t}`,returnHeaders:!0});return{ContentLength:s?.headers?.["content-length"]?parseInt(s.headers["content-length"]):void 0,ContentType:s?.headers?.["content-type"],ETag:s?.headers?.etag,LastModified:s?.headers?.["last-modified"]}}catch(s){if(s.statusCode===404)return null;throw s}}async getObjectBuffer(e,t){let s=await this.getObject(e,t);return Buffer.from(s)}async getObjectJson(e,t){let s=await this.getObject(e,t);return JSON.parse(s)}async putObjectJson(e,t,s,r){await this.putObject({bucket:e,key:t,body:JSON.stringify(s),contentType:"application/json",...r})}async getBucketVersioning(e){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
22
|
+
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
23
|
+
<Status>${t}</Status>
|
|
24
|
+
</VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:s})}async getBucketLifecycleConfiguration(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketLifecycleConfiguration(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
25
|
+
<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
26
|
+
${t.map((n)=>{let i=`<Rule><ID>${n.ID}</ID><Status>${n.Status}</Status>`;if(n.Filter)i+=`<Filter><Prefix>${n.Filter.Prefix||""}</Prefix></Filter>`;else i+="<Filter><Prefix></Prefix></Filter>";if(n.Expiration){if(n.Expiration.Days)i+=`<Expiration><Days>${n.Expiration.Days}</Days></Expiration>`;else if(n.Expiration.Date)i+=`<Expiration><Date>${n.Expiration.Date}</Date></Expiration>`}if(n.Transitions)for(let o of n.Transitions)i+=`<Transition><Days>${o.Days}</Days><StorageClass>${o.StorageClass}</StorageClass></Transition>`;if(n.NoncurrentVersionExpiration)i+=`<NoncurrentVersionExpiration><NoncurrentDays>${n.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return i+="</Rule>",i}).join("")}
|
|
27
|
+
</LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketLifecycleConfiguration(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{lifecycle:""}})}async getBucketCors(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{cors:""}}))?.CORSConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketCors(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
+
<CORSConfiguration>
|
|
29
|
+
${t.map((n)=>{let i="<CORSRule>";for(let o of n.AllowedOrigins)i+=`<AllowedOrigin>${o}</AllowedOrigin>`;for(let o of n.AllowedMethods)i+=`<AllowedMethod>${o}</AllowedMethod>`;if(n.AllowedHeaders)for(let o of n.AllowedHeaders)i+=`<AllowedHeader>${o}</AllowedHeader>`;if(n.ExposeHeaders)for(let o of n.ExposeHeaders)i+=`<ExposeHeader>${o}</ExposeHeader>`;if(n.MaxAgeSeconds)i+=`<MaxAgeSeconds>${n.MaxAgeSeconds}</MaxAgeSeconds>`;return i+="</CORSRule>",i}).join("")}
|
|
30
|
+
</CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketCors(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{cors:""}})}async getBucketEncryption(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketEncryption(e,t,s){let r=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${t}</SSEAlgorithm>`;if(s)r+=`<KMSMasterKeyID>${s}</KMSMasterKeyID>`;r+="</ApplyServerSideEncryptionByDefault>";let n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
31
|
+
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
32
|
+
<Rule>${r}</Rule>
|
|
33
|
+
</ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:n})}async deleteBucketEncryption(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{encryption:""}})}async getBucketTagging(e){try{let s=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!s)return[];return Array.isArray(s)?s:[s]}catch(t){if(t.statusCode===404)return[];throw t}}async putBucketTagging(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<Tagging>
|
|
35
|
+
<TagSet>${t.map((n)=>`<Tag><Key>${n.Key}</Key><Value>${n.Value}</Value></Tag>`).join("")}</TagSet>
|
|
36
|
+
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketTagging(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{tagging:""}})}async getObjectTagging(e,t){try{let r=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!r)return[];return Array.isArray(r)?r:[r]}catch(s){if(s.statusCode===404)return[];throw s}}async putObjectTagging(e,t,s){let n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
37
|
+
<Tagging>
|
|
38
|
+
<TagSet>${s.map((i)=>`<Tag><Key>${i.Key}</Key><Value>${i.Value}</Value></Tag>`).join("")}</TagSet>
|
|
39
|
+
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:n})}async deleteObjectTagging(e,t){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}/${t}`,queryParams:{tagging:""}})}async getBucketAcl(e){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl(e,t){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{acl:""},headers:{"x-amz-acl":t}})}async getObjectAcl(e,t){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl(e,t,s){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{acl:""},headers:{"x-amz-acl":s}})}async getBucketLocation(e){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging(e){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging(e,t,s){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
40
|
+
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
41
|
+
<LoggingEnabled>
|
|
42
|
+
<TargetBucket>${t}</TargetBucket>
|
|
43
|
+
<TargetPrefix>${s}</TargetPrefix>
|
|
44
|
+
</LoggingEnabled>
|
|
45
|
+
</BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketNotificationConfiguration(e){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration(e,t){let s="";if(t.LambdaFunctionConfigurations)for(let n of t.LambdaFunctionConfigurations){if(s+="<CloudFunctionConfiguration>",n.Id)s+=`<Id>${n.Id}</Id>`;s+=`<CloudFunction>${n.LambdaFunctionArn}</CloudFunction>`;for(let i of n.Events)s+=`<Event>${i}</Event>`;if(n.Filter?.Key?.FilterRules){s+="<Filter><S3Key>";for(let i of n.Filter.Key.FilterRules)s+=`<FilterRule><Name>${i.Name}</Name><Value>${i.Value}</Value></FilterRule>`;s+="</S3Key></Filter>"}s+="</CloudFunctionConfiguration>"}if(t.TopicConfigurations)for(let n of t.TopicConfigurations){if(s+="<TopicConfiguration>",n.Id)s+=`<Id>${n.Id}</Id>`;s+=`<Topic>${n.TopicArn}</Topic>`;for(let i of n.Events)s+=`<Event>${i}</Event>`;s+="</TopicConfiguration>"}if(t.QueueConfigurations)for(let n of t.QueueConfigurations){if(s+="<QueueConfiguration>",n.Id)s+=`<Id>${n.Id}</Id>`;s+=`<Queue>${n.QueueArn}</Queue>`;for(let i of n.Events)s+=`<Event>${i}</Event>`;s+="</QueueConfiguration>"}let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
46
|
+
<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
47
|
+
${s}
|
|
48
|
+
</NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketWebsite(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketWebsite(e,t){let s="";if(t.RedirectAllRequestsTo)s=`<RedirectAllRequestsTo>
|
|
49
|
+
<HostName>${t.RedirectAllRequestsTo.HostName}</HostName>
|
|
50
|
+
${t.RedirectAllRequestsTo.Protocol?`<Protocol>${t.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
|
|
51
|
+
</RedirectAllRequestsTo>`;else if(s=`<IndexDocument><Suffix>${t.IndexDocument}</Suffix></IndexDocument>`,t.ErrorDocument)s+=`<ErrorDocument><Key>${t.ErrorDocument}</Key></ErrorDocument>`;let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
52
|
+
<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
53
|
+
${s}
|
|
54
|
+
</WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketWebsite(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{website:""}})}async getBucketReplication(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async deleteBucketReplication(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{replication:""}})}async getPublicAccessBlock(e){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch(t){if(t.statusCode===404)return null;throw t}}async putPublicAccessBlock(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
55
|
+
<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
56
|
+
<BlockPublicAcls>${t.BlockPublicAcls??!0}</BlockPublicAcls>
|
|
57
|
+
<IgnorePublicAcls>${t.IgnorePublicAcls??!0}</IgnorePublicAcls>
|
|
58
|
+
<BlockPublicPolicy>${t.BlockPublicPolicy??!0}</BlockPublicPolicy>
|
|
59
|
+
<RestrictPublicBuckets>${t.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
|
|
60
|
+
</PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:s})}async deletePublicAccessBlock(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(e,t,s=3600){let{accessKeyId:r,secretAccessKey:n}=this.getCredentials(),i=this.s3VirtualHost(e),o=new Date,a=o.toISOString().replace(/[:-]|\.\d{3}/g,""),g=o.toISOString().slice(0,10).replace(/-/g,""),l=`${g}/${this.region}/s3/aws4_request`,u=`${r}/${l}`,d=t.split("/").map((b)=>encodeURIComponent(b)).join("/"),y=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":u,"X-Amz-Date":a,"X-Amz-Expires":s.toString(),"X-Amz-SignedHeaders":"host"}),h=["GET",this.objectPath(e,d),y.toString(),`host:${i}
|
|
61
|
+
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
62
|
+
`),S=["AWS4-HMAC-SHA256",a,l,c.createHash("sha256").update(h).digest("hex")].join(`
|
|
63
|
+
`),m=c.createHmac("sha256",`AWS4${n}`).update(g).digest(),p=c.createHmac("sha256",m).update(this.region).digest(),C=c.createHmac("sha256",p).update("s3").digest(),P=c.createHmac("sha256",C).update("aws4_request").digest(),k=c.createHmac("sha256",P).update(S).digest("hex");return y.append("X-Amz-Signature",k),`${this.endpointProtocol}://${i}${this.objectPath(e,d)}?${y.toString()}`}generatePresignedPutUrl(e,t,s,r=3600){let{accessKeyId:n,secretAccessKey:i}=this.getCredentials(),o=this.s3VirtualHost(e),a=new Date,g=a.toISOString().replace(/[:-]|\.\d{3}/g,""),l=a.toISOString().slice(0,10).replace(/-/g,""),u=`${l}/${this.region}/s3/aws4_request`,d=`${n}/${u}`,y=t.split("/").map((v)=>encodeURIComponent(v)).join("/"),h=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":d,"X-Amz-Date":g,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"content-type;host"}),S=["PUT",this.objectPath(e,y),h.toString(),`content-type:${s}
|
|
64
|
+
host:${o}
|
|
65
|
+
`,"content-type;host","UNSIGNED-PAYLOAD"].join(`
|
|
66
|
+
`),m=["AWS4-HMAC-SHA256",g,u,c.createHash("sha256").update(S).digest("hex")].join(`
|
|
67
|
+
`),p=c.createHmac("sha256",`AWS4${i}`).update(l).digest(),C=c.createHmac("sha256",p).update(this.region).digest(),P=c.createHmac("sha256",C).update("s3").digest(),k=c.createHmac("sha256",P).update("aws4_request").digest(),b=c.createHmac("sha256",k).update(m).digest("hex");return h.append("X-Amz-Signature",b),`${this.endpointProtocol}://${o}${this.objectPath(e,y)}?${h.toString()}`}async createMultipartUpload(e,t,s){let r={};if(s?.contentType)r["Content-Type"]=s.contentType;if(s?.metadata)for(let[a,g]of Object.entries(s.metadata))r[`x-amz-meta-${a}`]=g;let n=t.split("/").map((a)=>encodeURIComponent(a)).join("/"),i=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${n}`,bucket:e,queryParams:{uploads:""},headers:r});return{UploadId:(i?.InitiateMultipartUploadResult??i)?.UploadId}}async uploadPart(e,t,s,r,n){let{accessKeyId:i,secretAccessKey:o,sessionToken:a}=this.getCredentials(),g=this.s3VirtualHost(e),l=t.split("/").map((j)=>encodeURIComponent(j)).join("/"),u=this.objectPath(e,l),d=`${this.objectUrl(e,l)}?partNumber=${r}&uploadId=${encodeURIComponent(s)}`,y=new Date,h=y.toISOString().replace(/[:-]|\.\d{3}/g,""),S=y.toISOString().slice(0,10).replace(/-/g,""),m=c.createHash("sha256").update(n).digest("hex"),p={host:g,"x-amz-date":h,"x-amz-content-sha256":m};if(a)p["x-amz-security-token"]=a;let C=Object.keys(p).sort().map((j)=>`${j.toLowerCase()}:${p[j].trim()}
|
|
68
|
+
`).join(""),P=Object.keys(p).sort().map((j)=>j.toLowerCase()).join(";"),k=["PUT",u,`partNumber=${r}&uploadId=${encodeURIComponent(s)}`,C,P,m].join(`
|
|
69
|
+
`),b="AWS4-HMAC-SHA256",v=`${S}/${this.region}/s3/aws4_request`,q=[b,h,v,c.createHash("sha256").update(k).digest("hex")].join(`
|
|
70
|
+
`),H=c.createHmac("sha256",`AWS4${o}`).update(S).digest(),E=c.createHmac("sha256",H).update(this.region).digest(),w=c.createHmac("sha256",E).update("s3").digest(),x=c.createHmac("sha256",w).update("aws4_request").digest(),T=c.createHmac("sha256",x).update(q).digest("hex"),A=`${b} Credential=${i}/${v}, SignedHeaders=${P}, Signature=${T}`,f=await fetch(d,{method:"PUT",headers:{...p,Authorization:A},body:B(n)});if(!f.ok){let j=await f.text();throw Error(`Upload part failed: ${f.status} ${j}`)}return{ETag:f.headers.get("etag")||""}}async completeMultipartUpload(e,t,s,r){let n=t.split("/").map((a)=>encodeURIComponent(a)).join("/"),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
71
|
+
<CompleteMultipartUpload>${r.sort((a,g)=>a.PartNumber-g.PartNumber).map((a)=>`<Part><PartNumber>${a.PartNumber}</PartNumber><ETag>${a.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${n}`,bucket:e,queryParams:{uploadId:s},headers:{"Content-Type":"application/xml"},body:o})}async abortMultipartUpload(e,t,s){let r=t.split("/").map((n)=>encodeURIComponent(n)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${r}`,bucket:e,queryParams:{uploadId:s}})}async listMultipartUploads(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:e,queryParams:{uploads:""}}),s=(t?.ListMultipartUploadsResult??t)?.Upload;if(!s)return[];return(Array.isArray(s)?s:[s]).map((n)=>({Key:n.Key,UploadId:n.UploadId,Initiated:n.Initiated}))}async restoreObject(e,t,s,r="Standard"){let n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
72
|
+
<RestoreRequest>
|
|
73
|
+
<Days>${s}</Days>
|
|
74
|
+
<GlacierJobParameters>
|
|
75
|
+
<Tier>${r}</Tier>
|
|
76
|
+
</GlacierJobParameters>
|
|
77
|
+
</RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:n})}async selectObjectContent(e,t,s,r,n="JSON"){let i="";if(r==="CSV")i="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(r==="JSON")i="<JSON><Type>DOCUMENT</Type></JSON>";else i="<Parquet/>";let o="";if(n==="CSV")o="<CSV/>";else o="<JSON/>";let a=`<?xml version="1.0" encoding="UTF-8"?>
|
|
78
|
+
<SelectObjectContentRequest>
|
|
79
|
+
<Expression>${s}</Expression>
|
|
80
|
+
<ExpressionType>SQL</ExpressionType>
|
|
81
|
+
<InputSerialization>${i}</InputSerialization>
|
|
82
|
+
<OutputSerialization>${o}</OutputSerialization>
|
|
83
|
+
</SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:a,rawResponse:!0})}async getSignedUrl(e){let{bucket:t,key:s,expiresIn:r=3600,operation:n="getObject"}=e,{accessKeyId:i,secretAccessKey:o,sessionToken:a}=this.getCredentials(),g=new Date,l=g.toISOString().replace(/[:-]|\.\d{3}/g,""),u=g.toISOString().slice(0,10).replace(/-/g,""),d=this.s3VirtualHost(t),y=n==="putObject"?"PUT":"GET",h="AWS4-HMAC-SHA256",S=`${u}/${this.region}/s3/aws4_request`,p={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${i}/${S}`,"X-Amz-Date":l,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"host"};if(a)p["X-Amz-Security-Token"]=a;let P=Object.keys(p).sort().map((I)=>`${encodeURIComponent(I)}=${encodeURIComponent(p[I])}`).join("&"),k=s.split("/").map((I)=>encodeURIComponent(I)).join("/"),b=this.objectPath(t,k),v=`host:${d}
|
|
84
|
+
`,E=[y,b,P,v,"host","UNSIGNED-PAYLOAD"].join(`
|
|
85
|
+
`),w=["AWS4-HMAC-SHA256",l,S,c.createHash("sha256").update(E).digest("hex")].join(`
|
|
86
|
+
`),x=c.createHmac("sha256",`AWS4${o}`).update(u).digest(),T=c.createHmac("sha256",x).update(this.region).digest(),A=c.createHmac("sha256",T).update("s3").digest(),f=c.createHmac("sha256",A).update("aws4_request").digest(),j=c.createHmac("sha256",f).update(w).digest("hex");return`${this.endpointProtocol}://${d}${b}?${P}&X-Amz-Signature=${j}`}async listObjects(e){let{bucket:t,prefix:s,maxKeys:r=1000,continuationToken:n}=e,i={"list-type":"2","max-keys":r.toString()};if(s)i.prefix=s;if(n)i["continuation-token"]=n;let o=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:i}),a=[],g=o?.ListBucketResult??o;if(g?.Contents){let l=Array.isArray(g.Contents)?g.Contents:[g.Contents];for(let u of l)a.push({Key:u.Key||"",LastModified:u.LastModified||"",Size:Number.parseInt(u.Size||"0"),ETag:u.ETag})}return{objects:a,nextContinuationToken:g?.NextContinuationToken}}async emptyBucket(e){let t=0,s=await this.listAllObjects({bucket:e});if(s.length>0)for(let r=0;r<s.length;r+=1000){let i=s.slice(r,r+1000).map((o)=>o.Key);await this.deleteObjects(e,i),t+=i.length}try{let r,n;do{let i=await this.listObjectVersions({bucket:e,keyMarker:r,versionIdMarker:n,maxKeys:1000}),o=[];if(i.versions)for(let a of i.versions)o.push({Key:a.Key,VersionId:a.VersionId});if(i.deleteMarkers)for(let a of i.deleteMarkers)o.push({Key:a.Key,VersionId:a.VersionId});if(o.length>0)await this.deleteObjectVersions(e,o),t+=o.length;r=i.nextKeyMarker,n=i.nextVersionIdMarker}while(r)}catch{}return{deletedCount:t}}async listObjectVersions(e){let{bucket:t,prefix:s,keyMarker:r,versionIdMarker:n,maxKeys:i=1000}=e,o={versions:"","max-keys":i.toString()};if(s)o.prefix=s;if(r)o["key-marker"]=r;if(n)o["version-id-marker"]=n;let a=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:o}),g=[],l=[];if(a.Version){let u=Array.isArray(a.Version)?a.Version:[a.Version];for(let d of u)g.push({Key:d.Key,VersionId:d.VersionId,IsLatest:d.IsLatest==="true"})}if(a.DeleteMarker){let u=Array.isArray(a.DeleteMarker)?a.DeleteMarker:[a.DeleteMarker];for(let d of u)l.push({Key:d.Key,VersionId:d.VersionId,IsLatest:d.IsLatest==="true"})}return{versions:g,deleteMarkers:l,nextKeyMarker:a.NextKeyMarker,nextVersionIdMarker:a.NextVersionIdMarker}}async deleteObjectVersions(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
87
|
+
<Delete>
|
|
88
|
+
<Quiet>true</Quiet>
|
|
89
|
+
${t.map((n)=>`<Object><Key>${n.Key}</Key>${n.VersionId?`<VersionId>${n.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
|
+
`)}
|
|
91
|
+
</Delete>`,r=c.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}}
|
|
92
|
+
export{R as Uh,V as Vh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Wh as a,Xh as b,Yh as c,Zh as d}from"./chunk-cp54a0qn.js";import"./chunk-77t2ctwn.js";export{b as AWSClient,c as buildQueryParams,d as detectCredentialSource,a as resolveS3Endpoint};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import{Xh as a}from"./chunk-cp54a0qn.js";class d{client;region;constructor(e="us-east-1"){this.region=e,this.client=new a}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
3
|
+
<Name>${e.Name}</Name>
|
|
4
|
+
<CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
|
|
5
|
+
<HostedZoneConfig>`,e.HostedZoneConfig.Comment)o+=`
|
|
6
|
+
<Comment>${e.HostedZoneConfig.Comment}</Comment>`;if(e.HostedZoneConfig.PrivateZone!==void 0)o+=`
|
|
7
|
+
<PrivateZone>${e.HostedZoneConfig.PrivateZone}</PrivateZone>`;o+=`
|
|
8
|
+
</HostedZoneConfig>`}if(e.VPC)o+=`
|
|
9
|
+
<VPC>
|
|
10
|
+
<VPCRegion>${e.VPC.VPCRegion}</VPCRegion>
|
|
11
|
+
<VPCId>${e.VPC.VPCId}</VPCId>
|
|
12
|
+
</VPC>`;if(e.DelegationSetId)o+=`
|
|
13
|
+
<DelegationSetId>${e.DelegationSetId}</DelegationSetId>`;o+=`
|
|
14
|
+
</CreateHostedZoneRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:"/2013-04-01/hostedzone",headers:{"content-type":"application/xml"},body:o});return this.parseCreateHostedZoneResponse(n)}async listHostedZones(e){let t={};if(e?.Marker)t.marker=e.Marker;if(e?.MaxItems)t.maxitems=e.MaxItems;let o=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzone",queryParams:Object.keys(t).length>0?t:void 0});return this.parseListHostedZonesResponse(o)}async listHostedZonesByName(e){let t={};if(e?.DNSName)t.dnsname=e.DNSName;if(e?.HostedZoneId)t.hostedzoneid=e.HostedZoneId;if(e?.MaxItems)t.maxitems=e.MaxItems;let o=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzonesbyname",queryParams:Object.keys(t).length>0?t:void 0});return this.parseListHostedZonesResponse(o)}async getHostedZone(e){let t=e.Id.replace("/hostedzone/",""),o=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${t}`});return this.parseGetHostedZoneResponse(o)}async deleteHostedZone(e){let t=e.Id.replace("/hostedzone/","");await this.client.request({service:"route53",region:this.region,method:"DELETE",path:`/2013-04-01/hostedzone/${t}`})}async listResourceRecordSets(e){let t=e.HostedZoneId.replace("/hostedzone/",""),o={};if(e.StartRecordName)o.name=e.StartRecordName;if(e.StartRecordType)o.type=e.StartRecordType;if(e.StartRecordIdentifier)o.identifier=e.StartRecordIdentifier;if(e.MaxItems)o.maxitems=e.MaxItems;let n=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${t}/rrset`,queryParams:Object.keys(o).length>0?o:void 0});return this.parseListResourceRecordSetsResponse(n)}async changeResourceRecordSets(e){let t=e.HostedZoneId.replace("/hostedzone/",""),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
15
|
+
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
16
|
+
<ChangeBatch>`;if(e.ChangeBatch.Comment)o+=`
|
|
17
|
+
<Comment>${this.escapeXml(e.ChangeBatch.Comment)}</Comment>`;o+=`
|
|
18
|
+
<Changes>`;for(let s of e.ChangeBatch.Changes){if(o+=`
|
|
19
|
+
<Change>
|
|
20
|
+
<Action>${s.Action}</Action>
|
|
21
|
+
<ResourceRecordSet>
|
|
22
|
+
<Name>${s.ResourceRecordSet.Name}</Name>
|
|
23
|
+
<Type>${s.ResourceRecordSet.Type}</Type>`,s.ResourceRecordSet.TTL!==void 0)o+=`
|
|
24
|
+
<TTL>${s.ResourceRecordSet.TTL}</TTL>`;if(s.ResourceRecordSet.SetIdentifier)o+=`
|
|
25
|
+
<SetIdentifier>${s.ResourceRecordSet.SetIdentifier}</SetIdentifier>`;if(s.ResourceRecordSet.Weight!==void 0)o+=`
|
|
26
|
+
<Weight>${s.ResourceRecordSet.Weight}</Weight>`;if(s.ResourceRecordSet.Region)o+=`
|
|
27
|
+
<Region>${s.ResourceRecordSet.Region}</Region>`;if(s.ResourceRecordSet.Failover)o+=`
|
|
28
|
+
<Failover>${s.ResourceRecordSet.Failover}</Failover>`;if(s.ResourceRecordSet.HealthCheckId)o+=`
|
|
29
|
+
<HealthCheckId>${s.ResourceRecordSet.HealthCheckId}</HealthCheckId>`;if(s.ResourceRecordSet.ResourceRecords&&s.ResourceRecordSet.ResourceRecords.length>0){o+=`
|
|
30
|
+
<ResourceRecords>`;for(let r of s.ResourceRecordSet.ResourceRecords)o+=`
|
|
31
|
+
<ResourceRecord>
|
|
32
|
+
<Value>${this.escapeXml(r.Value)}</Value>
|
|
33
|
+
</ResourceRecord>`;o+=`
|
|
34
|
+
</ResourceRecords>`}if(s.ResourceRecordSet.AliasTarget)o+=`
|
|
35
|
+
<AliasTarget>
|
|
36
|
+
<HostedZoneId>${s.ResourceRecordSet.AliasTarget.HostedZoneId}</HostedZoneId>
|
|
37
|
+
<DNSName>${s.ResourceRecordSet.AliasTarget.DNSName}</DNSName>
|
|
38
|
+
<EvaluateTargetHealth>${s.ResourceRecordSet.AliasTarget.EvaluateTargetHealth}</EvaluateTargetHealth>
|
|
39
|
+
</AliasTarget>`;if(s.ResourceRecordSet.GeoLocation){if(o+=`
|
|
40
|
+
<GeoLocation>`,s.ResourceRecordSet.GeoLocation.ContinentCode)o+=`
|
|
41
|
+
<ContinentCode>${s.ResourceRecordSet.GeoLocation.ContinentCode}</ContinentCode>`;if(s.ResourceRecordSet.GeoLocation.CountryCode)o+=`
|
|
42
|
+
<CountryCode>${s.ResourceRecordSet.GeoLocation.CountryCode}</CountryCode>`;if(s.ResourceRecordSet.GeoLocation.SubdivisionCode)o+=`
|
|
43
|
+
<SubdivisionCode>${s.ResourceRecordSet.GeoLocation.SubdivisionCode}</SubdivisionCode>`;o+=`
|
|
44
|
+
</GeoLocation>`}o+=`
|
|
45
|
+
</ResourceRecordSet>
|
|
46
|
+
</Change>`}o+=`
|
|
47
|
+
</Changes>
|
|
48
|
+
</ChangeBatch>
|
|
49
|
+
</ChangeResourceRecordSetsRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${t}/rrset`,headers:{"content-type":"application/xml"},body:o});return this.parseChangeResourceRecordSetsResponse(n)}escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse(e){let t=e.CreateHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(t.DelegationSet),Location:t.Location||""}}parseListHostedZonesResponse(e){let t=e.ListHostedZonesResponse||e.ListHostedZonesByNameResponse||e,o=t.HostedZones?.HostedZone||t.HostedZones||[];if(!Array.isArray(o))o=o?[o]:[];return{HostedZones:o.map((n)=>this.parseHostedZone(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",Marker:t.Marker,NextMarker:t.NextMarker}}parseGetHostedZoneResponse(e){let t=e.GetHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),DelegationSet:this.parseDelegationSet(t.DelegationSet),VPCs:t.VPCs?.VPC?Array.isArray(t.VPCs.VPC)?t.VPCs.VPC:[t.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(e){let t=e.ListResourceRecordSetsResponse||e,o=t.ResourceRecordSets?.ResourceRecordSet||t.ResourceRecordSets||[];if(!Array.isArray(o))o=o?[o]:[];return{ResourceRecordSets:o.map((n)=>this.parseResourceRecordSet(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",NextRecordName:t.NextRecordName,NextRecordType:t.NextRecordType,NextRecordIdentifier:t.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(e){let t=e.ChangeResourceRecordSetsResponse||e;return{ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||"",Comment:t.ChangeInfo?.Comment}}}parseHostedZone(e){if(!e)return{Id:"",Name:""};return{Id:e.Id||"",Name:e.Name||"",CallerReference:e.CallerReference,Config:e.Config?{Comment:e.Config.Comment,PrivateZone:e.Config.PrivateZone==="true"||e.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:e.ResourceRecordSetCount?Number(e.ResourceRecordSetCount):void 0}}parseDelegationSet(e){if(!e)return{NameServers:[]};let t=e.NameServers?.NameServer||e.NameServers||[];if(!Array.isArray(t))t=t?[t]:[];return{Id:e.Id,CallerReference:e.CallerReference,NameServers:t}}parseResourceRecordSet(e){if(!e)return{Name:"",Type:""};let t=e.ResourceRecords?.ResourceRecord||e.ResourceRecords||[];if(!Array.isArray(t))t=t?[t]:[];return{Name:e.Name||"",Type:e.Type||"",TTL:e.TTL?Number(e.TTL):void 0,ResourceRecords:t.map((o)=>({Value:o.Value||o})),AliasTarget:e.AliasTarget?{HostedZoneId:e.AliasTarget.HostedZoneId,DNSName:e.AliasTarget.DNSName,EvaluateTargetHealth:e.AliasTarget.EvaluateTargetHealth==="true"||e.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:e.SetIdentifier,Weight:e.Weight?Number(e.Weight):void 0,Region:e.Region,GeoLocation:e.GeoLocation,Failover:e.Failover,HealthCheckId:e.HealthCheckId}}async findHostedZoneByName(e){let t=e.endsWith(".")?e:`${e}.`;return(await this.listHostedZonesByName({DNSName:t})).HostedZones.find((s)=>s.Name===t)||null}async createARecord(e){let t=Array.isArray(e.Value)?e.Value:[e.Value];return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"A",TTL:e.TTL||300,ResourceRecords:t.map((o)=>({Value:o}))}}]}})}async createCnameRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"CNAME",TTL:e.TTL||300,ResourceRecords:[{Value:e.Value}]}}]}})}async createAliasRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:e.Type||"A",AliasTarget:{HostedZoneId:e.TargetHostedZoneId,DNSName:e.TargetDNSName,EvaluateTargetHealth:e.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(e){let o=(Array.isArray(e.Value)?e.Value:[e.Value]).map((n)=>{if(!n.startsWith('"'))return`"${n}"`;return n});return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"TXT",TTL:e.TTL||300,ResourceRecords:o.map((n)=>({Value:n}))}}]}})}async createMxRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"MX",TTL:e.TTL||300,ResourceRecords:e.Values.map((t)=>({Value:`${t.priority} ${t.mailServer}`}))}}]}})}async deleteRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:e.RecordSet}]}})}async waitForChange(e,t=60,o=5000){let n=e.replace("/change/","");for(let s=0;s<t;s++){let r=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${n}`});if((r.GetChangeResponse?.ChangeInfo?.Status||r.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((i)=>setTimeout(i,o))}return!1}async findOrCreateHostedZone(e){let t=e.domainName.endsWith(".")?e.domainName:`${e.domainName}.`,o=await this.findHostedZoneByName(t);if(o){let s=await this.getHostedZone({Id:o.Id});return{hostedZone:o,nameServers:s.DelegationSet.NameServers,isNew:!1}}let n=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:e.comment||`Hosted zone for ${e.domainName}`,PrivateZone:e.privateZone},VPC:e.vpc});return{hostedZone:n.HostedZone,nameServers:n.DelegationSet.NameServers,isNew:!0}}static getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length<=2)return e;return t.slice(-2).join(".")}async findHostedZoneForDomain(e){let o=e.replace(/\.$/,"").split(".");for(let n=0;n<o.length-1;n++){let s=o.slice(n).join("."),r=await this.findHostedZoneByName(s);if(r)return r}return null}async ensureHostedZone(e){let t=await this.findOrCreateHostedZone({domainName:e.domainName,comment:e.comment});return{hostedZoneId:t.hostedZone.Id.replace("/hostedzone/",""),nameServers:t.nameServers,isNew:t.isNew,action:t.isNew?"created":"found"}}async setupDomainDns(e){let{domain:t,createIfNotExists:o=!0}=e,n=await this.findHostedZoneByName(t);if(n){let r=await this.getHostedZone({Id:n.Id});return{success:!0,hostedZoneId:n.Id.replace("/hostedzone/",""),nameServers:r.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${t}`}}if(!o)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${t} and createIfNotExists is false`};let s=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${t}`}});return{success:!0,hostedZoneId:s.HostedZone.Id.replace("/hostedzone/",""),nameServers:s.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${t}. Please update your domain registrar with these name servers: ${s.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}
|
|
50
|
+
export{d as Tf};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var u={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},p={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function l(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function g(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function S(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let d=n.path?R(n.path):".*";if(!g(d)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let c=[`SecRule REQUEST_URI "@rx ${l(d)}"`];if(n.methods?.length)c.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);else c.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${l(n.id)}".`),t.push(c.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${l(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function R(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function v(e={},r=[]){let t=e.mode??u.mode,o=[],s=e.paranoiaLevel??u.paranoiaLevel,n=e.inboundThreshold??u.inboundThreshold,d=e.outboundThreshold??u.outboundThreshold,c=e.maxBodyBytes??u.maxBodyBytes,m=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!m)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${c}`,`SecRequestBodyNoFilesLimit ${Math.min(c,131072)}`,`SecRequestBodyLimitAction ${m?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${l(e.auditLogPath??u.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??u.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${d}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let f=p.bypassBase;for(let a of e.bypassPaths??[]){let x=R(a);if(!g(x)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${l(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${l(x)}" "id:${f},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),f++}let y=p.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${l(a.reason)}`),a.pathPattern){if(!g(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${l(a.pathPattern)}" "id:${y},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),y++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let h=S(r,p.rateLimitBase);if(h.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...h.lines);let b=p.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${b}.`,a.trim(),""),b++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??u.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`,unmappedRateLimits:h.unmapped,warnings:o,mode:t}}function I(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=v(e,r);return`#!/usr/bin/env bash
|
|
6
|
+
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
7
|
+
set -euo pipefail
|
|
8
|
+
|
|
9
|
+
if [ ! -x "${o}" ]; then
|
|
10
|
+
echo "ts-cloud: ${o} is not installed; skipping WAF configuration" >&2
|
|
11
|
+
exit 0
|
|
12
|
+
fi
|
|
13
|
+
|
|
14
|
+
install -d -m 0755 "$(dirname "${s}")"
|
|
15
|
+
install -d -m 0750 /var/log/ts-cloud
|
|
16
|
+
|
|
17
|
+
cat > "${s}.new" <<'WAF_EOF'
|
|
18
|
+
${n.config}WAF_EOF
|
|
19
|
+
|
|
20
|
+
# Compile the config before it goes live. A config that does not validate
|
|
21
|
+
# would leave the engine with no rules while still reporting itself enabled.
|
|
22
|
+
if ! "${o}" validate "${s}.new"; then
|
|
23
|
+
echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
|
|
24
|
+
rm -f "${s}.new"
|
|
25
|
+
exit 1
|
|
26
|
+
fi
|
|
27
|
+
|
|
28
|
+
if [ -f "${s}" ] && cmp -s "${s}.new" "${s}"; then
|
|
29
|
+
rm -f "${s}.new"
|
|
30
|
+
echo "ts-cloud: WAF config unchanged"
|
|
31
|
+
exit 0
|
|
32
|
+
fi
|
|
33
|
+
|
|
34
|
+
mv "${s}.new" "${s}"
|
|
35
|
+
echo "ts-cloud: WAF config installed (mode: ${n.mode})"
|
|
36
|
+
`}function _(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
|
|
37
|
+
export{l as jl,g as kl,R as ll,v as ml,I as nl,_ as ol};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ql as w}from"./chunk-cd0zpxhf.js";var L="\x00";function k(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function y(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function d(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!k(t.path,i.path))return!1;if(t.host&&!y(t.host,i.host??""))return!1;return!0}function m(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class A{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>d(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||p(s.action)>p(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!d(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function p(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function I(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function C(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var h="protection.controls",b=24,x=4,M={ipRules:{allow:[],block:[]}};function f(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function g(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(b,Math.max(0.25,e))}var R=500;class P{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(h);if(!t||typeof t!=="object"||Array.isArray(t))return{...M,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(h,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:f(i.attackMode,t),mitigationPause:f(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+g(t.hours,x)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+g(t.hours,b)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!w(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>R)throw Error(`At most ${R} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function D(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function E(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function T(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function v(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:T(o,i)}}}}export{L as Wk,k as Xk,d as Yk,m as Zk,A as _k,I as $k,C as al,h as bl,b as cl,x as dl,P as el,D as fl,E as gl,T as hl,v as il};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{Xh as g}from"./chunk-cp54a0qn.js";class l{client;region;constructor(e="us-east-1"){this.region=e,this.client=new g}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,n)=>{t[`InstanceId.${n+1}`]=s});if(e?.Filters)e.Filters.forEach((s,n)=>{t[`Filter.${n+1}.Name`]=s.Name,s.Values.forEach((i,o)=>{t[`Filter.${n+1}.Value.${o+1}`]=i})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
|
|
2
|
+
`).slice(-t.tailLines).join(`
|
|
3
|
+
`);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,n)=>{a[`InstanceId.${n+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((s,n)=>{t[`TagSpecification.${n+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((i,o)=>{t[`TagSpecification.${n+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${n+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(a.CreateImageResponse||a).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(a.vpcSet?.item).map((r)=>({VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((n,i)=>{t[`Filter.${s+1}.Value.${i+1}`]=n})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((n,i)=>{t[`TagSpecification.${s+1}.Tag.${i+1}.Key`]=n.Key,t[`TagSpecification.${s+1}.Tag.${i+1}.Value`]=n.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:a.allocationId,PublicIp:a.publicIp,Domain:a.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,n=Date.now();while(Date.now()-n<r){let i;try{i=await this.getInstance(e)}catch{i=void 0}if(i?.State?.Name===t)return i;await new Promise((o)=>setTimeout(o,s))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((n,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=n.ResourceType,n.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((n,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=n.ResourceType,n.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((s,n)=>{t[`TagSpecification.${n+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((i,o)=>{t[`TagSpecification.${n+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${n+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(a.CreateSecurityGroupResponse||a).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((s,n)=>{t[`RouteTableId.${n+1}`]=s});if(e?.Filters)e.Filters.forEach((s,n)=>{t[`Filter.${n+1}.Name`]=s.Name,s.Values.forEach((i,o)=>{t[`Filter.${n+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((n)=>({DestinationCidrBlock:n.destinationCidrBlock,GatewayId:n.gatewayId,NatGatewayId:n.natGatewayId,State:n.state})),Associations:this.parseArray(s.associationSet?.item).map((n)=>({RouteTableAssociationId:n.routeTableAssociationId,SubnetId:n.subnetId,Main:n.main==="true"||n.main===!0})),Tags:this.parseTags(s.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((s,n)=>{t[`NetworkInterfaceId.${n+1}`]=s});if(e?.Filters)e.Filters.forEach((s,n)=>{t[`Filter.${n+1}.Name`]=s.Name,s.Values.forEach((i,o)=>{t[`Filter.${n+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((s,n)=>{t[`SecurityGroupId.${n+1}`]=s});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((s,n)=>{t[`TagSpecification.${n+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((i,o)=>{t[`TagSpecification.${n+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${n+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((n,i)=>{if(n.CidrIp)e[`${s}.IpRanges.${i+1}.CidrIp`]=n.CidrIp;if(n.Description)e[`${s}.IpRanges.${i+1}.Description`]=n.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((n,i)=>{if(n.CidrIpv6)e[`${s}.Ipv6Ranges.${i+1}.CidrIpv6`]=n.CidrIpv6;if(n.Description)e[`${s}.Ipv6Ranges.${i+1}.Description`]=n.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((n,i)=>{if(n.GroupId)e[`${s}.Groups.${i+1}.GroupId`]=n.GroupId;if(n.UserId)e[`${s}.Groups.${i+1}.UserId`]=n.UserId;if(n.Description)e[`${s}.Groups.${i+1}.Description`]=n.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((a)=>({GroupId:a.groupId,GroupName:a.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new g}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,n=a?.maxWaitMs||300000,i=Date.now();while(Date.now()-i<n){await new Promise((o)=>setTimeout(o,s));try{let o=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(o.Status==="Success")return{success:!0,output:o.StandardOutputContent,error:o.StandardErrorContent,status:o.Status};if(o.Status==="Failed"||o.Status==="Cancelled"||o.Status==="TimedOut")return{success:!1,output:o.StandardOutputContent,error:o.StandardErrorContent||o.StatusDetails,status:o.Status}}catch(o){if(!o.message?.includes("InvocationDoesNotExist"))return{success:!1,error:o.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,u])=>({Key:`tag:${c}`,Values:[u]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,n=Date.now(),i=new Set(["Success","Failed","Cancelled","TimedOut"]),o=[];while(Date.now()-n<s){await new Promise((c)=>setTimeout(c,r));try{if(o=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),o.length===0)continue;if(o.every((u)=>i.has(u.Status||""))){let u=o.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),m=o.every((d)=>d.Status==="Success");return{success:m,instanceCount:o.length,perInstance:u,error:m?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:o.length,perInstance:o.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
|
|
4
|
+
export{l as Rh,p as Sh};
|
|
@@ -1,13 +1,9 @@
|
|
|
1
|
+
import type { ReachableResource } from '@ts-cloud/core';
|
|
1
2
|
/**
|
|
2
|
-
* The minimum a driver has to produce for a server to be attributed
|
|
3
|
-
*
|
|
4
|
-
* Structural rather than a provider type so a Hetzner server satisfies it as-is
|
|
5
|
-
* and another driver can satisfy it without importing anything.
|
|
3
|
+
* The minimum a driver has to produce for a server to be attributed — the shape
|
|
4
|
+
* `CloudDriver.listReachableResources()` returns.
|
|
6
5
|
*/
|
|
7
|
-
export
|
|
8
|
-
name: string;
|
|
9
|
-
labels?: Record<string, string>;
|
|
10
|
-
}
|
|
6
|
+
export type ReachableServer = ReachableResource;
|
|
11
7
|
export interface CredentialReach {
|
|
12
8
|
/** Every server the credential enumerated. */
|
|
13
9
|
total: number;
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ac as Z,Bc as
|
|
1
|
+
import{Ac as Z,Bc as aa,Cc as ba,Dc as ca,Ec as da,Fc as ea,Gc as fa,Hc as ga,Ic as ha,Jc as ia,Kc as ja,Lc as ka,Mc as la,Nc as ma,Oc as na,ic as y,jc as z,kc as A,lc as B,mc as C,nc as D,oc as E,od as oa,pc as O,pd as pa,qc as P,qd as qa,rc as Q,rd as ra,sc as R,tc as S,uc as T,vc as U,wc as V,xc as W,yc as X,zc as Y}from"../chunk-qh9ep11z.js";import{Ad as N,sd as F,td as G,ud as H,vd as I,wd as J,xd as K,yd as L,zd as M}from"../chunk-9a22225r.js";import{Id as _}from"../chunk-0e16qt6k.js";import"../chunk-88z37ey4.js";import"../chunk-13hxhzaz.js";import"../chunk-d67xbk4v.js";import"../chunk-dckz9xve.js";import"../chunk-8c4715hz.js";import"../chunk-2p89vt3b.js";import"../chunk-xd6w0c11.js";import{Ch as s,Dh as t,Eh as u,Fh as v,Gh as w,Hh as x,Uf as a,Vf as b,Wf as c,Xf as d,Yf as e,Zf as f,_f as g,fg as h,gg as i,hg as j,ig as k,jg as l,kg as m,lg as n,mg as o,ng as p,og as q,pg as r}from"../chunk-hhdx5k96.js";import"../chunk-zmxffmmq.js";import"../chunk-e1666vjv.js";import"../chunk-snak8s7m.js";import"../chunk-cp54a0qn.js";import"../chunk-kv2ztkp4.js";import"../chunk-xtwjt370.js";import"../chunk-cd0zpxhf.js";import"../chunk-06jk7ba9.js";import"../chunk-77t2ctwn.js";export{d as IPV6_EXCLUDED_HOST_LABELS,s as MANAGEMENT_DASHBOARD_SITE,Z as buildAndPushContainerImage,_ as buildAndPushServerlessImage,ba as buildFunctionEnv,x as buildManagementDashboardArtifact,ha as buildServerTopology,ia as buildServerlessTopology,ja as buildTopology,na as collectEgressMetrics,a as collectServerDnsDomains,Y as createContainerImageDependencies,T as createExistingStaticFullStackDependencies,P as createStaticApiOriginDependencies,pa as dashboardActions,t as dashboardCredentialsFile,C as dashboardPageRoutes,M as deleteStaticSite,V as deployExistingStaticFullStack,ca as deployServerlessApp,r as deployShipsFiles,O as deploySite,Q as deployStaticApiOrigin,J as deployStaticSite,N as deployStaticSiteFull,G as deployStaticSiteWithExternalDns,H as deployStaticSiteWithExternalDnsFull,la as egressReportMetrics,y as ensureDashboardActor,w as ensureManagementDashboard,W as estimateExistingStaticFullStackMonthlyCost,S as estimateStaticApiOriginMonthlyCost,ma as fetchEgressReport,U as generateExistingStaticFullStackTemplate,F as generateExternalDnsStaticSiteTemplate,I as generateStaticSiteTemplate,n as hasComputeConfigured,k as hasProxyUpstream,X as hashContainerContext,e as hostAcceptsIpv6,aa as infraEnvFromOutputs,z as initializeDashboardControlPlane,L as invalidateCache,i as isPhpSite,c as normalizePublicIpv6,f as reconcileAddressRecords,da as redeployServerlessApp,b as removeStaleServerAddressRecords,qa as resolveDashboardAction,u as resolveDashboardAuth,ka as resolveDashboardData,D as resolveLegacyDashboardRoute,j as resolveProxyUpstreams,l as resolveSiteDeployTarget,m as resolveSiteKind,v as resolveUiSource,ea as rollbackServerlessApp,E as routesForDashboard,ga as runRemoteCommand,oa as sanitizeCloudConfig,fa as setMaintenance,p as shipsARelease,q as shipsToBucket,h as siteInstallBase,ra as startLocalDashboardServer,A as synchronizeDashboardUsers,B as trackDashboardOperation,K as uploadStaticFiles,o as validateDeploymentConfig,g as verifyAddressRecord,R as verifyStaticApiOrigin};
|
package/dist/dns/cloudflare.d.ts
CHANGED
|
@@ -104,6 +104,33 @@ export declare class CloudflareProvider implements DnsProvider {
|
|
|
104
104
|
* List all domains (zones) managed by this Cloudflare account
|
|
105
105
|
*/
|
|
106
106
|
listDomains(): Promise<string[]>;
|
|
107
|
+
/**
|
|
108
|
+
* Create a zone in this account, or return the one already there.
|
|
109
|
+
*
|
|
110
|
+
* Idempotent on purpose. A zone migration is re-run far more often than it
|
|
111
|
+
* succeeds first time — a too-narrow token, a half-imported record set, a
|
|
112
|
+
* nameserver flip that has not propagated — and every one of those reruns
|
|
113
|
+
* would otherwise die on Cloudflare's "zone already exists" (code 1061)
|
|
114
|
+
* before reaching the import that actually needed fixing.
|
|
115
|
+
*
|
|
116
|
+
* `accountId` is required by the API for anything but a single-account token,
|
|
117
|
+
* so it falls back to {@link CloudflareProviderOptions.accountId} and fails
|
|
118
|
+
* loudly rather than letting Cloudflare pick an account for you.
|
|
119
|
+
*
|
|
120
|
+
* The returned `nameServers` are the pair the registrar has to be pointed at.
|
|
121
|
+
* They are assigned at creation and never change for the life of the zone, so
|
|
122
|
+
* they can be read once here and used to drive the registrar update.
|
|
123
|
+
*/
|
|
124
|
+
createZone(domain: string, options?: {
|
|
125
|
+
accountId?: string;
|
|
126
|
+
jumpStart?: boolean;
|
|
127
|
+
}): Promise<{
|
|
128
|
+
id: string;
|
|
129
|
+
name: string;
|
|
130
|
+
status: string;
|
|
131
|
+
nameServers: string[];
|
|
132
|
+
created: boolean;
|
|
133
|
+
}>;
|
|
107
134
|
/**
|
|
108
135
|
* Get zone details (Cloudflare-specific)
|
|
109
136
|
*/
|
package/dist/dns/godaddy.d.ts
CHANGED
|
@@ -49,7 +49,24 @@ export declare class GoDaddyProvider implements DnsProvider {
|
|
|
49
49
|
expires?: string;
|
|
50
50
|
} | null>;
|
|
51
51
|
/**
|
|
52
|
-
*
|
|
52
|
+
* Read the nameservers the REGISTRY has this domain delegated to.
|
|
53
|
+
*
|
|
54
|
+
* Note this is the delegation, not the zone's own `NS` records. The two can
|
|
55
|
+
* disagree — that is exactly the state a half-finished migration leaves
|
|
56
|
+
* behind — and only the delegation decides who actually answers queries.
|
|
57
|
+
*/
|
|
58
|
+
getNameServers(domain: string): Promise<string[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Delegate a domain to a different set of nameservers.
|
|
61
|
+
*
|
|
62
|
+
* This PATCHes the DOMAIN, which is the registrar operation that changes the
|
|
63
|
+
* delegation at the registry. The obvious-looking alternative —
|
|
64
|
+
* `PUT /v1/domains/{domain}/records/NS` — writes `NS` records into GoDaddy's
|
|
65
|
+
* own hosted zone instead. That call succeeds, returns 200, and changes
|
|
66
|
+
* nothing about who is authoritative: the registry still points at the old
|
|
67
|
+
* provider. For a migration whose whole purpose is the cutover, that is the
|
|
68
|
+
* worst possible failure, because every check short of an external `dig +trace`
|
|
69
|
+
* reports success.
|
|
53
70
|
*/
|
|
54
71
|
updateNameServers(domain: string, nameservers: string[]): Promise<boolean>;
|
|
55
72
|
/**
|
package/dist/dns/index.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export { CloudflareProvider } from './cloudflare';
|
|
|
9
9
|
export type { DeclaredRecord, DeclaredRecordInput, DeclaredRecordOutcome, DeclaredRecordsReport, } from './declared-records';
|
|
10
10
|
export { policyTag, qualifyName, reconcileDeclaredRecords, resolveDeclaredRecords, } from './declared-records';
|
|
11
11
|
export { Route53Provider } from './route53-adapter';
|
|
12
|
+
export type { MigratedRecord, SkippedRecord, ZoneMigrationPlan, ZoneMigrationReport, ZoneParityReport, } from './zone-migration';
|
|
13
|
+
export { applyZoneMigration, exportRoute53Zone, planZoneMigration, verifyZoneParity, } from './zone-migration';
|
|
12
14
|
export { UnifiedDnsValidator, createPorkbunValidator, createGoDaddyValidator, createRoute53Validator, } from './validator';
|
|
13
15
|
import type { DnsProvider, DnsProviderConfig } from './types';
|
|
14
16
|
/**
|
package/dist/dns/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Af as e,Bf as f,Cf as g,Df as h,Ef as i,Ff as j,Gf as k,Hf as l,If as m,Jf as n,Kf as o,Lf as p,Mf as q,vf as a,wf as b,xf as c,zf as d}from"../chunk-
|
|
1
|
+
import{Af as e,Bf as f,Cf as g,Df as h,Ef as i,Ff as j,Gf as k,Hf as l,If as m,Jf as n,Kf as o,Lf as p,Mf as q,Nf as r,Of as s,Pf as t,Qf as u,vf as a,wf as b,xf as c,zf as d}from"../chunk-2p89vt3b.js";import"../chunk-xd6w0c11.js";import"../chunk-cp54a0qn.js";import"../chunk-77t2ctwn.js";export{d as CloudflareProvider,t as DnsProviderFactory,c as GoDaddyProvider,a as PROXIABLE_RECORD_TYPES,b as PorkbunProvider,i as Route53Provider,n as UnifiedDnsValidator,l as applyZoneMigration,r as createDnsProvider,p as createGoDaddyValidator,o as createPorkbunValidator,q as createRoute53Validator,s as detectDnsProvider,u as dnsProviders,j as exportRoute53Zone,k as planZoneMigration,e as policyTag,f as qualifyName,h as reconcileDeclaredRecords,g as resolveDeclaredRecords,m as verifyZoneParity};
|